1 /*
2 * Copyright (C) 2015 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 <gtest/gtest.h>
18
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <unistd.h>
22
23 #include <filesystem>
24 #include <map>
25 #include <memory>
26 #include <regex>
27 #include <thread>
28
29 #include <android-base/file.h>
30 #include <android-base/logging.h>
31 #include <android-base/properties.h>
32 #include <android-base/stringprintf.h>
33 #include <android-base/strings.h>
34 #include <android-base/test_utils.h>
35
36 #include "ETMRecorder.h"
37 #include "ProbeEvents.h"
38 #include "cmd_record_impl.h"
39 #include "command.h"
40 #include "environment.h"
41 #include "event_selection_set.h"
42 #include "get_test_data.h"
43 #include "kallsyms.h"
44 #include "record.h"
45 #include "record_file.h"
46 #include "test_util.h"
47 #include "thread_tree.h"
48
49 using android::base::Realpath;
50 using android::base::StringPrintf;
51 using namespace simpleperf;
52 using namespace PerfFileFormat;
53 namespace fs = std::filesystem;
54
RecordCmd()55 static std::unique_ptr<Command> RecordCmd() {
56 return CreateCommandInstance("record");
57 }
58
GetDefaultEvent()59 static const char* GetDefaultEvent() {
60 return HasHardwareCounter() ? "cpu-cycles" : "task-clock";
61 }
62
RunRecordCmd(std::vector<std::string> v,const char * output_file=nullptr)63 static bool RunRecordCmd(std::vector<std::string> v, const char* output_file = nullptr) {
64 bool has_event = false;
65 for (auto& arg : v) {
66 if (arg == "-e" || arg == "--group") {
67 has_event = true;
68 break;
69 }
70 }
71 if (!has_event) {
72 v.insert(v.end(), {"-e", GetDefaultEvent()});
73 }
74
75 std::unique_ptr<TemporaryFile> tmpfile;
76 std::string out_file;
77 if (output_file != nullptr) {
78 out_file = output_file;
79 } else {
80 tmpfile.reset(new TemporaryFile);
81 out_file = tmpfile->path;
82 }
83 v.insert(v.end(), {"-o", out_file, "sleep", SLEEP_SEC});
84 return RecordCmd()->Run(v);
85 }
86
TEST(record_cmd,no_options)87 TEST(record_cmd, no_options) {
88 ASSERT_TRUE(RunRecordCmd({}));
89 }
90
TEST(record_cmd,system_wide_option)91 TEST(record_cmd, system_wide_option) {
92 TEST_IN_ROOT(ASSERT_TRUE(RunRecordCmd({"-a"})));
93 }
94
CheckEventType(const std::string & record_file,const std::string & event_type,uint64_t sample_period,uint64_t sample_freq)95 static void CheckEventType(const std::string& record_file, const std::string& event_type,
96 uint64_t sample_period, uint64_t sample_freq) {
97 const EventType* type = FindEventTypeByName(event_type);
98 ASSERT_TRUE(type != nullptr);
99 std::unique_ptr<RecordFileReader> reader = RecordFileReader::CreateInstance(record_file);
100 ASSERT_TRUE(reader);
101 std::vector<EventAttrWithId> attrs = reader->AttrSection();
102 for (auto& attr : attrs) {
103 if (attr.attr->type == type->type && attr.attr->config == type->config) {
104 if (attr.attr->freq == 0) {
105 ASSERT_EQ(sample_period, attr.attr->sample_period);
106 ASSERT_EQ(sample_freq, 0u);
107 } else {
108 ASSERT_EQ(sample_period, 0u);
109 ASSERT_EQ(sample_freq, attr.attr->sample_freq);
110 }
111 return;
112 }
113 }
114 FAIL();
115 }
116
TEST(record_cmd,sample_period_option)117 TEST(record_cmd, sample_period_option) {
118 TemporaryFile tmpfile;
119 ASSERT_TRUE(RunRecordCmd({"-c", "100000"}, tmpfile.path));
120 CheckEventType(tmpfile.path, GetDefaultEvent(), 100000u, 0);
121 }
122
TEST(record_cmd,event_option)123 TEST(record_cmd, event_option) {
124 ASSERT_TRUE(RunRecordCmd({"-e", "cpu-clock"}));
125 }
126
TEST(record_cmd,freq_option)127 TEST(record_cmd, freq_option) {
128 TemporaryFile tmpfile;
129 ASSERT_TRUE(RunRecordCmd({"-f", "99"}, tmpfile.path));
130 CheckEventType(tmpfile.path, GetDefaultEvent(), 0, 99u);
131 ASSERT_TRUE(RunRecordCmd({"-e", "cpu-clock", "-f", "99"}, tmpfile.path));
132 CheckEventType(tmpfile.path, "cpu-clock", 0, 99u);
133 ASSERT_FALSE(RunRecordCmd({"-f", std::to_string(UINT_MAX)}));
134 }
135
TEST(record_cmd,multiple_freq_or_sample_period_option)136 TEST(record_cmd, multiple_freq_or_sample_period_option) {
137 TemporaryFile tmpfile;
138 ASSERT_TRUE(RunRecordCmd({"-f", "99", "-e", "task-clock", "-c", "1000000", "-e", "cpu-clock"},
139 tmpfile.path));
140 CheckEventType(tmpfile.path, "task-clock", 0, 99u);
141 CheckEventType(tmpfile.path, "cpu-clock", 1000000u, 0u);
142 }
143
TEST(record_cmd,output_file_option)144 TEST(record_cmd, output_file_option) {
145 TemporaryFile tmpfile;
146 ASSERT_TRUE(RecordCmd()->Run({"-o", tmpfile.path, "-e", GetDefaultEvent(), "sleep", SLEEP_SEC}));
147 }
148
TEST(record_cmd,dump_kernel_mmap)149 TEST(record_cmd, dump_kernel_mmap) {
150 TemporaryFile tmpfile;
151 ASSERT_TRUE(RunRecordCmd({}, tmpfile.path));
152 std::unique_ptr<RecordFileReader> reader = RecordFileReader::CreateInstance(tmpfile.path);
153 ASSERT_TRUE(reader != nullptr);
154 std::vector<std::unique_ptr<Record>> records = reader->DataSection();
155 ASSERT_GT(records.size(), 0U);
156 bool have_kernel_mmap = false;
157 for (auto& record : records) {
158 if (record->type() == PERF_RECORD_MMAP) {
159 const MmapRecord* mmap_record = static_cast<const MmapRecord*>(record.get());
160 if (android::base::StartsWith(mmap_record->filename, DEFAULT_KERNEL_MMAP_NAME)) {
161 have_kernel_mmap = true;
162 break;
163 }
164 }
165 }
166 ASSERT_TRUE(have_kernel_mmap);
167 }
168
TEST(record_cmd,dump_build_id_feature)169 TEST(record_cmd, dump_build_id_feature) {
170 TemporaryFile tmpfile;
171 ASSERT_TRUE(RunRecordCmd({}, tmpfile.path));
172 std::unique_ptr<RecordFileReader> reader = RecordFileReader::CreateInstance(tmpfile.path);
173 ASSERT_TRUE(reader != nullptr);
174 const FileHeader& file_header = reader->FileHeader();
175 ASSERT_TRUE(file_header.features[FEAT_BUILD_ID / 8] & (1 << (FEAT_BUILD_ID % 8)));
176 ASSERT_GT(reader->FeatureSectionDescriptors().size(), 0u);
177 }
178
TEST(record_cmd,tracepoint_event)179 TEST(record_cmd, tracepoint_event) {
180 TEST_IN_ROOT(ASSERT_TRUE(RunRecordCmd({"-a", "-e", "sched:sched_switch"})));
181 }
182
TEST(record_cmd,rN_event)183 TEST(record_cmd, rN_event) {
184 TEST_REQUIRE_HW_COUNTER();
185 OMIT_TEST_ON_NON_NATIVE_ABIS();
186 size_t event_number;
187 if (GetBuildArch() == ARCH_ARM64 || GetBuildArch() == ARCH_ARM) {
188 // As in D5.10.2 of the ARMv8 manual, ARM defines the event number space for PMU. part of the
189 // space is for common event numbers (which will stay the same for all ARM chips), part of the
190 // space is for implementation defined events. Here 0x08 is a common event for instructions.
191 event_number = 0x08;
192 } else if (GetBuildArch() == ARCH_X86_32 || GetBuildArch() == ARCH_X86_64) {
193 // As in volume 3 chapter 19 of the Intel manual, 0x00c0 is the event number for instruction.
194 event_number = 0x00c0;
195 } else {
196 GTEST_LOG_(INFO) << "Omit arch " << GetBuildArch();
197 return;
198 }
199 std::string event_name = android::base::StringPrintf("r%zx", event_number);
200 TemporaryFile tmpfile;
201 ASSERT_TRUE(RunRecordCmd({"-e", event_name}, tmpfile.path));
202 std::unique_ptr<RecordFileReader> reader = RecordFileReader::CreateInstance(tmpfile.path);
203 ASSERT_TRUE(reader);
204 std::vector<EventAttrWithId> attrs = reader->AttrSection();
205 ASSERT_EQ(1u, attrs.size());
206 ASSERT_EQ(PERF_TYPE_RAW, attrs[0].attr->type);
207 ASSERT_EQ(event_number, attrs[0].attr->config);
208 }
209
TEST(record_cmd,branch_sampling)210 TEST(record_cmd, branch_sampling) {
211 TEST_REQUIRE_HW_COUNTER();
212 if (IsBranchSamplingSupported()) {
213 ASSERT_TRUE(RunRecordCmd({"-b"}));
214 ASSERT_TRUE(RunRecordCmd({"-j", "any,any_call,any_ret,ind_call"}));
215 ASSERT_TRUE(RunRecordCmd({"-j", "any,k"}));
216 ASSERT_TRUE(RunRecordCmd({"-j", "any,u"}));
217 ASSERT_FALSE(RunRecordCmd({"-j", "u"}));
218 } else {
219 GTEST_LOG_(INFO) << "This test does nothing as branch stack sampling is "
220 "not supported on this device.";
221 }
222 }
223
TEST(record_cmd,event_modifier)224 TEST(record_cmd, event_modifier) {
225 ASSERT_TRUE(RunRecordCmd({"-e", GetDefaultEvent() + std::string(":u")}));
226 }
227
TEST(record_cmd,fp_callchain_sampling)228 TEST(record_cmd, fp_callchain_sampling) {
229 ASSERT_TRUE(RunRecordCmd({"--call-graph", "fp"}));
230 }
231
TEST(record_cmd,fp_callchain_sampling_warning_on_arm)232 TEST(record_cmd, fp_callchain_sampling_warning_on_arm) {
233 if (GetBuildArch() != ARCH_ARM) {
234 GTEST_LOG_(INFO) << "This test does nothing as it only tests on arm arch.";
235 return;
236 }
237 ASSERT_EXIT(
238 {
239 exit(RunRecordCmd({"--call-graph", "fp"}) ? 0 : 1);
240 },
241 testing::ExitedWithCode(0), "doesn't work well on arm");
242 }
243
TEST(record_cmd,system_wide_fp_callchain_sampling)244 TEST(record_cmd, system_wide_fp_callchain_sampling) {
245 TEST_IN_ROOT(ASSERT_TRUE(RunRecordCmd({"-a", "--call-graph", "fp"})));
246 }
247
TEST(record_cmd,dwarf_callchain_sampling)248 TEST(record_cmd, dwarf_callchain_sampling) {
249 OMIT_TEST_ON_NON_NATIVE_ABIS();
250 ASSERT_TRUE(IsDwarfCallChainSamplingSupported());
251 std::vector<std::unique_ptr<Workload>> workloads;
252 CreateProcesses(1, &workloads);
253 std::string pid = std::to_string(workloads[0]->GetPid());
254 ASSERT_TRUE(RunRecordCmd({"-p", pid, "--call-graph", "dwarf"}));
255 ASSERT_TRUE(RunRecordCmd({"-p", pid, "--call-graph", "dwarf,16384"}));
256 ASSERT_FALSE(RunRecordCmd({"-p", pid, "--call-graph", "dwarf,65536"}));
257 ASSERT_TRUE(RunRecordCmd({"-p", pid, "-g"}));
258 }
259
TEST(record_cmd,system_wide_dwarf_callchain_sampling)260 TEST(record_cmd, system_wide_dwarf_callchain_sampling) {
261 OMIT_TEST_ON_NON_NATIVE_ABIS();
262 ASSERT_TRUE(IsDwarfCallChainSamplingSupported());
263 TEST_IN_ROOT(RunRecordCmd({"-a", "--call-graph", "dwarf"}));
264 }
265
TEST(record_cmd,no_unwind_option)266 TEST(record_cmd, no_unwind_option) {
267 OMIT_TEST_ON_NON_NATIVE_ABIS();
268 ASSERT_TRUE(IsDwarfCallChainSamplingSupported());
269 ASSERT_TRUE(RunRecordCmd({"--call-graph", "dwarf", "--no-unwind"}));
270 ASSERT_FALSE(RunRecordCmd({"--no-unwind"}));
271 }
272
TEST(record_cmd,post_unwind_option)273 TEST(record_cmd, post_unwind_option) {
274 OMIT_TEST_ON_NON_NATIVE_ABIS();
275 ASSERT_TRUE(IsDwarfCallChainSamplingSupported());
276 std::vector<std::unique_ptr<Workload>> workloads;
277 CreateProcesses(1, &workloads);
278 std::string pid = std::to_string(workloads[0]->GetPid());
279 ASSERT_TRUE(RunRecordCmd({"-p", pid, "--call-graph", "dwarf", "--post-unwind"}));
280 ASSERT_TRUE(RunRecordCmd({"-p", pid, "--call-graph", "dwarf", "--post-unwind=yes"}));
281 ASSERT_TRUE(RunRecordCmd({"-p", pid, "--call-graph", "dwarf", "--post-unwind=no"}));
282 }
283
TEST(record_cmd,existing_processes)284 TEST(record_cmd, existing_processes) {
285 std::vector<std::unique_ptr<Workload>> workloads;
286 CreateProcesses(2, &workloads);
287 std::string pid_list =
288 android::base::StringPrintf("%d,%d", workloads[0]->GetPid(), workloads[1]->GetPid());
289 ASSERT_TRUE(RunRecordCmd({"-p", pid_list}));
290 }
291
TEST(record_cmd,existing_threads)292 TEST(record_cmd, existing_threads) {
293 std::vector<std::unique_ptr<Workload>> workloads;
294 CreateProcesses(2, &workloads);
295 // Process id can also be used as thread id in linux.
296 std::string tid_list =
297 android::base::StringPrintf("%d,%d", workloads[0]->GetPid(), workloads[1]->GetPid());
298 ASSERT_TRUE(RunRecordCmd({"-t", tid_list}));
299 }
300
TEST(record_cmd,no_monitored_threads)301 TEST(record_cmd, no_monitored_threads) {
302 TemporaryFile tmpfile;
303 ASSERT_FALSE(RecordCmd()->Run({"-o", tmpfile.path}));
304 ASSERT_FALSE(RecordCmd()->Run({"-o", tmpfile.path, ""}));
305 }
306
TEST(record_cmd,more_than_one_event_types)307 TEST(record_cmd, more_than_one_event_types) {
308 ASSERT_TRUE(RunRecordCmd({"-e", "task-clock,cpu-clock"}));
309 ASSERT_TRUE(RunRecordCmd({"-e", "task-clock", "-e", "cpu-clock"}));
310 }
311
TEST(record_cmd,mmap_page_option)312 TEST(record_cmd, mmap_page_option) {
313 ASSERT_TRUE(RunRecordCmd({"-m", "1"}));
314 ASSERT_FALSE(RunRecordCmd({"-m", "0"}));
315 ASSERT_FALSE(RunRecordCmd({"-m", "7"}));
316 }
317
CheckKernelSymbol(const std::string & path,bool need_kallsyms,bool * success)318 static void CheckKernelSymbol(const std::string& path, bool need_kallsyms, bool* success) {
319 *success = false;
320 std::unique_ptr<RecordFileReader> reader = RecordFileReader::CreateInstance(path);
321 ASSERT_TRUE(reader != nullptr);
322 std::vector<std::unique_ptr<Record>> records = reader->DataSection();
323 bool has_kernel_symbol_records = false;
324 for (const auto& record : records) {
325 if (record->type() == SIMPLE_PERF_RECORD_KERNEL_SYMBOL) {
326 has_kernel_symbol_records = true;
327 }
328 }
329 std::string kallsyms;
330 bool require_kallsyms = need_kallsyms && LoadKernelSymbols(&kallsyms);
331 ASSERT_EQ(require_kallsyms, has_kernel_symbol_records);
332 *success = true;
333 }
334
TEST(record_cmd,kernel_symbol)335 TEST(record_cmd, kernel_symbol) {
336 TemporaryFile tmpfile;
337 ASSERT_TRUE(RunRecordCmd({"--no-dump-symbols"}, tmpfile.path));
338 bool success;
339 CheckKernelSymbol(tmpfile.path, true, &success);
340 ASSERT_TRUE(success);
341 ASSERT_TRUE(RunRecordCmd({"--no-dump-symbols", "--no-dump-kernel-symbols"}, tmpfile.path));
342 CheckKernelSymbol(tmpfile.path, false, &success);
343 ASSERT_TRUE(success);
344 }
345
ProcessSymbolsInPerfDataFile(const std::string & perf_data_file,const std::function<bool (const Symbol &,uint32_t)> & callback)346 static void ProcessSymbolsInPerfDataFile(
347 const std::string& perf_data_file,
348 const std::function<bool(const Symbol&, uint32_t)>& callback) {
349 auto reader = RecordFileReader::CreateInstance(perf_data_file);
350 ASSERT_TRUE(reader);
351 FileFeature file;
352 size_t read_pos = 0;
353 while (reader->ReadFileFeature(read_pos, &file)) {
354 for (const auto& symbol : file.symbols) {
355 if (callback(symbol, file.type)) {
356 return;
357 }
358 }
359 }
360 }
361
362 // Check if dumped symbols in perf.data matches our expectation.
CheckDumpedSymbols(const std::string & path,bool allow_dumped_symbols)363 static bool CheckDumpedSymbols(const std::string& path, bool allow_dumped_symbols) {
364 bool has_dumped_symbols = false;
365 auto callback = [&](const Symbol&, uint32_t) {
366 has_dumped_symbols = true;
367 return true;
368 };
369 ProcessSymbolsInPerfDataFile(path, callback);
370 // It is possible that there are no samples hitting functions having symbols.
371 // So "allow_dumped_symbols = true" doesn't guarantee "has_dumped_symbols = true".
372 if (!allow_dumped_symbols && has_dumped_symbols) {
373 return false;
374 }
375 return true;
376 }
377
TEST(record_cmd,no_dump_symbols)378 TEST(record_cmd, no_dump_symbols) {
379 TemporaryFile tmpfile;
380 ASSERT_TRUE(RunRecordCmd({}, tmpfile.path));
381 ASSERT_TRUE(CheckDumpedSymbols(tmpfile.path, true));
382 ASSERT_TRUE(RunRecordCmd({"--no-dump-symbols", "--no-dump-kernel-symbols"}, tmpfile.path));
383 ASSERT_TRUE(CheckDumpedSymbols(tmpfile.path, false));
384 OMIT_TEST_ON_NON_NATIVE_ABIS();
385 ASSERT_TRUE(IsDwarfCallChainSamplingSupported());
386 std::vector<std::unique_ptr<Workload>> workloads;
387 CreateProcesses(1, &workloads);
388 std::string pid = std::to_string(workloads[0]->GetPid());
389 ASSERT_TRUE(RunRecordCmd({"-p", pid, "-g"}, tmpfile.path));
390 ASSERT_TRUE(CheckDumpedSymbols(tmpfile.path, true));
391 ASSERT_TRUE(RunRecordCmd({"-p", pid, "-g", "--no-dump-symbols", "--no-dump-kernel-symbols"},
392 tmpfile.path));
393 ASSERT_TRUE(CheckDumpedSymbols(tmpfile.path, false));
394 }
395
TEST(record_cmd,dump_kernel_symbols)396 TEST(record_cmd, dump_kernel_symbols) {
397 TEST_REQUIRE_ROOT();
398 TemporaryFile tmpfile;
399 ASSERT_TRUE(RecordCmd()->Run({"-a", "-o", tmpfile.path, "-e", GetDefaultEvent(), "sleep", "1"}));
400 bool has_kernel_symbols = false;
401 auto callback = [&](const Symbol&, uint32_t file_type) {
402 if (file_type == DSO_KERNEL) {
403 has_kernel_symbols = true;
404 }
405 return has_kernel_symbols;
406 };
407 ProcessSymbolsInPerfDataFile(tmpfile.path, callback);
408 ASSERT_TRUE(has_kernel_symbols);
409 }
410
TEST(record_cmd,group_option)411 TEST(record_cmd, group_option) {
412 ASSERT_TRUE(RunRecordCmd({"--group", "task-clock,cpu-clock", "-m", "16"}));
413 ASSERT_TRUE(
414 RunRecordCmd({"--group", "task-clock,cpu-clock", "--group", "task-clock:u,cpu-clock:u",
415 "--group", "task-clock:k,cpu-clock:k", "-m", "16"}));
416 }
417
TEST(record_cmd,symfs_option)418 TEST(record_cmd, symfs_option) {
419 ASSERT_TRUE(RunRecordCmd({"--symfs", "/"}));
420 }
421
TEST(record_cmd,duration_option)422 TEST(record_cmd, duration_option) {
423 TemporaryFile tmpfile;
424 ASSERT_TRUE(RecordCmd()->Run({"--duration", "1.2", "-p", std::to_string(getpid()), "-o",
425 tmpfile.path, "--in-app", "-e", GetDefaultEvent()}));
426 ASSERT_TRUE(RecordCmd()->Run(
427 {"--duration", "1", "-o", tmpfile.path, "-e", GetDefaultEvent(), "sleep", "2"}));
428 }
429
TEST(record_cmd,support_modifier_for_clock_events)430 TEST(record_cmd, support_modifier_for_clock_events) {
431 for (const std::string& e : {"cpu-clock", "task-clock"}) {
432 for (const std::string& m : {"u", "k"}) {
433 ASSERT_TRUE(RunRecordCmd({"-e", e + ":" + m})) << "event " << e << ":" << m;
434 }
435 }
436 }
437
TEST(record_cmd,handle_SIGHUP)438 TEST(record_cmd, handle_SIGHUP) {
439 TemporaryFile tmpfile;
440 int pipefd[2];
441 ASSERT_EQ(0, pipe(pipefd));
442 int read_fd = pipefd[0];
443 int write_fd = pipefd[1];
444 char data[8] = {};
445 std::thread thread([&]() {
446 android::base::ReadFully(read_fd, data, 7);
447 kill(getpid(), SIGHUP);
448 });
449 ASSERT_TRUE(
450 RecordCmd()->Run({"-o", tmpfile.path, "--start_profiling_fd", std::to_string(write_fd), "-e",
451 GetDefaultEvent(), "sleep", "1000000"}));
452 thread.join();
453 close(write_fd);
454 close(read_fd);
455 ASSERT_STREQ(data, "STARTED");
456 }
457
TEST(record_cmd,stop_when_no_more_targets)458 TEST(record_cmd, stop_when_no_more_targets) {
459 TemporaryFile tmpfile;
460 std::atomic<int> tid(0);
461 std::thread thread([&]() {
462 tid = gettid();
463 sleep(1);
464 });
465 thread.detach();
466 while (tid == 0)
467 ;
468 ASSERT_TRUE(RecordCmd()->Run(
469 {"-o", tmpfile.path, "-t", std::to_string(tid), "--in-app", "-e", GetDefaultEvent()}));
470 }
471
TEST(record_cmd,donot_stop_when_having_targets)472 TEST(record_cmd, donot_stop_when_having_targets) {
473 std::vector<std::unique_ptr<Workload>> workloads;
474 CreateProcesses(1, &workloads);
475 std::string pid = std::to_string(workloads[0]->GetPid());
476 uint64_t start_time_in_ns = GetSystemClock();
477 TemporaryFile tmpfile;
478 ASSERT_TRUE(RecordCmd()->Run(
479 {"-o", tmpfile.path, "-p", pid, "--duration", "3", "-e", GetDefaultEvent()}));
480 uint64_t end_time_in_ns = GetSystemClock();
481 ASSERT_GT(end_time_in_ns - start_time_in_ns, static_cast<uint64_t>(2e9));
482 }
483
TEST(record_cmd,start_profiling_fd_option)484 TEST(record_cmd, start_profiling_fd_option) {
485 int pipefd[2];
486 ASSERT_EQ(0, pipe(pipefd));
487 int read_fd = pipefd[0];
488 int write_fd = pipefd[1];
489 ASSERT_EXIT(
490 {
491 close(read_fd);
492 exit(RunRecordCmd({"--start_profiling_fd", std::to_string(write_fd)}) ? 0 : 1);
493 },
494 testing::ExitedWithCode(0), "");
495 close(write_fd);
496 std::string s;
497 ASSERT_TRUE(android::base::ReadFdToString(read_fd, &s));
498 close(read_fd);
499 ASSERT_EQ("STARTED", s);
500 }
501
TEST(record_cmd,record_meta_info_feature)502 TEST(record_cmd, record_meta_info_feature) {
503 TemporaryFile tmpfile;
504 ASSERT_TRUE(RunRecordCmd({}, tmpfile.path));
505 std::unique_ptr<RecordFileReader> reader = RecordFileReader::CreateInstance(tmpfile.path);
506 ASSERT_TRUE(reader);
507 auto& info_map = reader->GetMetaInfoFeature();
508 ASSERT_NE(info_map.find("simpleperf_version"), info_map.end());
509 ASSERT_NE(info_map.find("timestamp"), info_map.end());
510 #if defined(__ANDROID__)
511 ASSERT_NE(info_map.find("product_props"), info_map.end());
512 ASSERT_NE(info_map.find("android_version"), info_map.end());
513 #endif
514 }
515
516 // See http://b/63135835.
TEST(record_cmd,cpu_clock_for_a_long_time)517 TEST(record_cmd, cpu_clock_for_a_long_time) {
518 std::vector<std::unique_ptr<Workload>> workloads;
519 CreateProcesses(1, &workloads);
520 std::string pid = std::to_string(workloads[0]->GetPid());
521 TemporaryFile tmpfile;
522 ASSERT_TRUE(
523 RecordCmd()->Run({"-e", "cpu-clock", "-o", tmpfile.path, "-p", pid, "--duration", "3"}));
524 }
525
TEST(record_cmd,dump_regs_for_tracepoint_events)526 TEST(record_cmd, dump_regs_for_tracepoint_events) {
527 TEST_REQUIRE_HOST_ROOT();
528 TEST_REQUIRE_TRACEPOINT_EVENTS();
529 OMIT_TEST_ON_NON_NATIVE_ABIS();
530 // Check if the kernel can dump registers for tracepoint events.
531 // If not, probably a kernel patch below is missing:
532 // "5b09a094f2 arm64: perf: Fix callchain parse error with kernel tracepoint events"
533 ASSERT_TRUE(IsDumpingRegsForTracepointEventsSupported());
534 }
535
TEST(record_cmd,trace_offcpu_option)536 TEST(record_cmd, trace_offcpu_option) {
537 // On linux host, we need root privilege to read tracepoint events.
538 TEST_REQUIRE_HOST_ROOT();
539 TEST_REQUIRE_TRACEPOINT_EVENTS();
540 OMIT_TEST_ON_NON_NATIVE_ABIS();
541 TemporaryFile tmpfile;
542 ASSERT_TRUE(RunRecordCmd({"--trace-offcpu", "-f", "1000"}, tmpfile.path));
543 CheckEventType(tmpfile.path, "sched:sched_switch", 1u, 0u);
544 std::unique_ptr<RecordFileReader> reader = RecordFileReader::CreateInstance(tmpfile.path);
545 ASSERT_TRUE(reader);
546 auto info_map = reader->GetMetaInfoFeature();
547 ASSERT_EQ(info_map["trace_offcpu"], "true");
548 // Release recording environment in perf.data, to avoid affecting tests below.
549 reader.reset();
550
551 // --trace-offcpu only works with cpu-clock, task-clock and cpu-cycles. cpu-cycles has been
552 // tested above.
553 ASSERT_TRUE(RunRecordCmd({"--trace-offcpu", "-e", "cpu-clock"}));
554 ASSERT_TRUE(RunRecordCmd({"--trace-offcpu", "-e", "task-clock"}));
555 ASSERT_FALSE(RunRecordCmd({"--trace-offcpu", "-e", "page-faults"}));
556 // --trace-offcpu doesn't work with more than one event.
557 ASSERT_FALSE(RunRecordCmd({"--trace-offcpu", "-e", "cpu-clock,task-clock"}));
558 }
559
TEST(record_cmd,exit_with_parent_option)560 TEST(record_cmd, exit_with_parent_option) {
561 ASSERT_TRUE(RunRecordCmd({"--exit-with-parent"}));
562 }
563
TEST(record_cmd,clockid_option)564 TEST(record_cmd, clockid_option) {
565 if (!IsSettingClockIdSupported()) {
566 ASSERT_FALSE(RunRecordCmd({"--clockid", "monotonic"}));
567 } else {
568 TemporaryFile tmpfile;
569 ASSERT_TRUE(RunRecordCmd({"--clockid", "monotonic"}, tmpfile.path));
570 std::unique_ptr<RecordFileReader> reader = RecordFileReader::CreateInstance(tmpfile.path);
571 ASSERT_TRUE(reader);
572 auto info_map = reader->GetMetaInfoFeature();
573 ASSERT_EQ(info_map["clockid"], "monotonic");
574 }
575 }
576
TEST(record_cmd,generate_samples_by_hw_counters)577 TEST(record_cmd, generate_samples_by_hw_counters) {
578 TEST_REQUIRE_HW_COUNTER();
579 std::vector<std::string> events = {"cpu-cycles", "instructions"};
580 for (auto& event : events) {
581 TemporaryFile tmpfile;
582 ASSERT_TRUE(RecordCmd()->Run({"-e", event, "-o", tmpfile.path, "sleep", "1"}));
583 std::unique_ptr<RecordFileReader> reader = RecordFileReader::CreateInstance(tmpfile.path);
584 ASSERT_TRUE(reader);
585 bool has_sample = false;
586 ASSERT_TRUE(reader->ReadDataSection([&](std::unique_ptr<Record> r) {
587 if (r->type() == PERF_RECORD_SAMPLE) {
588 has_sample = true;
589 }
590 return true;
591 }));
592 ASSERT_TRUE(has_sample);
593 }
594 }
595
TEST(record_cmd,callchain_joiner_options)596 TEST(record_cmd, callchain_joiner_options) {
597 ASSERT_TRUE(RunRecordCmd({"--no-callchain-joiner"}));
598 ASSERT_TRUE(RunRecordCmd({"--callchain-joiner-min-matching-nodes", "2"}));
599 }
600
TEST(record_cmd,dashdash)601 TEST(record_cmd, dashdash) {
602 TemporaryFile tmpfile;
603 ASSERT_TRUE(RecordCmd()->Run({"-o", tmpfile.path, "-e", GetDefaultEvent(), "--", "sleep", "1"}));
604 }
605
TEST(record_cmd,size_limit_option)606 TEST(record_cmd, size_limit_option) {
607 std::vector<std::unique_ptr<Workload>> workloads;
608 CreateProcesses(1, &workloads);
609 std::string pid = std::to_string(workloads[0]->GetPid());
610 TemporaryFile tmpfile;
611 ASSERT_TRUE(RecordCmd()->Run({"-o", tmpfile.path, "-p", pid, "--size-limit", "1k", "--duration",
612 "1", "-e", GetDefaultEvent()}));
613 std::unique_ptr<RecordFileReader> reader = RecordFileReader::CreateInstance(tmpfile.path);
614 ASSERT_TRUE(reader);
615 ASSERT_GT(reader->FileHeader().data.size, 1000u);
616 ASSERT_LT(reader->FileHeader().data.size, 2000u);
617 ASSERT_FALSE(RunRecordCmd({"--size-limit", "0"}));
618 }
619
TEST(record_cmd,support_mmap2)620 TEST(record_cmd, support_mmap2) {
621 // mmap2 is supported in kernel >= 3.16. If not supported, please cherry pick below kernel
622 // patches:
623 // 13d7a2410fa637 perf: Add attr->mmap2 attribute to an event
624 // f972eb63b1003f perf: Pass protection and flags bits through mmap2 interface.
625 ASSERT_TRUE(IsMmap2Supported());
626 }
627
TEST(record_cmd,kernel_bug_making_zero_dyn_size)628 TEST(record_cmd, kernel_bug_making_zero_dyn_size) {
629 // Test a kernel bug that makes zero dyn_size in kernel < 3.13. If it fails, please cherry pick
630 // below kernel patch: 0a196848ca365e perf: Fix arch_perf_out_copy_user default
631 OMIT_TEST_ON_NON_NATIVE_ABIS();
632 std::vector<std::unique_ptr<Workload>> workloads;
633 CreateProcesses(1, &workloads);
634 std::string pid = std::to_string(workloads[0]->GetPid());
635 TemporaryFile tmpfile;
636 ASSERT_TRUE(RecordCmd()->Run({"-o", tmpfile.path, "-p", pid, "--call-graph", "dwarf,8",
637 "--no-unwind", "--duration", "1", "-e", GetDefaultEvent()}));
638 std::unique_ptr<RecordFileReader> reader = RecordFileReader::CreateInstance(tmpfile.path);
639 ASSERT_TRUE(reader);
640 bool has_sample = false;
641 ASSERT_TRUE(reader->ReadDataSection([&](std::unique_ptr<Record> r) {
642 if (r->type() == PERF_RECORD_SAMPLE && !r->InKernel()) {
643 SampleRecord* sr = static_cast<SampleRecord*>(r.get());
644 if (sr->stack_user_data.dyn_size == 0) {
645 return false;
646 }
647 has_sample = true;
648 }
649 return true;
650 }));
651 ASSERT_TRUE(has_sample);
652 }
653
TEST(record_cmd,kernel_bug_making_zero_dyn_size_for_kernel_samples)654 TEST(record_cmd, kernel_bug_making_zero_dyn_size_for_kernel_samples) {
655 // Test a kernel bug that makes zero dyn_size for syscalls of 32-bit applications in 64-bit
656 // kernels. If it fails, please cherry pick below kernel patch:
657 // 02e184476eff8 perf/core: Force USER_DS when recording user stack data
658 OMIT_TEST_ON_NON_NATIVE_ABIS();
659 TEST_REQUIRE_HOST_ROOT();
660 TEST_REQUIRE_TRACEPOINT_EVENTS();
661 std::vector<std::unique_ptr<Workload>> workloads;
662 CreateProcesses(1, &workloads);
663 std::string pid = std::to_string(workloads[0]->GetPid());
664 TemporaryFile tmpfile;
665 ASSERT_TRUE(RecordCmd()->Run({"-e", "sched:sched_switch", "-o", tmpfile.path, "-p", pid,
666 "--call-graph", "dwarf,8", "--no-unwind", "--duration", "1"}));
667 std::unique_ptr<RecordFileReader> reader = RecordFileReader::CreateInstance(tmpfile.path);
668 ASSERT_TRUE(reader);
669 bool has_sample = false;
670 ASSERT_TRUE(reader->ReadDataSection([&](std::unique_ptr<Record> r) {
671 if (r->type() == PERF_RECORD_SAMPLE && r->InKernel()) {
672 SampleRecord* sr = static_cast<SampleRecord*>(r.get());
673 if (sr->stack_user_data.dyn_size == 0) {
674 return false;
675 }
676 has_sample = true;
677 }
678 return true;
679 }));
680 ASSERT_TRUE(has_sample);
681 }
682
TEST(record_cmd,cpu_percent_option)683 TEST(record_cmd, cpu_percent_option) {
684 ASSERT_TRUE(RunRecordCmd({"--cpu-percent", "50"}));
685 ASSERT_FALSE(RunRecordCmd({"--cpu-percent", "0"}));
686 ASSERT_FALSE(RunRecordCmd({"--cpu-percent", "101"}));
687 }
688
689 class RecordingAppHelper {
690 public:
InstallApk(const std::string & apk_path,const std::string & package_name)691 bool InstallApk(const std::string& apk_path, const std::string& package_name) {
692 return app_helper_.InstallApk(apk_path, package_name);
693 }
694
StartApp(const std::string & start_cmd)695 bool StartApp(const std::string& start_cmd) { return app_helper_.StartApp(start_cmd); }
696
RecordData(const std::string & record_cmd)697 bool RecordData(const std::string& record_cmd) {
698 std::vector<std::string> args = android::base::Split(record_cmd, " ");
699 args.emplace_back("-o");
700 args.emplace_back(perf_data_file_.path);
701 return RecordCmd()->Run(args);
702 }
703
CheckData(const std::function<bool (const char *)> & process_symbol)704 bool CheckData(const std::function<bool(const char*)>& process_symbol) {
705 bool success = false;
706 auto callback = [&](const Symbol& symbol, uint32_t) {
707 if (process_symbol(symbol.DemangledName())) {
708 success = true;
709 }
710 return success;
711 };
712 ProcessSymbolsInPerfDataFile(perf_data_file_.path, callback);
713 return success;
714 }
715
GetDataPath() const716 std::string GetDataPath() const { return perf_data_file_.path; }
717
718 private:
719 AppHelper app_helper_;
720 TemporaryFile perf_data_file_;
721 };
722
TestRecordingApps(const std::string & app_name,const std::string & app_type)723 static void TestRecordingApps(const std::string& app_name, const std::string& app_type) {
724 RecordingAppHelper helper;
725 // Bring the app to foreground to avoid no samples.
726 ASSERT_TRUE(helper.StartApp("am start " + app_name + "/.MainActivity"));
727
728 ASSERT_TRUE(helper.RecordData("--app " + app_name + " -g --duration 10 -e " + GetDefaultEvent()));
729
730 // Check if we can profile Java code by looking for a Java method name in dumped symbols, which
731 // is app_name + ".MainActivity$1.run".
732 const std::string expected_class_name = app_name + ".MainActivity";
733 const std::string expected_method_name = "run";
734 auto process_symbol = [&](const char* name) {
735 return strstr(name, expected_class_name.c_str()) != nullptr &&
736 strstr(name, expected_method_name.c_str()) != nullptr;
737 };
738 ASSERT_TRUE(helper.CheckData(process_symbol));
739
740 // Check app_package_name and app_type.
741 auto reader = RecordFileReader::CreateInstance(helper.GetDataPath());
742 ASSERT_TRUE(reader);
743 const std::unordered_map<std::string, std::string>& meta_info = reader->GetMetaInfoFeature();
744 auto it = meta_info.find("app_package_name");
745 ASSERT_NE(it, meta_info.end());
746 ASSERT_EQ(it->second, app_name);
747 it = meta_info.find("app_type");
748 ASSERT_NE(it, meta_info.end());
749 ASSERT_EQ(it->second, app_type);
750 }
751
TEST(record_cmd,app_option_for_debuggable_app)752 TEST(record_cmd, app_option_for_debuggable_app) {
753 TEST_REQUIRE_APPS();
754 SetRunInAppToolForTesting(true, false);
755 TestRecordingApps("com.android.simpleperf.debuggable", "debuggable");
756 SetRunInAppToolForTesting(false, true);
757 TestRecordingApps("com.android.simpleperf.debuggable", "debuggable");
758 }
759
TEST(record_cmd,app_option_for_profileable_app)760 TEST(record_cmd, app_option_for_profileable_app) {
761 TEST_REQUIRE_APPS();
762 SetRunInAppToolForTesting(false, true);
763 TestRecordingApps("com.android.simpleperf.profileable", "profileable");
764 }
765
766 #if defined(__ANDROID__)
RecordJavaApp(RecordingAppHelper & helper)767 static void RecordJavaApp(RecordingAppHelper& helper) {
768 // 1. Install apk.
769 ASSERT_TRUE(helper.InstallApk(GetTestData("DisplayBitmaps.apk"),
770 "com.example.android.displayingbitmaps"));
771 ASSERT_TRUE(helper.InstallApk(GetTestData("DisplayBitmapsTest.apk"),
772 "com.example.android.displayingbitmaps.test"));
773
774 // 2. Start the app.
775 ASSERT_TRUE(
776 helper.StartApp("am instrument -w -r -e debug false -e class "
777 "com.example.android.displayingbitmaps.tests.GridViewTest "
778 "com.example.android.displayingbitmaps.test/"
779 "androidx.test.runner.AndroidJUnitRunner"));
780
781 // 3. Record perf.data.
782 SetRunInAppToolForTesting(true, true);
783 ASSERT_TRUE(helper.RecordData(
784 "-e cpu-clock --app com.example.android.displayingbitmaps -g --duration 15"));
785 }
786 #endif // defined(__ANDROID__)
787
TEST(record_cmd,record_java_app)788 TEST(record_cmd, record_java_app) {
789 #if defined(__ANDROID__)
790 RecordingAppHelper helper;
791
792 RecordJavaApp(helper);
793 if (HasFailure()) {
794 return;
795 }
796
797 // Check perf.data by looking for java symbols.
798 auto process_symbol = [&](const char* name) {
799 #if !defined(IN_CTS_TEST)
800 const char* expected_name_with_keyguard = "androidx.test.runner"; // when screen is locked
801 if (strstr(name, expected_name_with_keyguard) != nullptr) {
802 return true;
803 }
804 #endif
805 const char* expected_name = "androidx.test.espresso"; // when screen stays awake
806 return strstr(name, expected_name) != nullptr;
807 };
808 ASSERT_TRUE(helper.CheckData(process_symbol));
809 #else
810 GTEST_LOG_(INFO) << "This test tests a function only available on Android.";
811 #endif
812 }
813
TEST(record_cmd,record_native_app)814 TEST(record_cmd, record_native_app) {
815 #if defined(__ANDROID__)
816 // In case of non-native ABI guest symbols are never directly executed, thus
817 // don't appear in perf.data. Instead binary translator executes code
818 // translated from guest at runtime.
819 OMIT_TEST_ON_NON_NATIVE_ABIS();
820
821 RecordingAppHelper helper;
822 // 1. Install apk.
823 ASSERT_TRUE(helper.InstallApk(GetTestData("EndlessTunnel.apk"), "com.google.sample.tunnel"));
824
825 // 2. Start the app.
826 ASSERT_TRUE(
827 helper.StartApp("am start -n com.google.sample.tunnel/android.app.NativeActivity -a "
828 "android.intent.action.MAIN -c android.intent.category.LAUNCHER"));
829
830 // 3. Record perf.data.
831 SetRunInAppToolForTesting(true, true);
832 ASSERT_TRUE(helper.RecordData("-e cpu-clock --app com.google.sample.tunnel -g --duration 10"));
833
834 // 4. Check perf.data.
835 auto process_symbol = [&](const char* name) {
836 const char* expected_name_with_keyguard = "NativeActivity"; // when screen is locked
837 if (strstr(name, expected_name_with_keyguard) != nullptr) {
838 return true;
839 }
840 const char* expected_name = "PlayScene::DoFrame"; // when screen is awake
841 return strstr(name, expected_name) != nullptr;
842 };
843 ASSERT_TRUE(helper.CheckData(process_symbol));
844 #else
845 GTEST_LOG_(INFO) << "This test tests a function only available on Android.";
846 #endif
847 }
848
TEST(record_cmd,check_trampoline_after_art_jni_methods)849 TEST(record_cmd, check_trampoline_after_art_jni_methods) {
850 // Test if art jni methods are called by art_jni_trampoline.
851 #if defined(__ANDROID__)
852 RecordingAppHelper helper;
853
854 RecordJavaApp(helper);
855 if (HasFailure()) {
856 return;
857 }
858
859 // Check if art::Method_invoke() is called by art_jni_trampoline.
860 auto reader = RecordFileReader::CreateInstance(helper.GetDataPath());
861 ASSERT_TRUE(reader);
862 ThreadTree thread_tree;
863
864 auto get_symbol_name = [&](ThreadEntry* thread, uint64_t ip) -> std::string {
865 const MapEntry* map = thread_tree.FindMap(thread, ip, false);
866 const Symbol* symbol = thread_tree.FindSymbol(map, ip, nullptr, nullptr);
867 return symbol->DemangledName();
868 };
869
870 bool has_check = false;
871
872 auto process_record = [&](std::unique_ptr<Record> r) {
873 thread_tree.Update(*r);
874 if (r->type() == PERF_RECORD_SAMPLE) {
875 auto sample = static_cast<SampleRecord*>(r.get());
876 ThreadEntry* thread = thread_tree.FindThreadOrNew(sample->tid_data.pid, sample->tid_data.tid);
877 size_t kernel_ip_count;
878 std::vector<uint64_t> ips = sample->GetCallChain(&kernel_ip_count);
879 for (size_t i = kernel_ip_count; i < ips.size(); i++) {
880 std::string sym_name = get_symbol_name(thread, ips[i]);
881 if (android::base::StartsWith(sym_name, "art::Method_invoke") && i + 1 < ips.size()) {
882 has_check = true;
883 if (get_symbol_name(thread, ips[i + 1]) != "art_jni_trampoline") {
884 return false;
885 }
886 }
887 }
888 }
889 return true;
890 };
891 ASSERT_TRUE(reader->ReadDataSection(process_record));
892 ASSERT_TRUE(has_check);
893 #else
894 GTEST_LOG_(INFO) << "This test tests a function only available on Android.";
895 #endif
896 }
897
TEST(record_cmd,no_cut_samples_option)898 TEST(record_cmd, no_cut_samples_option) {
899 ASSERT_TRUE(RunRecordCmd({"--no-cut-samples"}));
900 }
901
TEST(record_cmd,cs_etm_event)902 TEST(record_cmd, cs_etm_event) {
903 if (!ETMRecorder::GetInstance().CheckEtmSupport()) {
904 GTEST_LOG_(INFO) << "Omit this test since etm isn't supported on this device";
905 return;
906 }
907 TemporaryFile tmpfile;
908 ASSERT_TRUE(RunRecordCmd({"-e", "cs-etm"}, tmpfile.path));
909 std::unique_ptr<RecordFileReader> reader = RecordFileReader::CreateInstance(tmpfile.path);
910 ASSERT_TRUE(reader);
911
912 // cs-etm uses sample period instead of sample freq.
913 ASSERT_EQ(reader->AttrSection().size(), 1u);
914 const perf_event_attr* attr = reader->AttrSection()[0].attr;
915 ASSERT_EQ(attr->freq, 0);
916 ASSERT_EQ(attr->sample_period, 1);
917
918 bool has_auxtrace_info = false;
919 bool has_auxtrace = false;
920 bool has_aux = false;
921 ASSERT_TRUE(reader->ReadDataSection([&](std::unique_ptr<Record> r) {
922 if (r->type() == PERF_RECORD_AUXTRACE_INFO) {
923 has_auxtrace_info = true;
924 } else if (r->type() == PERF_RECORD_AUXTRACE) {
925 has_auxtrace = true;
926 } else if (r->type() == PERF_RECORD_AUX) {
927 has_aux = true;
928 }
929 return true;
930 }));
931 ASSERT_TRUE(has_auxtrace_info);
932 ASSERT_TRUE(has_auxtrace);
933 ASSERT_TRUE(has_aux);
934 }
935
TEST(record_cmd,cs_etm_system_wide)936 TEST(record_cmd, cs_etm_system_wide) {
937 TEST_REQUIRE_ROOT();
938 if (!ETMRecorder::GetInstance().CheckEtmSupport()) {
939 GTEST_LOG_(INFO) << "Omit this test since etm isn't supported on this device";
940 return;
941 }
942 ASSERT_TRUE(RunRecordCmd({"-e", "cs-etm", "-a"}));
943 }
944
TEST(record_cmd,aux_buffer_size_option)945 TEST(record_cmd, aux_buffer_size_option) {
946 if (!ETMRecorder::GetInstance().CheckEtmSupport()) {
947 GTEST_LOG_(INFO) << "Omit this test since etm isn't supported on this device";
948 return;
949 }
950 ASSERT_TRUE(RunRecordCmd({"-e", "cs-etm", "--aux-buffer-size", "1m"}));
951 // not page size aligned
952 ASSERT_FALSE(RunRecordCmd({"-e", "cs-etm", "--aux-buffer-size", "1024"}));
953 // not power of two
954 ASSERT_FALSE(RunRecordCmd({"-e", "cs-etm", "--aux-buffer-size", "12k"}));
955 }
956
TEST(record_cmd,addr_filter_option)957 TEST(record_cmd, addr_filter_option) {
958 TEST_REQUIRE_HW_COUNTER();
959 if (!ETMRecorder::GetInstance().CheckEtmSupport()) {
960 GTEST_LOG_(INFO) << "Omit this test since etm isn't supported on this device";
961 return;
962 }
963 FILE* fp = popen("which sleep", "r");
964 ASSERT_TRUE(fp != nullptr);
965 std::string path;
966 ASSERT_TRUE(android::base::ReadFdToString(fileno(fp), &path));
967 pclose(fp);
968 path = android::base::Trim(path);
969 std::string sleep_exec_path;
970 ASSERT_TRUE(Realpath(path, &sleep_exec_path));
971 // --addr-filter doesn't apply to cpu-cycles.
972 ASSERT_FALSE(RunRecordCmd({"--addr-filter", "filter " + sleep_exec_path}));
973 TemporaryFile record_file;
974 ASSERT_TRUE(RunRecordCmd({"-e", "cs-etm", "--addr-filter", "filter " + sleep_exec_path},
975 record_file.path));
976 TemporaryFile inject_file;
977 ASSERT_TRUE(
978 CreateCommandInstance("inject")->Run({"-i", record_file.path, "-o", inject_file.path}));
979 std::string data;
980 ASSERT_TRUE(android::base::ReadFileToString(inject_file.path, &data));
981 // Only instructions in sleep_exec_path are traced.
982 for (auto& line : android::base::Split(data, "\n")) {
983 if (android::base::StartsWith(line, "dso ")) {
984 std::string dso = line.substr(strlen("dso "), sleep_exec_path.size());
985 ASSERT_EQ(dso, sleep_exec_path);
986 }
987 }
988
989 // Test if different filter types are accepted by the kernel.
990 auto elf = ElfFile::Open(sleep_exec_path);
991 uint64_t off;
992 uint64_t addr = elf->ReadMinExecutableVaddr(&off);
993 // file start
994 std::string filter = StringPrintf("start 0x%" PRIx64 "@%s", addr, sleep_exec_path.c_str());
995 ASSERT_TRUE(RunRecordCmd({"-e", "cs-etm", "--addr-filter", filter}));
996 // file stop
997 filter = StringPrintf("stop 0x%" PRIx64 "@%s", addr, sleep_exec_path.c_str());
998 ASSERT_TRUE(RunRecordCmd({"-e", "cs-etm", "--addr-filter", filter}));
999 // file range
1000 filter = StringPrintf("filter 0x%" PRIx64 "-0x%" PRIx64 "@%s", addr, addr + 4,
1001 sleep_exec_path.c_str());
1002 ASSERT_TRUE(RunRecordCmd({"-e", "cs-etm", "--addr-filter", filter}));
1003 // If kernel panic, try backporting "perf/core: Fix crash when using HW tracing kernel
1004 // filters".
1005 // kernel start
1006 uint64_t fake_kernel_addr = (1ULL << 63);
1007 filter = StringPrintf("start 0x%" PRIx64, fake_kernel_addr);
1008 ASSERT_TRUE(RunRecordCmd({"-e", "cs-etm", "--addr-filter", filter}));
1009 // kernel stop
1010 filter = StringPrintf("stop 0x%" PRIx64, fake_kernel_addr);
1011 ASSERT_TRUE(RunRecordCmd({"-e", "cs-etm", "--addr-filter", filter}));
1012 // kernel range
1013 filter = StringPrintf("filter 0x%" PRIx64 "-0x%" PRIx64, fake_kernel_addr, fake_kernel_addr + 4);
1014 ASSERT_TRUE(RunRecordCmd({"-e", "cs-etm", "--addr-filter", filter}));
1015 }
1016
TEST(record_cmd,pmu_event_option)1017 TEST(record_cmd, pmu_event_option) {
1018 TEST_REQUIRE_PMU_COUNTER();
1019 TEST_REQUIRE_HW_COUNTER();
1020 std::string event_string;
1021 if (GetBuildArch() == ARCH_X86_64) {
1022 event_string = "cpu/cpu-cycles/";
1023 } else if (GetBuildArch() == ARCH_ARM64) {
1024 event_string = "armv8_pmuv3/cpu_cycles/";
1025 } else {
1026 GTEST_LOG_(INFO) << "Omit arch " << GetBuildArch();
1027 return;
1028 }
1029 TEST_IN_ROOT(ASSERT_TRUE(RunRecordCmd({"-e", event_string})));
1030 }
1031
TEST(record_cmd,exclude_perf_option)1032 TEST(record_cmd, exclude_perf_option) {
1033 ASSERT_TRUE(RunRecordCmd({"--exclude-perf"}));
1034 if (IsRoot()) {
1035 TemporaryFile tmpfile;
1036 ASSERT_TRUE(RecordCmd()->Run(
1037 {"-a", "--exclude-perf", "--duration", "1", "-e", GetDefaultEvent(), "-o", tmpfile.path}));
1038 std::unique_ptr<RecordFileReader> reader = RecordFileReader::CreateInstance(tmpfile.path);
1039 ASSERT_TRUE(reader);
1040 pid_t perf_pid = getpid();
1041 ASSERT_TRUE(reader->ReadDataSection([&](std::unique_ptr<Record> r) {
1042 if (r->type() == PERF_RECORD_SAMPLE) {
1043 if (static_cast<SampleRecord*>(r.get())->tid_data.pid == perf_pid) {
1044 return false;
1045 }
1046 }
1047 return true;
1048 }));
1049 }
1050 }
1051
TEST(record_cmd,tp_filter_option)1052 TEST(record_cmd, tp_filter_option) {
1053 TEST_REQUIRE_HOST_ROOT();
1054 TEST_REQUIRE_TRACEPOINT_EVENTS();
1055 // Test string operands both with quotes and without quotes.
1056 for (const auto& filter :
1057 std::vector<std::string>({"prev_comm != 'sleep'", "prev_comm != sleep"})) {
1058 TemporaryFile tmpfile;
1059 ASSERT_TRUE(RunRecordCmd({"-e", "sched:sched_switch", "--tp-filter", filter}, tmpfile.path))
1060 << filter;
1061 CaptureStdout capture;
1062 ASSERT_TRUE(capture.Start());
1063 ASSERT_TRUE(CreateCommandInstance("dump")->Run({tmpfile.path}));
1064 std::string data = capture.Finish();
1065 // Check that samples with prev_comm == sleep are filtered out. Although we do the check all the
1066 // time, it only makes sense when running as root. Tracepoint event fields are not allowed
1067 // to record unless running as root.
1068 ASSERT_EQ(data.find("prev_comm: sleep"), std::string::npos) << filter;
1069 }
1070 }
1071
TEST(record_cmd,ParseAddrFilterOption)1072 TEST(record_cmd, ParseAddrFilterOption) {
1073 auto option_to_str = [](const std::string& option) {
1074 auto filters = ParseAddrFilterOption(option);
1075 std::string s;
1076 for (auto& filter : filters) {
1077 if (!s.empty()) {
1078 s += ',';
1079 }
1080 s += filter.ToString();
1081 }
1082 return s;
1083 };
1084 std::string path;
1085 ASSERT_TRUE(Realpath(GetTestData(ELF_FILE), &path));
1086
1087 // Test file filters.
1088 ASSERT_EQ(option_to_str("filter " + path), "filter 0x0/0x73c@" + path);
1089 ASSERT_EQ(option_to_str("filter 0x400502-0x400527@" + path), "filter 0x502/0x25@" + path);
1090 ASSERT_EQ(option_to_str("start 0x400502@" + path + ",stop 0x400527@" + path),
1091 "start 0x502@" + path + ",stop 0x527@" + path);
1092
1093 // Test '-' in file path. Create a temporary file with '-' in name.
1094 TemporaryDir tmpdir;
1095 fs::path tmpfile = fs::path(tmpdir.path) / "elf-with-hyphen";
1096 ASSERT_TRUE(fs::copy_file(path, tmpfile));
1097 ASSERT_EQ(option_to_str("filter " + tmpfile.string()), "filter 0x0/0x73c@" + tmpfile.string());
1098
1099 // Test kernel filters.
1100 ASSERT_EQ(option_to_str("filter 0x12345678-0x1234567a"), "filter 0x12345678/0x2");
1101 ASSERT_EQ(option_to_str("start 0x12345678,stop 0x1234567a"), "start 0x12345678,stop 0x1234567a");
1102 }
1103
TEST(record_cmd,kprobe_option)1104 TEST(record_cmd, kprobe_option) {
1105 TEST_REQUIRE_ROOT();
1106 ProbeEvents probe_events;
1107 if (!probe_events.IsKprobeSupported()) {
1108 GTEST_LOG_(INFO) << "Skip this test as kprobe isn't supported by the kernel.";
1109 return;
1110 }
1111 ASSERT_TRUE(RunRecordCmd({"-e", "kprobes:myprobe", "--kprobe", "p:myprobe do_sys_open"}));
1112 // A default kprobe event is created if not given an explicit --kprobe option.
1113 ASSERT_TRUE(RunRecordCmd({"-e", "kprobes:do_sys_open"}));
1114 ASSERT_TRUE(RunRecordCmd({"--group", "kprobes:do_sys_open"}));
1115 }
1116
TEST(record_cmd,record_filter_options)1117 TEST(record_cmd, record_filter_options) {
1118 ASSERT_TRUE(
1119 RunRecordCmd({"--exclude-pid", "1,2", "--exclude-tid", "3,4", "--exclude-process-name",
1120 "processA", "--exclude-thread-name", "threadA", "--exclude-uid", "5,6"}));
1121 ASSERT_TRUE(
1122 RunRecordCmd({"--include-pid", "1,2", "--include-tid", "3,4", "--include-process-name",
1123 "processB", "--include-thread-name", "threadB", "--include-uid", "5,6"}));
1124 }
1125
TEST(record_cmd,keep_failed_unwinding_result_option)1126 TEST(record_cmd, keep_failed_unwinding_result_option) {
1127 OMIT_TEST_ON_NON_NATIVE_ABIS();
1128 std::vector<std::unique_ptr<Workload>> workloads;
1129 CreateProcesses(1, &workloads);
1130 std::string pid = std::to_string(workloads[0]->GetPid());
1131 ASSERT_TRUE(RunRecordCmd(
1132 {"-p", pid, "-g", "--keep-failed-unwinding-result", "--keep-failed-unwinding-debug-info"}));
1133 }
1134
TEST(record_cmd,kernel_address_warning)1135 TEST(record_cmd, kernel_address_warning) {
1136 TEST_REQUIRE_NON_ROOT();
1137 const std::string warning_msg = "Access to kernel symbol addresses is restricted.";
1138 CapturedStderr capture;
1139
1140 // When excluding kernel samples, no kernel address warning is printed.
1141 ResetKernelAddressWarning();
1142 TemporaryFile tmpfile;
1143 ASSERT_TRUE(RunRecordCmd({"-e", "cpu-clock:u"}, tmpfile.path));
1144 capture.Stop();
1145 ASSERT_EQ(capture.str().find(warning_msg), std::string::npos);
1146
1147 // When not excluding kernel samples, kernel address warning is printed once.
1148 capture.Reset();
1149 capture.Start();
1150 ResetKernelAddressWarning();
1151 ASSERT_TRUE(RunRecordCmd({"-e", "cpu-clock"}, tmpfile.path));
1152 capture.Stop();
1153 std::string output = capture.str();
1154 auto pos = output.find(warning_msg);
1155 ASSERT_NE(pos, std::string::npos);
1156 ASSERT_EQ(output.find(warning_msg, pos + warning_msg.size()), std::string::npos);
1157 }
1158
TEST(record_cmd,add_meta_info_option)1159 TEST(record_cmd, add_meta_info_option) {
1160 TemporaryFile tmpfile;
1161 ASSERT_TRUE(RunRecordCmd({"--add-meta-info", "key1=value1", "--add-meta-info", "key2=value2"},
1162 tmpfile.path));
1163 auto reader = RecordFileReader::CreateInstance(tmpfile.path);
1164 ASSERT_TRUE(reader);
1165
1166 const std::unordered_map<std::string, std::string>& meta_info = reader->GetMetaInfoFeature();
1167 auto it = meta_info.find("key1");
1168 ASSERT_NE(it, meta_info.end());
1169 ASSERT_EQ(it->second, "value1");
1170 it = meta_info.find("key2");
1171 ASSERT_NE(it, meta_info.end());
1172 ASSERT_EQ(it->second, "value2");
1173
1174 // Report error for invalid meta info.
1175 ASSERT_FALSE(RunRecordCmd({"--add-meta-info", "key1"}, tmpfile.path));
1176 ASSERT_FALSE(RunRecordCmd({"--add-meta-info", "key1="}, tmpfile.path));
1177 ASSERT_FALSE(RunRecordCmd({"--add-meta-info", "=value1"}, tmpfile.path));
1178 }
1179
TEST(record_cmd,device_meta_info)1180 TEST(record_cmd, device_meta_info) {
1181 TemporaryFile tmpfile;
1182 ASSERT_TRUE(RunRecordCmd({}, tmpfile.path));
1183 auto reader = RecordFileReader::CreateInstance(tmpfile.path);
1184 ASSERT_TRUE(reader);
1185
1186 const std::unordered_map<std::string, std::string>& meta_info = reader->GetMetaInfoFeature();
1187 auto it = meta_info.find("android_sdk_version");
1188 ASSERT_NE(it, meta_info.end());
1189 ASSERT_FALSE(it->second.empty());
1190 it = meta_info.find("android_build_type");
1191 ASSERT_NE(it, meta_info.end());
1192 ASSERT_FALSE(it->second.empty());
1193 }
1194