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