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