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