1 /*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include <gtest/gtest.h>
18
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <unistd.h>
22
23 #include <filesystem>
24 #include <map>
25 #include <memory>
26 #include <regex>
27 #include <thread>
28
29 #include <android-base/file.h>
30 #include <android-base/logging.h>
31 #include <android-base/properties.h>
32 #include <android-base/stringprintf.h>
33 #include <android-base/strings.h>
34 #include <android-base/test_utils.h>
35
36 #include "ETMRecorder.h"
37 #include "JITDebugReader.h"
38 #include "ProbeEvents.h"
39 #include "cmd_record_impl.h"
40 #include "command.h"
41 #include "environment.h"
42 #include "event_selection_set.h"
43 #include "get_test_data.h"
44 #include "kallsyms.h"
45 #include "record.h"
46 #include "record_file.h"
47 #include "test_util.h"
48 #include "thread_tree.h"
49
50 using android::base::Realpath;
51 using android::base::StringPrintf;
52 using namespace simpleperf;
53 using namespace PerfFileFormat;
54 namespace fs = std::filesystem;
55
RecordCmd()56 static std::unique_ptr<Command> RecordCmd() {
57 return CreateCommandInstance("record");
58 }
59
GetDefaultEvent()60 static const char* GetDefaultEvent() {
61 if (HasHardwareCounter()) {
62 return IsKernelEventSupported() ? "cpu-cycles" : "cpu-cycles:u";
63 }
64 return IsKernelEventSupported() ? "task-clock" : "task-clock:u";
65 }
66
RunRecordCmd(std::vector<std::string> v,const char * output_file=nullptr)67 static bool RunRecordCmd(std::vector<std::string> v, const char* output_file = nullptr) {
68 bool has_event = false;
69 for (auto& arg : v) {
70 if (arg == "-e" || arg == "--group") {
71 has_event = true;
72 break;
73 }
74 }
75 if (!has_event) {
76 v.insert(v.end(), {"-e", GetDefaultEvent()});
77 }
78
79 std::unique_ptr<TemporaryFile> tmpfile;
80 std::string out_file;
81 if (output_file != nullptr) {
82 out_file = output_file;
83 } else {
84 tmpfile.reset(new TemporaryFile);
85 out_file = tmpfile->path;
86 }
87 v.insert(v.end(), {"-o", out_file, "sleep", SLEEP_SEC});
88 return RecordCmd()->Run(v);
89 }
90
91 // @CddTest = 6.1/C-0-2
TEST(record_cmd,no_options)92 TEST(record_cmd, no_options) {
93 ASSERT_TRUE(RunRecordCmd({}));
94 }
95
96 // @CddTest = 6.1/C-0-2
TEST(record_cmd,system_wide_option)97 TEST(record_cmd, system_wide_option) {
98 TEST_IN_ROOT(ASSERT_TRUE(RunRecordCmd({"-a"})));
99 }
100
CheckEventType(const std::string & record_file,const std::string & event_type,uint64_t sample_period,uint64_t sample_freq)101 static void CheckEventType(const std::string& record_file, const std::string& event_type,
102 uint64_t sample_period, uint64_t sample_freq) {
103 std::string event_name = event_type;
104 if (auto pos = event_name.find(":u"); pos != std::string::npos) {
105 event_name = event_name.substr(0, pos);
106 }
107 const EventType* type = FindEventTypeByName(event_name);
108 ASSERT_TRUE(type != nullptr);
109 std::unique_ptr<RecordFileReader> reader = RecordFileReader::CreateInstance(record_file);
110 ASSERT_TRUE(reader);
111 for (const auto& attr_with_id : reader->AttrSection()) {
112 const perf_event_attr& attr = attr_with_id.attr;
113 if (attr.type == type->type && attr.config == type->config) {
114 if (attr.freq == 0) {
115 ASSERT_EQ(sample_period, attr.sample_period);
116 ASSERT_EQ(sample_freq, 0u);
117 } else {
118 ASSERT_EQ(sample_period, 0u);
119 ASSERT_EQ(sample_freq, attr.sample_freq);
120 }
121 return;
122 }
123 }
124 FAIL();
125 }
126
127 // @CddTest = 6.1/C-0-2
TEST(record_cmd,sample_period_option)128 TEST(record_cmd, sample_period_option) {
129 TemporaryFile tmpfile;
130 ASSERT_TRUE(RunRecordCmd({"-c", "100000"}, tmpfile.path));
131 CheckEventType(tmpfile.path, GetDefaultEvent(), 100000u, 0);
132 }
133
134 // @CddTest = 6.1/C-0-2
TEST(record_cmd,event_option)135 TEST(record_cmd, event_option) {
136 ASSERT_TRUE(RunRecordCmd({"-e", "cpu-clock:u"}));
137 }
138
139 // @CddTest = 6.1/C-0-2
TEST(record_cmd,freq_option)140 TEST(record_cmd, freq_option) {
141 TemporaryFile tmpfile;
142 ASSERT_TRUE(RunRecordCmd({"-f", "99"}, tmpfile.path));
143 CheckEventType(tmpfile.path, GetDefaultEvent(), 0, 99u);
144 ASSERT_TRUE(RunRecordCmd({"-e", "cpu-clock:u", "-f", "99"}, tmpfile.path));
145 CheckEventType(tmpfile.path, "cpu-clock:u", 0, 99u);
146 ASSERT_FALSE(RunRecordCmd({"-f", std::to_string(UINT_MAX)}));
147 }
148
149 // @CddTest = 6.1/C-0-2
TEST(record_cmd,multiple_freq_or_sample_period_option)150 TEST(record_cmd, multiple_freq_or_sample_period_option) {
151 TemporaryFile tmpfile;
152 ASSERT_TRUE(RunRecordCmd({"-f", "99", "-e", "task-clock:u", "-c", "1000000", "-e", "cpu-clock:u"},
153 tmpfile.path));
154 CheckEventType(tmpfile.path, "task-clock", 0, 99u);
155 CheckEventType(tmpfile.path, "cpu-clock", 1000000u, 0u);
156 }
157
158 // @CddTest = 6.1/C-0-2
TEST(record_cmd,output_file_option)159 TEST(record_cmd, output_file_option) {
160 TemporaryFile tmpfile;
161 ASSERT_TRUE(RecordCmd()->Run({"-o", tmpfile.path, "-e", GetDefaultEvent(), "sleep", SLEEP_SEC}));
162 }
163
164 // @CddTest = 6.1/C-0-2
TEST(record_cmd,dump_kernel_mmap)165 TEST(record_cmd, dump_kernel_mmap) {
166 TEST_REQUIRE_KERNEL_EVENTS();
167 TemporaryFile tmpfile;
168 ASSERT_TRUE(RunRecordCmd({}, tmpfile.path));
169 std::unique_ptr<RecordFileReader> reader = RecordFileReader::CreateInstance(tmpfile.path);
170 ASSERT_TRUE(reader != nullptr);
171 std::vector<std::unique_ptr<Record>> records = reader->DataSection();
172 ASSERT_GT(records.size(), 0U);
173 bool have_kernel_mmap = false;
174 for (auto& record : records) {
175 if (record->type() == PERF_RECORD_MMAP) {
176 const MmapRecord* mmap_record = static_cast<const MmapRecord*>(record.get());
177 if (android::base::StartsWith(mmap_record->filename, DEFAULT_KERNEL_MMAP_NAME)) {
178 have_kernel_mmap = true;
179 break;
180 }
181 }
182 }
183 ASSERT_TRUE(have_kernel_mmap);
184 }
185
186 // @CddTest = 6.1/C-0-2
TEST(record_cmd,dump_build_id_feature)187 TEST(record_cmd, dump_build_id_feature) {
188 TemporaryFile tmpfile;
189 ASSERT_TRUE(RunRecordCmd({}, tmpfile.path));
190 std::unique_ptr<RecordFileReader> reader = RecordFileReader::CreateInstance(tmpfile.path);
191 ASSERT_TRUE(reader != nullptr);
192 const FileHeader& file_header = reader->FileHeader();
193 ASSERT_TRUE(file_header.features[FEAT_BUILD_ID / 8] & (1 << (FEAT_BUILD_ID % 8)));
194 ASSERT_GT(reader->FeatureSectionDescriptors().size(), 0u);
195 }
196
197 // @CddTest = 6.1/C-0-2
TEST(record_cmd,tracepoint_event)198 TEST(record_cmd, tracepoint_event) {
199 TEST_IN_ROOT(ASSERT_TRUE(RunRecordCmd({"-a", "-e", "sched:sched_switch"})));
200 }
201
202 // @CddTest = 6.1/C-0-2
TEST(record_cmd,rN_event)203 TEST(record_cmd, rN_event) {
204 TEST_REQUIRE_HW_COUNTER();
205 OMIT_TEST_ON_NON_NATIVE_ABIS();
206 size_t event_number;
207 if (GetTargetArch() == ARCH_ARM64 || GetTargetArch() == ARCH_ARM) {
208 // As in D5.10.2 of the ARMv8 manual, ARM defines the event number space for PMU. part of the
209 // space is for common event numbers (which will stay the same for all ARM chips), part of the
210 // space is for implementation defined events. Here 0x08 is a common event for instructions.
211 event_number = 0x08;
212 } else if (GetTargetArch() == ARCH_X86_32 || GetTargetArch() == ARCH_X86_64) {
213 // As in volume 3 chapter 19 of the Intel manual, 0x00c0 is the event number for instruction.
214 event_number = 0x00c0;
215 } else if (GetTargetArch() == ARCH_RISCV64) {
216 // RISCV_PMU_INSTRET = 1
217 event_number = 0x1;
218 } else {
219 GTEST_LOG_(INFO) << "Omit arch " << GetTargetArch();
220 return;
221 }
222 std::string event_name = android::base::StringPrintf("r%zx:u", event_number);
223 TemporaryFile tmpfile;
224 ASSERT_TRUE(RunRecordCmd({"-e", event_name}, tmpfile.path));
225 std::unique_ptr<RecordFileReader> reader = RecordFileReader::CreateInstance(tmpfile.path);
226 ASSERT_TRUE(reader);
227 const EventAttrIds& attrs = reader->AttrSection();
228 ASSERT_EQ(1u, attrs.size());
229 ASSERT_EQ(PERF_TYPE_RAW, attrs[0].attr.type);
230 ASSERT_EQ(event_number, attrs[0].attr.config);
231 }
232
233 // @CddTest = 6.1/C-0-2
TEST(record_cmd,branch_sampling)234 TEST(record_cmd, branch_sampling) {
235 TEST_REQUIRE_HW_COUNTER();
236 if (IsBranchSamplingSupported()) {
237 ASSERT_TRUE(RunRecordCmd({"-b"}));
238 ASSERT_TRUE(RunRecordCmd({"-j", "any,any_call,any_ret,ind_call"}));
239 ASSERT_TRUE(RunRecordCmd({"-j", "any,k"}));
240 ASSERT_TRUE(RunRecordCmd({"-j", "any,u"}));
241 ASSERT_FALSE(RunRecordCmd({"-j", "u"}));
242 } else {
243 GTEST_LOG_(INFO) << "This test does nothing as branch stack sampling is "
244 "not supported on this device.";
245 }
246 }
247
248 // @CddTest = 6.1/C-0-2
TEST(record_cmd,event_modifier)249 TEST(record_cmd, event_modifier) {
250 std::string event_name = GetDefaultEvent();
251 if (event_name.find(':') == std::string::npos) {
252 event_name += ":u";
253 }
254 ASSERT_TRUE(RunRecordCmd({"-e", event_name}));
255 }
256
257 // @CddTest = 6.1/C-0-2
TEST(record_cmd,fp_callchain_sampling)258 TEST(record_cmd, fp_callchain_sampling) {
259 ASSERT_TRUE(RunRecordCmd({"--call-graph", "fp"}));
260 }
261
262 // @CddTest = 6.1/C-0-2
TEST(record_cmd,fp_callchain_sampling_warning_on_arm)263 TEST(record_cmd, fp_callchain_sampling_warning_on_arm) {
264 if (GetTargetArch() != ARCH_ARM) {
265 GTEST_LOG_(INFO) << "This test does nothing as it only tests on arm arch.";
266 return;
267 }
268 ASSERT_EXIT(
269 { exit(RunRecordCmd({"--call-graph", "fp"}) ? 0 : 1); }, testing::ExitedWithCode(0),
270 "doesn't work well on arm");
271 }
272
273 // @CddTest = 6.1/C-0-2
TEST(record_cmd,system_wide_fp_callchain_sampling)274 TEST(record_cmd, system_wide_fp_callchain_sampling) {
275 TEST_IN_ROOT(ASSERT_TRUE(RunRecordCmd({"-a", "--call-graph", "fp"})));
276 }
277
278 // @CddTest = 6.1/C-0-2
TEST(record_cmd,dwarf_callchain_sampling)279 TEST(record_cmd, dwarf_callchain_sampling) {
280 OMIT_TEST_ON_NON_NATIVE_ABIS();
281 ASSERT_TRUE(IsDwarfCallChainSamplingSupported());
282 std::vector<std::unique_ptr<Workload>> workloads;
283 CreateProcesses(1, &workloads);
284 std::string pid = std::to_string(workloads[0]->GetPid());
285 ASSERT_TRUE(RunRecordCmd({"-p", pid, "--call-graph", "dwarf"}));
286 ASSERT_TRUE(RunRecordCmd({"-p", pid, "--call-graph", "dwarf,16384"}));
287 ASSERT_FALSE(RunRecordCmd({"-p", pid, "--call-graph", "dwarf,65536"}));
288 TemporaryFile tmpfile;
289 ASSERT_TRUE(RunRecordCmd({"-p", pid, "-g"}, tmpfile.path));
290 auto reader = RecordFileReader::CreateInstance(tmpfile.path);
291 ASSERT_TRUE(reader);
292 const EventAttrIds& attrs = reader->AttrSection();
293 ASSERT_GT(attrs.size(), 0);
294 // Check that reg and stack fields are removed after unwinding.
295 for (const auto& attr : attrs) {
296 ASSERT_EQ(attr.attr.sample_type & (PERF_SAMPLE_REGS_USER | PERF_SAMPLE_STACK_USER), 0);
297 }
298 }
299
300 // @CddTest = 6.1/C-0-2
TEST(record_cmd,system_wide_dwarf_callchain_sampling)301 TEST(record_cmd, system_wide_dwarf_callchain_sampling) {
302 OMIT_TEST_ON_NON_NATIVE_ABIS();
303 ASSERT_TRUE(IsDwarfCallChainSamplingSupported());
304 TEST_IN_ROOT(RunRecordCmd({"-a", "--call-graph", "dwarf"}));
305 }
306
307 // @CddTest = 6.1/C-0-2
TEST(record_cmd,no_unwind_option)308 TEST(record_cmd, no_unwind_option) {
309 OMIT_TEST_ON_NON_NATIVE_ABIS();
310 ASSERT_TRUE(IsDwarfCallChainSamplingSupported());
311 ASSERT_TRUE(RunRecordCmd({"--call-graph", "dwarf", "--no-unwind"}));
312 ASSERT_FALSE(RunRecordCmd({"--no-unwind"}));
313 }
314
315 // @CddTest = 6.1/C-0-2
TEST(record_cmd,post_unwind_option)316 TEST(record_cmd, post_unwind_option) {
317 OMIT_TEST_ON_NON_NATIVE_ABIS();
318 ASSERT_TRUE(IsDwarfCallChainSamplingSupported());
319 std::vector<std::unique_ptr<Workload>> workloads;
320 CreateProcesses(1, &workloads);
321 std::string pid = std::to_string(workloads[0]->GetPid());
322 ASSERT_TRUE(RunRecordCmd({"-p", pid, "--call-graph", "dwarf", "--post-unwind"}));
323 ASSERT_TRUE(RunRecordCmd({"-p", pid, "--call-graph", "dwarf", "--post-unwind=yes"}));
324 ASSERT_TRUE(RunRecordCmd({"-p", pid, "--call-graph", "dwarf", "--post-unwind=no"}));
325 }
326
327 // @CddTest = 6.1/C-0-2
TEST(record_cmd,existing_processes)328 TEST(record_cmd, existing_processes) {
329 std::vector<std::unique_ptr<Workload>> workloads;
330 CreateProcesses(2, &workloads);
331 std::string pid_list =
332 android::base::StringPrintf("%d,%d", workloads[0]->GetPid(), workloads[1]->GetPid());
333 ASSERT_TRUE(RunRecordCmd({"-p", pid_list}));
334 }
335
336 // @CddTest = 6.1/C-0-2
TEST(record_cmd,existing_threads)337 TEST(record_cmd, existing_threads) {
338 std::vector<std::unique_ptr<Workload>> workloads;
339 CreateProcesses(2, &workloads);
340 // Process id can also be used as thread id in linux.
341 std::string tid_list =
342 android::base::StringPrintf("%d,%d", workloads[0]->GetPid(), workloads[1]->GetPid());
343 ASSERT_TRUE(RunRecordCmd({"-t", tid_list}));
344 }
345
346 // @CddTest = 6.1/C-0-2
TEST(record_cmd,no_monitored_threads)347 TEST(record_cmd, no_monitored_threads) {
348 TemporaryFile tmpfile;
349 ASSERT_FALSE(RecordCmd()->Run({"-o", tmpfile.path}));
350 ASSERT_FALSE(RecordCmd()->Run({"-o", tmpfile.path, ""}));
351 }
352
353 // @CddTest = 6.1/C-0-2
TEST(record_cmd,more_than_one_event_types)354 TEST(record_cmd, more_than_one_event_types) {
355 ASSERT_TRUE(RunRecordCmd({"-e", "task-clock:u,cpu-clock:u"}));
356 ASSERT_TRUE(RunRecordCmd({"-e", "task-clock:u", "-e", "cpu-clock:u"}));
357 }
358
359 // @CddTest = 6.1/C-0-2
TEST(record_cmd,mmap_page_option)360 TEST(record_cmd, mmap_page_option) {
361 ASSERT_TRUE(RunRecordCmd({"-m", "1"}));
362 ASSERT_FALSE(RunRecordCmd({"-m", "0"}));
363 ASSERT_FALSE(RunRecordCmd({"-m", "7"}));
364 }
365
CheckKernelSymbol(const std::string & path,bool need_kallsyms,bool * success)366 static void CheckKernelSymbol(const std::string& path, bool need_kallsyms, bool* success) {
367 *success = false;
368 std::unique_ptr<RecordFileReader> reader = RecordFileReader::CreateInstance(path);
369 ASSERT_TRUE(reader != nullptr);
370 std::vector<std::unique_ptr<Record>> records = reader->DataSection();
371 bool has_kernel_symbol_records = false;
372 for (const auto& record : records) {
373 if (record->type() == SIMPLE_PERF_RECORD_KERNEL_SYMBOL) {
374 has_kernel_symbol_records = true;
375 }
376 }
377 std::string kallsyms;
378 bool require_kallsyms = need_kallsyms && LoadKernelSymbols(&kallsyms);
379 ASSERT_EQ(require_kallsyms, has_kernel_symbol_records);
380 *success = true;
381 }
382
383 // @CddTest = 6.1/C-0-2
TEST(record_cmd,kernel_symbol)384 TEST(record_cmd, kernel_symbol) {
385 TemporaryFile tmpfile;
386 ASSERT_TRUE(RunRecordCmd({"--no-dump-symbols"}, tmpfile.path));
387 bool success;
388 CheckKernelSymbol(tmpfile.path, true, &success);
389 ASSERT_TRUE(success);
390 ASSERT_TRUE(RunRecordCmd({"--no-dump-symbols", "--no-dump-kernel-symbols"}, tmpfile.path));
391 CheckKernelSymbol(tmpfile.path, false, &success);
392 ASSERT_TRUE(success);
393 }
394
ProcessSymbolsInPerfDataFile(const std::string & perf_data_file,const std::function<bool (const Symbol &,uint32_t)> & callback)395 static void ProcessSymbolsInPerfDataFile(
396 const std::string& perf_data_file,
397 const std::function<bool(const Symbol&, uint32_t)>& callback) {
398 auto reader = RecordFileReader::CreateInstance(perf_data_file);
399 ASSERT_TRUE(reader);
400 FileFeature file;
401 uint64_t read_pos = 0;
402 bool error = false;
403 while (reader->ReadFileFeature(read_pos, file, error)) {
404 for (const auto& symbol : file.symbols) {
405 if (callback(symbol, file.type)) {
406 return;
407 }
408 }
409 }
410 ASSERT_FALSE(error);
411 }
412
413 // Check if dumped symbols in perf.data matches our expectation.
CheckDumpedSymbols(const std::string & path,bool allow_dumped_symbols)414 static bool CheckDumpedSymbols(const std::string& path, bool allow_dumped_symbols) {
415 bool has_dumped_symbols = false;
416 auto callback = [&](const Symbol&, uint32_t) {
417 has_dumped_symbols = true;
418 return true;
419 };
420 ProcessSymbolsInPerfDataFile(path, callback);
421 // It is possible that there are no samples hitting functions having symbols.
422 // So "allow_dumped_symbols = true" doesn't guarantee "has_dumped_symbols = true".
423 if (!allow_dumped_symbols && has_dumped_symbols) {
424 return false;
425 }
426 return true;
427 }
428
429 // @CddTest = 6.1/C-0-2
TEST(record_cmd,no_dump_symbols)430 TEST(record_cmd, no_dump_symbols) {
431 TemporaryFile tmpfile;
432 ASSERT_TRUE(RunRecordCmd({}, tmpfile.path));
433 ASSERT_TRUE(CheckDumpedSymbols(tmpfile.path, true));
434 ASSERT_TRUE(RunRecordCmd({"--no-dump-symbols", "--no-dump-kernel-symbols"}, tmpfile.path));
435 ASSERT_TRUE(CheckDumpedSymbols(tmpfile.path, false));
436 OMIT_TEST_ON_NON_NATIVE_ABIS();
437 ASSERT_TRUE(IsDwarfCallChainSamplingSupported());
438 std::vector<std::unique_ptr<Workload>> workloads;
439 CreateProcesses(1, &workloads);
440 std::string pid = std::to_string(workloads[0]->GetPid());
441 ASSERT_TRUE(RunRecordCmd({"-p", pid, "-g"}, tmpfile.path));
442 ASSERT_TRUE(CheckDumpedSymbols(tmpfile.path, true));
443 ASSERT_TRUE(RunRecordCmd({"-p", pid, "-g", "--no-dump-symbols", "--no-dump-kernel-symbols"},
444 tmpfile.path));
445 ASSERT_TRUE(CheckDumpedSymbols(tmpfile.path, false));
446 }
447
448 // @CddTest = 6.1/C-0-2
TEST(record_cmd,dump_kernel_symbols)449 TEST(record_cmd, dump_kernel_symbols) {
450 TEST_REQUIRE_ROOT();
451 TemporaryFile tmpfile;
452 ASSERT_TRUE(RecordCmd()->Run({"-a", "-o", tmpfile.path, "-e", GetDefaultEvent(), "sleep", "1"}));
453 bool has_kernel_symbols = false;
454 auto callback = [&](const Symbol&, uint32_t file_type) {
455 if (file_type == DSO_KERNEL) {
456 has_kernel_symbols = true;
457 }
458 return has_kernel_symbols;
459 };
460 ProcessSymbolsInPerfDataFile(tmpfile.path, callback);
461 ASSERT_TRUE(has_kernel_symbols);
462 }
463
464 // @CddTest = 6.1/C-0-2
TEST(record_cmd,group_option)465 TEST(record_cmd, group_option) {
466 ASSERT_TRUE(RunRecordCmd({"--group", "task-clock:u,cpu-clock:u", "-m", "16"}));
467 if (IsRoot()) {
468 ASSERT_TRUE(
469 RunRecordCmd({"--group", "task-clock,cpu-clock", "--group", "task-clock:u,cpu-clock:u",
470 "--group", "task-clock:k,cpu-clock:k", "-m", "16"}));
471 }
472 }
473
474 // @CddTest = 6.1/C-0-2
TEST(record_cmd,symfs_option)475 TEST(record_cmd, symfs_option) {
476 ASSERT_TRUE(RunRecordCmd({"--symfs", "/"}));
477 }
478
479 // @CddTest = 6.1/C-0-2
TEST(record_cmd,duration_option)480 TEST(record_cmd, duration_option) {
481 TemporaryFile tmpfile;
482 ASSERT_TRUE(RecordCmd()->Run({"--duration", "1.2", "-p", std::to_string(getpid()), "-o",
483 tmpfile.path, "--in-app", "-e", GetDefaultEvent()}));
484 ASSERT_TRUE(RecordCmd()->Run(
485 {"--duration", "1", "-o", tmpfile.path, "-e", GetDefaultEvent(), "sleep", "2"}));
486 }
487
488 // @CddTest = 6.1/C-0-2
TEST(record_cmd,support_modifier_for_clock_events)489 TEST(record_cmd, support_modifier_for_clock_events) {
490 TEST_REQUIRE_KERNEL_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 << ":" << m;
494 }
495 }
496 }
497
498 // @CddTest = 6.1/C-0-2
TEST(record_cmd,handle_SIGHUP)499 TEST(record_cmd, handle_SIGHUP) {
500 TemporaryFile tmpfile;
501 int pipefd[2];
502 ASSERT_EQ(0, pipe(pipefd));
503 int read_fd = pipefd[0];
504 int write_fd = pipefd[1];
505 char data[8] = {};
506 std::thread thread([&]() {
507 android::base::ReadFully(read_fd, data, 7);
508 kill(getpid(), SIGHUP);
509 });
510 ASSERT_TRUE(
511 RecordCmd()->Run({"-o", tmpfile.path, "--start_profiling_fd", std::to_string(write_fd), "-e",
512 GetDefaultEvent(), "sleep", "1000000"}));
513 thread.join();
514 close(write_fd);
515 close(read_fd);
516 ASSERT_STREQ(data, "STARTED");
517 }
518
519 // @CddTest = 6.1/C-0-2
TEST(record_cmd,stop_when_no_more_targets)520 TEST(record_cmd, stop_when_no_more_targets) {
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(
530 {"-o", tmpfile.path, "-t", std::to_string(tid), "--in-app", "-e", GetDefaultEvent()}));
531 }
532
533 // @CddTest = 6.1/C-0-2
TEST(record_cmd,donot_stop_when_having_targets)534 TEST(record_cmd, donot_stop_when_having_targets) {
535 std::vector<std::unique_ptr<Workload>> workloads;
536 CreateProcesses(1, &workloads);
537 std::string pid = std::to_string(workloads[0]->GetPid());
538 uint64_t start_time_in_ns = GetSystemClock();
539 TemporaryFile tmpfile;
540 ASSERT_TRUE(RecordCmd()->Run(
541 {"-o", tmpfile.path, "-p", pid, "--duration", "3", "-e", GetDefaultEvent()}));
542 uint64_t end_time_in_ns = GetSystemClock();
543 ASSERT_GT(end_time_in_ns - start_time_in_ns, static_cast<uint64_t>(2e9));
544 }
545
546 // @CddTest = 6.1/C-0-2
TEST(record_cmd,start_profiling_fd_option)547 TEST(record_cmd, start_profiling_fd_option) {
548 int pipefd[2];
549 ASSERT_EQ(0, pipe(pipefd));
550 int read_fd = pipefd[0];
551 int write_fd = pipefd[1];
552 ASSERT_EXIT(
553 {
554 close(read_fd);
555 exit(RunRecordCmd({"--start_profiling_fd", std::to_string(write_fd)}) ? 0 : 1);
556 },
557 testing::ExitedWithCode(0), "");
558 close(write_fd);
559 std::string s;
560 ASSERT_TRUE(android::base::ReadFdToString(read_fd, &s));
561 close(read_fd);
562 ASSERT_EQ("STARTED", s);
563 }
564
565 // @CddTest = 6.1/C-0-2
TEST(record_cmd,record_meta_info_feature)566 TEST(record_cmd, record_meta_info_feature) {
567 TemporaryFile tmpfile;
568 ASSERT_TRUE(RunRecordCmd({}, tmpfile.path));
569 std::unique_ptr<RecordFileReader> reader = RecordFileReader::CreateInstance(tmpfile.path);
570 ASSERT_TRUE(reader);
571 auto& info_map = reader->GetMetaInfoFeature();
572 ASSERT_NE(info_map.find("simpleperf_version"), info_map.end());
573 ASSERT_NE(info_map.find("timestamp"), info_map.end());
574 ASSERT_NE(info_map.find("record_stat"), info_map.end());
575 #if defined(__ANDROID__)
576 ASSERT_NE(info_map.find("product_props"), info_map.end());
577 ASSERT_NE(info_map.find("android_version"), info_map.end());
578 #endif
579 }
580
581 // See http://b/63135835.
582 // @CddTest = 6.1/C-0-2
TEST(record_cmd,cpu_clock_for_a_long_time)583 TEST(record_cmd, cpu_clock_for_a_long_time) {
584 std::vector<std::unique_ptr<Workload>> workloads;
585 CreateProcesses(1, &workloads);
586 std::string pid = std::to_string(workloads[0]->GetPid());
587 TemporaryFile tmpfile;
588 ASSERT_TRUE(
589 RecordCmd()->Run({"-e", "cpu-clock:u", "-o", tmpfile.path, "-p", pid, "--duration", "3"}));
590 }
591
592 // @CddTest = 6.1/C-0-2
TEST(record_cmd,dump_regs_for_tracepoint_events)593 TEST(record_cmd, dump_regs_for_tracepoint_events) {
594 TEST_REQUIRE_HOST_ROOT();
595 TEST_REQUIRE_TRACEPOINT_EVENTS();
596 OMIT_TEST_ON_NON_NATIVE_ABIS();
597 // Check if the kernel can dump registers for tracepoint events.
598 // If not, probably a kernel patch below is missing:
599 // "5b09a094f2 arm64: perf: Fix callchain parse error with kernel tracepoint events"
600 ASSERT_TRUE(IsDumpingRegsForTracepointEventsSupported());
601 }
602
603 // @CddTest = 6.1/C-0-2
TEST(record_cmd,trace_offcpu_option)604 TEST(record_cmd, trace_offcpu_option) {
605 TEST_REQUIRE_KERNEL_EVENTS();
606 // On linux host, we need root privilege to read tracepoint events.
607 TEST_REQUIRE_HOST_ROOT();
608 TEST_REQUIRE_TRACEPOINT_EVENTS();
609 OMIT_TEST_ON_NON_NATIVE_ABIS();
610 TemporaryFile tmpfile;
611 ASSERT_TRUE(RunRecordCmd({"--trace-offcpu", "-e", "cpu-clock", "-f", "1000"}, tmpfile.path));
612 CheckEventType(tmpfile.path, "sched:sched_switch", 1u, 0u);
613 std::unique_ptr<RecordFileReader> reader = RecordFileReader::CreateInstance(tmpfile.path);
614 ASSERT_TRUE(reader);
615 auto info_map = reader->GetMetaInfoFeature();
616 ASSERT_EQ(info_map["trace_offcpu"], "true");
617 if (IsSwitchRecordSupported()) {
618 ASSERT_EQ(reader->AttrSection()[0].attr.context_switch, 1);
619 }
620 // Release recording environment in perf.data, to avoid affecting tests below.
621 reader.reset();
622
623 // --trace-offcpu only works with cpu-clock and task-clock. cpu-clock has been tested above.
624 ASSERT_TRUE(RunRecordCmd({"--trace-offcpu", "-e", "task-clock"}));
625 ASSERT_FALSE(RunRecordCmd({"--trace-offcpu", "-e", "page-faults"}));
626 // --trace-offcpu doesn't work with more than one event.
627 ASSERT_FALSE(RunRecordCmd({"--trace-offcpu", "-e", "cpu-clock,task-clock"}));
628 }
629
630 // @CddTest = 6.1/C-0-2
TEST(record_cmd,exit_with_parent_option)631 TEST(record_cmd, exit_with_parent_option) {
632 ASSERT_TRUE(RunRecordCmd({"--exit-with-parent"}));
633 }
634
635 // @CddTest = 6.1/C-0-2
TEST(record_cmd,use_cmd_exit_code_option)636 TEST(record_cmd, use_cmd_exit_code_option) {
637 TemporaryFile tmpfile;
638 int exit_code;
639 RecordCmd()->Run({"-e", GetDefaultEvent(), "--use-cmd-exit-code", "-o", tmpfile.path, "ls", "."},
640 &exit_code);
641 ASSERT_EQ(exit_code, 0);
642 RecordCmd()->Run(
643 {"-e", GetDefaultEvent(), "--use-cmd-exit-code", "-o", tmpfile.path, "ls", "/not_exist_path"},
644 &exit_code);
645 ASSERT_NE(exit_code, 0);
646 }
647
648 // @CddTest = 6.1/C-0-2
TEST(record_cmd,clockid_option)649 TEST(record_cmd, clockid_option) {
650 if (!IsSettingClockIdSupported()) {
651 ASSERT_FALSE(RunRecordCmd({"--clockid", "monotonic"}));
652 } else {
653 TemporaryFile tmpfile;
654 ASSERT_TRUE(RunRecordCmd({"--clockid", "monotonic"}, 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["clockid"], "monotonic");
659 }
660 }
661
662 // @CddTest = 6.1/C-0-2
TEST(record_cmd,generate_samples_by_hw_counters)663 TEST(record_cmd, generate_samples_by_hw_counters) {
664 TEST_REQUIRE_HW_COUNTER();
665 std::vector<std::string> events = {"cpu-cycles:u", "instructions:u"};
666 for (auto& event : events) {
667 TemporaryFile tmpfile;
668 ASSERT_TRUE(RecordCmd()->Run({"-e", event, "-o", tmpfile.path, "sleep", "1"}));
669 std::unique_ptr<RecordFileReader> reader = RecordFileReader::CreateInstance(tmpfile.path);
670 ASSERT_TRUE(reader);
671 bool has_sample = false;
672 ASSERT_TRUE(reader->ReadDataSection([&](std::unique_ptr<Record> r) {
673 if (r->type() == PERF_RECORD_SAMPLE) {
674 has_sample = true;
675 }
676 return true;
677 }));
678 ASSERT_TRUE(has_sample);
679 }
680 }
681
682 // @CddTest = 6.1/C-0-2
TEST(record_cmd,callchain_joiner_options)683 TEST(record_cmd, callchain_joiner_options) {
684 ASSERT_TRUE(RunRecordCmd({"--no-callchain-joiner"}));
685 ASSERT_TRUE(RunRecordCmd({"--callchain-joiner-min-matching-nodes", "2"}));
686 }
687
688 // @CddTest = 6.1/C-0-2
TEST(record_cmd,dashdash)689 TEST(record_cmd, dashdash) {
690 TemporaryFile tmpfile;
691 ASSERT_TRUE(RecordCmd()->Run({"-o", tmpfile.path, "-e", GetDefaultEvent(), "--", "sleep", "1"}));
692 }
693
694 // @CddTest = 6.1/C-0-2
TEST(record_cmd,size_limit_option)695 TEST(record_cmd, size_limit_option) {
696 std::vector<std::unique_ptr<Workload>> workloads;
697 CreateProcesses(1, &workloads);
698 std::string pid = std::to_string(workloads[0]->GetPid());
699 TemporaryFile tmpfile;
700 ASSERT_TRUE(RecordCmd()->Run({"-o", tmpfile.path, "-p", pid, "--size-limit", "1k", "--duration",
701 "1", "-e", GetDefaultEvent()}));
702 std::unique_ptr<RecordFileReader> reader = RecordFileReader::CreateInstance(tmpfile.path);
703 ASSERT_TRUE(reader);
704 ASSERT_GT(reader->FileHeader().data.size, 1000u);
705 ASSERT_LT(reader->FileHeader().data.size, 2000u);
706 ASSERT_FALSE(RunRecordCmd({"--size-limit", "0"}));
707 }
708
709 // @CddTest = 6.1/C-0-2
TEST(record_cmd,support_mmap2)710 TEST(record_cmd, support_mmap2) {
711 // mmap2 is supported in kernel >= 3.16. If not supported, please cherry pick below kernel
712 // patches:
713 // 13d7a2410fa637 perf: Add attr->mmap2 attribute to an event
714 // f972eb63b1003f perf: Pass protection and flags bits through mmap2 interface.
715 ASSERT_TRUE(IsMmap2Supported());
716 }
717
718 // @CddTest = 6.1/C-0-2
TEST(record_cmd,kernel_bug_making_zero_dyn_size)719 TEST(record_cmd, kernel_bug_making_zero_dyn_size) {
720 // Test a kernel bug that makes zero dyn_size in kernel < 3.13. If it fails, please cherry pick
721 // below kernel patch: 0a196848ca365e perf: Fix arch_perf_out_copy_user default
722 OMIT_TEST_ON_NON_NATIVE_ABIS();
723 std::vector<std::unique_ptr<Workload>> workloads;
724 CreateProcesses(1, &workloads);
725 std::string pid = std::to_string(workloads[0]->GetPid());
726 TemporaryFile tmpfile;
727 ASSERT_TRUE(RecordCmd()->Run({"-o", tmpfile.path, "-p", pid, "--call-graph", "dwarf,8",
728 "--no-unwind", "--duration", "1", "-e", GetDefaultEvent()}));
729 std::unique_ptr<RecordFileReader> reader = RecordFileReader::CreateInstance(tmpfile.path);
730 ASSERT_TRUE(reader);
731 bool has_sample = false;
732 ASSERT_TRUE(reader->ReadDataSection([&](std::unique_ptr<Record> r) {
733 if (r->type() == PERF_RECORD_SAMPLE && !r->InKernel()) {
734 SampleRecord* sr = static_cast<SampleRecord*>(r.get());
735 if (sr->stack_user_data.dyn_size == 0) {
736 return false;
737 }
738 has_sample = true;
739 }
740 return true;
741 }));
742 ASSERT_TRUE(has_sample);
743 }
744
745 // @CddTest = 6.1/C-0-2
TEST(record_cmd,kernel_bug_making_zero_dyn_size_for_kernel_samples)746 TEST(record_cmd, kernel_bug_making_zero_dyn_size_for_kernel_samples) {
747 // Test a kernel bug that makes zero dyn_size for syscalls of 32-bit applications in 64-bit
748 // kernels. If it fails, please cherry pick below kernel patch:
749 // 02e184476eff8 perf/core: Force USER_DS when recording user stack data
750 OMIT_TEST_ON_NON_NATIVE_ABIS();
751 TEST_REQUIRE_ROOT();
752 TEST_REQUIRE_TRACEPOINT_EVENTS();
753 std::vector<std::unique_ptr<Workload>> workloads;
754 CreateProcesses(1, &workloads);
755 std::string pid = std::to_string(workloads[0]->GetPid());
756 TemporaryFile tmpfile;
757 ASSERT_TRUE(RecordCmd()->Run({"-e", "sched:sched_switch", "-o", tmpfile.path, "-p", pid,
758 "--call-graph", "dwarf,8", "--no-unwind", "--duration", "1"}));
759 std::unique_ptr<RecordFileReader> reader = RecordFileReader::CreateInstance(tmpfile.path);
760 ASSERT_TRUE(reader);
761 bool has_sample = false;
762 ASSERT_TRUE(reader->ReadDataSection([&](std::unique_ptr<Record> r) {
763 if (r->type() == PERF_RECORD_SAMPLE && r->InKernel()) {
764 SampleRecord* sr = static_cast<SampleRecord*>(r.get());
765 if (sr->stack_user_data.dyn_size == 0) {
766 return false;
767 }
768 has_sample = true;
769 }
770 return true;
771 }));
772 ASSERT_TRUE(has_sample);
773 }
774
775 // @CddTest = 6.1/C-0-2
TEST(record_cmd,cpu_percent_option)776 TEST(record_cmd, cpu_percent_option) {
777 ASSERT_TRUE(RunRecordCmd({"--cpu-percent", "50"}));
778 ASSERT_FALSE(RunRecordCmd({"--cpu-percent", "0"}));
779 ASSERT_FALSE(RunRecordCmd({"--cpu-percent", "101"}));
780 }
781
782 class RecordingAppHelper {
783 public:
InstallApk(const std::string & apk_path,const std::string & package_name)784 bool InstallApk(const std::string& apk_path, const std::string& package_name) {
785 return app_helper_.InstallApk(apk_path, package_name);
786 }
787
StartApp(const std::string & start_cmd)788 bool StartApp(const std::string& start_cmd) { return app_helper_.StartApp(start_cmd); }
789
RecordData(const std::string & record_cmd)790 bool RecordData(const std::string& record_cmd) {
791 std::vector<std::string> args = android::base::Split(record_cmd, " ");
792 // record_cmd may end with child command. We should put output options before it.
793 args.emplace(args.begin(), "-o");
794 args.emplace(args.begin() + 1, GetDataPath());
795 return RecordCmd()->Run(args);
796 }
797
CheckData(const std::function<bool (const char *)> & process_symbol)798 bool CheckData(const std::function<bool(const char*)>& process_symbol) {
799 bool success = false;
800 auto callback = [&](const Symbol& symbol, uint32_t) {
801 if (process_symbol(symbol.DemangledName())) {
802 success = true;
803 }
804 return success;
805 };
806 ProcessSymbolsInPerfDataFile(GetDataPath(), callback);
807 size_t sample_count = GetSampleCount();
808 if (!success) {
809 if (IsInEmulator()) {
810 // In emulator, the monitored app may not have a chance to run.
811 constexpr size_t MIN_SAMPLES_TO_CHECK_SYMBOLS = 1000;
812 if (size_t sample_count = GetSampleCount(); sample_count < MIN_SAMPLES_TO_CHECK_SYMBOLS) {
813 GTEST_LOG_(INFO) << "Only " << sample_count
814 << " samples recorded in the emulator. Skip checking symbols (need "
815 << MIN_SAMPLES_TO_CHECK_SYMBOLS << " samples).";
816 return true;
817 }
818 }
819 DumpData();
820 }
821 return success;
822 }
823
DumpData()824 void DumpData() { CreateCommandInstance("report")->Run({"-i", GetDataPath()}); }
825
GetDataPath() const826 std::string GetDataPath() const { return perf_data_file_.path; }
827
828 private:
GetSampleCount()829 size_t GetSampleCount() {
830 size_t sample_count = 0;
831 std::unique_ptr<RecordFileReader> reader = RecordFileReader::CreateInstance(GetDataPath());
832 if (!reader) {
833 return sample_count;
834 }
835 auto process_record = [&](std::unique_ptr<Record> r) {
836 if (r->type() == PERF_RECORD_SAMPLE) {
837 sample_count++;
838 }
839 return true;
840 };
841 if (!reader->ReadDataSection(process_record)) {
842 return sample_count;
843 }
844 return sample_count;
845 }
846
847 AppHelper app_helper_;
848 TemporaryFile perf_data_file_;
849 };
850
TestRecordingApps(const std::string & app_name,const std::string & app_type)851 static void TestRecordingApps(const std::string& app_name, const std::string& app_type) {
852 RecordingAppHelper helper;
853 // Bring the app to foreground to avoid no samples.
854 ASSERT_TRUE(helper.StartApp("am start " + app_name + "/.MainActivity"));
855
856 ASSERT_TRUE(helper.RecordData("--app " + app_name + " -g --duration 10 -e " + GetDefaultEvent()));
857
858 // Check if we can profile Java code by looking for a Java method name in dumped symbols, which
859 // is app_name + ".MainActivity$1.run".
860 const std::string expected_class_name = app_name + ".MainActivity";
861 const std::string expected_method_name = "run";
862 auto process_symbol = [&](const char* name) {
863 return strstr(name, expected_class_name.c_str()) != nullptr &&
864 strstr(name, expected_method_name.c_str()) != nullptr;
865 };
866 ASSERT_TRUE(helper.CheckData(process_symbol));
867
868 // Check app_package_name and app_type.
869 auto reader = RecordFileReader::CreateInstance(helper.GetDataPath());
870 ASSERT_TRUE(reader);
871 const std::unordered_map<std::string, std::string>& meta_info = reader->GetMetaInfoFeature();
872 auto it = meta_info.find("app_package_name");
873 ASSERT_NE(it, meta_info.end());
874 ASSERT_EQ(it->second, app_name);
875 it = meta_info.find("app_type");
876 ASSERT_NE(it, meta_info.end());
877 ASSERT_EQ(it->second, app_type);
878
879 if (!IsRoot()) {
880 // Check that we are not leaking kernel ip addresses.
881 auto process_record = [](std::unique_ptr<Record> r) {
882 if (r->type() == PERF_RECORD_SAMPLE) {
883 const SampleRecord* sr = static_cast<const SampleRecord*>(r.get());
884 if (sr->InKernel()) {
885 return false;
886 }
887 }
888 return true;
889 };
890 ASSERT_TRUE(reader->ReadDataSection(process_record));
891 }
892 reader.reset(nullptr);
893
894 // Check that simpleperf can't execute child command in app uid.
895 if (!IsRoot()) {
896 ASSERT_FALSE(helper.RecordData("--app " + app_name + " -e " + GetDefaultEvent() + " sleep 1"));
897 }
898 }
899
900 // @CddTest = 6.1/C-0-2
TEST(record_cmd,app_option_for_debuggable_app)901 TEST(record_cmd, app_option_for_debuggable_app) {
902 OMIT_TEST_ON_NON_NATIVE_ABIS();
903 TEST_REQUIRE_APPS();
904 TestRecordingApps("com.android.simpleperf.debuggable", "debuggable");
905 SetRunInAppToolForTesting(true, false);
906 TestRecordingApps("com.android.simpleperf.debuggable", "debuggable");
907 SetRunInAppToolForTesting(true, true);
908 }
909
910 // @CddTest = 6.1/C-0-2
TEST(record_cmd,app_option_for_profileable_app)911 TEST(record_cmd, app_option_for_profileable_app) {
912 OMIT_TEST_ON_NON_NATIVE_ABIS();
913 TEST_REQUIRE_APPS();
914 TestRecordingApps("com.android.simpleperf.profileable", "profileable");
915 }
916
917 #if defined(__ANDROID__)
RecordJavaApp(RecordingAppHelper & helper)918 static void RecordJavaApp(RecordingAppHelper& helper) {
919 // 1. Install apk.
920 ASSERT_TRUE(helper.InstallApk(GetTestData("DisplayBitmaps.apk"),
921 "com.example.android.displayingbitmaps"));
922 ASSERT_TRUE(helper.InstallApk(GetTestData("DisplayBitmapsTest.apk"),
923 "com.example.android.displayingbitmaps.test"));
924
925 // 2. Start the app.
926 ASSERT_TRUE(
927 helper.StartApp("am instrument -w -r -e debug false -e class "
928 "com.example.android.displayingbitmaps.tests.GridViewTest "
929 "com.example.android.displayingbitmaps.test/"
930 "androidx.test.runner.AndroidJUnitRunner"));
931
932 // 3. Record perf.data.
933 ASSERT_TRUE(helper.RecordData(
934 "-e cpu-clock --app com.example.android.displayingbitmaps -g --duration 15"));
935 }
936 #endif // defined(__ANDROID__)
937
938 // @CddTest = 6.1/C-0-2
TEST(record_cmd,record_java_app)939 TEST(record_cmd, record_java_app) {
940 #if defined(__ANDROID__)
941 OMIT_TEST_ON_NON_NATIVE_ABIS();
942 RecordingAppHelper helper;
943
944 RecordJavaApp(helper);
945 if (HasFailure()) {
946 return;
947 }
948
949 // Check perf.data by looking for java symbols.
950 const char* java_symbols[] = {
951 "androidx.test.runner",
952 "androidx.test.espresso",
953 "android.app.ActivityThread.main",
954 };
955 auto process_symbol = [&](const char* name) {
956 for (const char* java_symbol : java_symbols) {
957 if (strstr(name, java_symbol) != nullptr) {
958 return true;
959 }
960 }
961 return false;
962 };
963 ASSERT_TRUE(helper.CheckData(process_symbol));
964 #else
965 GTEST_LOG_(INFO) << "This test tests a function only available on Android.";
966 #endif
967 }
968
969 // @CddTest = 6.1/C-0-2
TEST(record_cmd,record_native_app)970 TEST(record_cmd, record_native_app) {
971 #if defined(__ANDROID__)
972 // In case of non-native ABI guest symbols are never directly executed, thus
973 // don't appear in perf.data. Instead binary translator executes code
974 // translated from guest at runtime.
975 OMIT_TEST_ON_NON_NATIVE_ABIS();
976
977 RecordingAppHelper helper;
978 // 1. Install apk.
979 ASSERT_TRUE(helper.InstallApk(GetTestData("EndlessTunnel.apk"), "com.google.sample.tunnel"));
980
981 // 2. Start the app.
982 ASSERT_TRUE(
983 helper.StartApp("am start -n com.google.sample.tunnel/android.app.NativeActivity -a "
984 "android.intent.action.MAIN -c android.intent.category.LAUNCHER"));
985
986 // 3. Record perf.data.
987 ASSERT_TRUE(helper.RecordData("-e cpu-clock --app com.google.sample.tunnel -g --duration 10"));
988
989 // 4. Check perf.data.
990 auto process_symbol = [&](const char* name) {
991 const char* expected_name_with_keyguard = "NativeActivity"; // when screen is locked
992 if (strstr(name, expected_name_with_keyguard) != nullptr) {
993 return true;
994 }
995 const char* expected_name = "PlayScene::DoFrame"; // when screen is awake
996 return strstr(name, expected_name) != nullptr;
997 };
998 ASSERT_TRUE(helper.CheckData(process_symbol));
999 #else
1000 GTEST_LOG_(INFO) << "This test tests a function only available on Android.";
1001 #endif
1002 }
1003
1004 // @CddTest = 6.1/C-0-2
TEST(record_cmd,check_trampoline_after_art_jni_methods)1005 TEST(record_cmd, check_trampoline_after_art_jni_methods) {
1006 // Test if art jni methods are called by art_jni_trampoline.
1007 #if defined(__ANDROID__)
1008 OMIT_TEST_ON_NON_NATIVE_ABIS();
1009 RecordingAppHelper helper;
1010
1011 RecordJavaApp(helper);
1012 if (HasFailure()) {
1013 return;
1014 }
1015
1016 // Check if art::Method_invoke() is called by art_jni_trampoline.
1017 auto reader = RecordFileReader::CreateInstance(helper.GetDataPath());
1018 ASSERT_TRUE(reader);
1019 ThreadTree thread_tree;
1020 ASSERT_TRUE(reader->LoadBuildIdAndFileFeatures(thread_tree));
1021
1022 auto get_symbol_name = [&](ThreadEntry* thread, uint64_t ip) -> std::string {
1023 const MapEntry* map = thread_tree.FindMap(thread, ip, false);
1024 const Symbol* symbol = thread_tree.FindSymbol(map, ip, nullptr, nullptr);
1025 return symbol->DemangledName();
1026 };
1027
1028 bool has_check = false;
1029
1030 auto process_record = [&](std::unique_ptr<Record> r) {
1031 thread_tree.Update(*r);
1032 if (r->type() == PERF_RECORD_SAMPLE) {
1033 auto sample = static_cast<SampleRecord*>(r.get());
1034 ThreadEntry* thread = thread_tree.FindThreadOrNew(sample->tid_data.pid, sample->tid_data.tid);
1035 size_t kernel_ip_count;
1036 std::vector<uint64_t> ips = sample->GetCallChain(&kernel_ip_count);
1037 for (size_t i = kernel_ip_count; i < ips.size(); i++) {
1038 std::string sym_name = get_symbol_name(thread, ips[i]);
1039 if (android::base::StartsWith(sym_name, "art::Method_invoke") && i + 1 < ips.size()) {
1040 has_check = true;
1041 std::string name = get_symbol_name(thread, ips[i + 1]);
1042 if (android::base::EndsWith(name, "jni_trampoline")) {
1043 continue;
1044 }
1045 // When the jni_trampoline function is from JIT cache, we may not get map info in time.
1046 // To avoid test flakiness, we accept this.
1047 // Case 1: It doesn't hit any maps.
1048 if (name == "unknown") {
1049 continue;
1050 }
1051 // Case 2: It hits an old map for JIT cache.
1052 if (const MapEntry* map = thread_tree.FindMap(thread, ips[i + 1], false);
1053 JITDebugReader::IsPathInJITSymFile(map->dso->Path())) {
1054 continue;
1055 }
1056
1057 GTEST_LOG_(ERROR) << "unexpected symbol after art::Method_invoke: " << name;
1058 return false;
1059 }
1060 }
1061 }
1062 return true;
1063 };
1064 ASSERT_TRUE(reader->ReadDataSection(process_record));
1065 ASSERT_TRUE(has_check);
1066 #else
1067 GTEST_LOG_(INFO) << "This test tests a function only available on Android.";
1068 #endif
1069 }
1070
1071 // @CddTest = 6.1/C-0-2
TEST(record_cmd,no_cut_samples_option)1072 TEST(record_cmd, no_cut_samples_option) {
1073 ASSERT_TRUE(RunRecordCmd({"--no-cut-samples"}));
1074 }
1075
1076 // @CddTest = 6.1/C-0-2
TEST(record_cmd,cs_etm_event)1077 TEST(record_cmd, cs_etm_event) {
1078 if (!ETMRecorder::GetInstance().CheckEtmSupport().ok()) {
1079 GTEST_LOG_(INFO) << "Omit this test since etm isn't supported on this device";
1080 return;
1081 }
1082 TemporaryFile tmpfile;
1083 ASSERT_TRUE(RunRecordCmd({"-e", "cs-etm"}, tmpfile.path));
1084 std::unique_ptr<RecordFileReader> reader = RecordFileReader::CreateInstance(tmpfile.path);
1085 ASSERT_TRUE(reader);
1086
1087 // cs-etm uses sample period instead of sample freq.
1088 ASSERT_EQ(reader->AttrSection().size(), 1u);
1089 const perf_event_attr& attr = reader->AttrSection()[0].attr;
1090 ASSERT_EQ(attr.freq, 0);
1091 ASSERT_EQ(attr.sample_period, 1);
1092
1093 bool has_auxtrace_info = false;
1094 bool has_auxtrace = false;
1095 bool has_aux = false;
1096 ASSERT_TRUE(reader->ReadDataSection([&](std::unique_ptr<Record> r) {
1097 if (r->type() == PERF_RECORD_AUXTRACE_INFO) {
1098 has_auxtrace_info = true;
1099 } else if (r->type() == PERF_RECORD_AUXTRACE) {
1100 has_auxtrace = true;
1101 } else if (r->type() == PERF_RECORD_AUX) {
1102 has_aux = true;
1103 }
1104 return true;
1105 }));
1106 ASSERT_TRUE(has_auxtrace_info);
1107 ASSERT_TRUE(has_auxtrace);
1108 ASSERT_TRUE(has_aux);
1109 ASSERT_TRUE(!reader->ReadBuildIdFeature().empty());
1110 }
1111
1112 // @CddTest = 6.1/C-0-2
TEST(record_cmd,cs_etm_system_wide)1113 TEST(record_cmd, cs_etm_system_wide) {
1114 TEST_REQUIRE_ROOT();
1115 if (!ETMRecorder::GetInstance().CheckEtmSupport().ok()) {
1116 GTEST_LOG_(INFO) << "Omit this test since etm isn't supported on this device";
1117 return;
1118 }
1119 TemporaryFile tmpfile;
1120 ASSERT_TRUE(RunRecordCmd({"-e", "cs-etm", "-a"}, tmpfile.path));
1121 // Check if build ids are dumped.
1122 std::unique_ptr<RecordFileReader> reader = RecordFileReader::CreateInstance(tmpfile.path);
1123 ASSERT_TRUE(reader);
1124
1125 bool has_kernel_build_id = false;
1126 for (const auto& build_id_record : reader->ReadBuildIdFeature()) {
1127 if (strcmp(build_id_record.filename, DEFAULT_KERNEL_MMAP_NAME) == 0) {
1128 has_kernel_build_id = true;
1129 break;
1130 }
1131 }
1132 ASSERT_TRUE(has_kernel_build_id);
1133
1134 // build ids are not dumped if --no-dump-build-id is used.
1135 ASSERT_TRUE(RunRecordCmd({"-e", "cs-etm", "-a", "--no-dump-build-id"}, tmpfile.path));
1136 reader = RecordFileReader::CreateInstance(tmpfile.path);
1137 ASSERT_TRUE(reader);
1138 ASSERT_TRUE(reader->ReadBuildIdFeature().empty());
1139 }
1140
1141 // @CddTest = 6.1/C-0-2
TEST(record_cmd,aux_buffer_size_option)1142 TEST(record_cmd, aux_buffer_size_option) {
1143 if (!ETMRecorder::GetInstance().CheckEtmSupport().ok()) {
1144 GTEST_LOG_(INFO) << "Omit this test since etm isn't supported on this device";
1145 return;
1146 }
1147 ASSERT_TRUE(RunRecordCmd({"-e", "cs-etm", "--aux-buffer-size", "1m"}));
1148 // not page size aligned
1149 ASSERT_FALSE(RunRecordCmd({"-e", "cs-etm", "--aux-buffer-size", "1024"}));
1150 // not power of two
1151 ASSERT_FALSE(RunRecordCmd({"-e", "cs-etm", "--aux-buffer-size", "12k"}));
1152 }
1153
1154 // @CddTest = 6.1/C-0-2
TEST(record_cmd,addr_filter_option)1155 TEST(record_cmd, addr_filter_option) {
1156 TEST_REQUIRE_HW_COUNTER();
1157 if (!ETMRecorder::GetInstance().CheckEtmSupport().ok()) {
1158 GTEST_LOG_(INFO) << "Omit this test since etm isn't supported on this device";
1159 return;
1160 }
1161 FILE* fp = popen("which sleep", "r");
1162 ASSERT_TRUE(fp != nullptr);
1163 std::string path;
1164 ASSERT_TRUE(android::base::ReadFdToString(fileno(fp), &path));
1165 pclose(fp);
1166 path = android::base::Trim(path);
1167 std::string sleep_exec_path;
1168 ASSERT_TRUE(Realpath(path, &sleep_exec_path));
1169 // --addr-filter doesn't apply to cpu-cycles.
1170 ASSERT_FALSE(RunRecordCmd({"--addr-filter", "filter " + sleep_exec_path}));
1171 TemporaryFile record_file;
1172 ASSERT_TRUE(RunRecordCmd({"-e", "cs-etm", "--addr-filter", "filter " + sleep_exec_path},
1173 record_file.path));
1174 TemporaryFile inject_file;
1175 ASSERT_TRUE(
1176 CreateCommandInstance("inject")->Run({"-i", record_file.path, "-o", inject_file.path}));
1177 std::string data;
1178 ASSERT_TRUE(android::base::ReadFileToString(inject_file.path, &data));
1179 // Only instructions in sleep_exec_path are traced.
1180 for (auto& line : android::base::Split(data, "\n")) {
1181 if (android::base::StartsWith(line, "dso ")) {
1182 std::string dso = line.substr(strlen("dso "), sleep_exec_path.size());
1183 ASSERT_EQ(dso, sleep_exec_path);
1184 }
1185 }
1186
1187 // Test if different filter types are accepted by the kernel.
1188 auto elf = ElfFile::Open(sleep_exec_path);
1189 uint64_t off;
1190 uint64_t addr = elf->ReadMinExecutableVaddr(&off);
1191 // file start
1192 std::string filter = StringPrintf("start 0x%" PRIx64 "@%s", addr, sleep_exec_path.c_str());
1193 ASSERT_TRUE(RunRecordCmd({"-e", "cs-etm", "--addr-filter", filter}));
1194 // file stop
1195 filter = StringPrintf("stop 0x%" PRIx64 "@%s", addr, sleep_exec_path.c_str());
1196 ASSERT_TRUE(RunRecordCmd({"-e", "cs-etm", "--addr-filter", filter}));
1197 // file range
1198 filter = StringPrintf("filter 0x%" PRIx64 "-0x%" PRIx64 "@%s", addr, addr + 4,
1199 sleep_exec_path.c_str());
1200 ASSERT_TRUE(RunRecordCmd({"-e", "cs-etm", "--addr-filter", filter}));
1201 // If kernel panic, try backporting "perf/core: Fix crash when using HW tracing kernel
1202 // filters".
1203 // kernel start
1204 uint64_t fake_kernel_addr = (1ULL << 63);
1205 filter = StringPrintf("start 0x%" PRIx64, fake_kernel_addr);
1206 ASSERT_TRUE(RunRecordCmd({"-e", "cs-etm", "--addr-filter", filter}));
1207 // kernel stop
1208 filter = StringPrintf("stop 0x%" PRIx64, fake_kernel_addr);
1209 ASSERT_TRUE(RunRecordCmd({"-e", "cs-etm", "--addr-filter", filter}));
1210 // kernel range
1211 filter = StringPrintf("filter 0x%" PRIx64 "-0x%" PRIx64, fake_kernel_addr, fake_kernel_addr + 4);
1212 ASSERT_TRUE(RunRecordCmd({"-e", "cs-etm", "--addr-filter", filter}));
1213 }
1214
1215 // @CddTest = 6.1/C-0-2
TEST(record_cmd,decode_etm_option)1216 TEST(record_cmd, decode_etm_option) {
1217 if (!ETMRecorder::GetInstance().CheckEtmSupport().ok()) {
1218 GTEST_LOG_(INFO) << "Omit this test since etm isn't supported on this device";
1219 return;
1220 }
1221 ASSERT_TRUE(RunRecordCmd({"-e", "cs-etm", "--decode-etm"}));
1222 ASSERT_TRUE(RunRecordCmd({"-e", "cs-etm", "--decode-etm", "--exclude-perf"}));
1223 }
1224
1225 // @CddTest = 6.1/C-0-2
TEST(record_cmd,record_timestamp)1226 TEST(record_cmd, record_timestamp) {
1227 if (!ETMRecorder::GetInstance().CheckEtmSupport().ok()) {
1228 GTEST_LOG_(INFO) << "Omit this test since etm isn't supported on this device";
1229 return;
1230 }
1231 ASSERT_TRUE(RunRecordCmd({"-e", "cs-etm", "--record-timestamp"}));
1232 }
1233
1234 // @CddTest = 6.1/C-0-2
TEST(record_cmd,record_cycles)1235 TEST(record_cmd, record_cycles) {
1236 if (!ETMRecorder::GetInstance().CheckEtmSupport().ok()) {
1237 GTEST_LOG_(INFO) << "Omit this test since etm isn't supported on this device";
1238 return;
1239 }
1240 ASSERT_TRUE(RunRecordCmd({"-e", "cs-etm", "--record-cycles"}));
1241 }
1242
1243 // @CddTest = 6.1/C-0-2
TEST(record_cmd,cycle_threshold)1244 TEST(record_cmd, cycle_threshold) {
1245 if (!ETMRecorder::GetInstance().CheckEtmSupport().ok()) {
1246 GTEST_LOG_(INFO) << "Omit this test since etm isn't supported on this device";
1247 return;
1248 }
1249 ASSERT_TRUE(RunRecordCmd({"-e", "cs-etm", "--record-cycles", "--cycle-threshold", "8"}));
1250 }
1251
1252 // @CddTest = 6.1/C-0-2
TEST(record_cmd,binary_option)1253 TEST(record_cmd, binary_option) {
1254 if (!ETMRecorder::GetInstance().CheckEtmSupport().ok()) {
1255 GTEST_LOG_(INFO) << "Omit this test since etm isn't supported on this device";
1256 return;
1257 }
1258 ASSERT_TRUE(RunRecordCmd({"-e", "cs-etm", "--decode-etm", "--binary", ".*"}));
1259 }
1260
1261 // @CddTest = 6.1/C-0-2
TEST(record_cmd,etm_flush_interval_option)1262 TEST(record_cmd, etm_flush_interval_option) {
1263 if (!ETMRecorder::GetInstance().CheckEtmSupport().ok()) {
1264 GTEST_LOG_(INFO) << "Omit this test since etm isn't supported on this device";
1265 return;
1266 }
1267 ASSERT_TRUE(RunRecordCmd({"-e", "cs-etm", "--etm-flush-interval", "10"}));
1268 }
1269
1270 // @CddTest = 6.1/C-0-2
TEST(record_cmd,pmu_event_option)1271 TEST(record_cmd, pmu_event_option) {
1272 TEST_REQUIRE_PMU_COUNTER();
1273 TEST_REQUIRE_HW_COUNTER();
1274 std::string event_string;
1275 if (GetTargetArch() == ARCH_X86_64) {
1276 event_string = "cpu/cpu-cycles/";
1277 } else if (GetTargetArch() == ARCH_ARM64) {
1278 event_string = "armv8_pmuv3/cpu_cycles/";
1279 } else {
1280 GTEST_LOG_(INFO) << "Omit arch " << GetTargetArch();
1281 return;
1282 }
1283 TEST_IN_ROOT(ASSERT_TRUE(RunRecordCmd({"-e", event_string})));
1284 }
1285
1286 // @CddTest = 6.1/C-0-2
TEST(record_cmd,exclude_perf_option)1287 TEST(record_cmd, exclude_perf_option) {
1288 ASSERT_TRUE(RunRecordCmd({"--exclude-perf"}));
1289 if (IsRoot()) {
1290 TemporaryFile tmpfile;
1291 ASSERT_TRUE(RecordCmd()->Run(
1292 {"-a", "--exclude-perf", "--duration", "1", "-e", GetDefaultEvent(), "-o", tmpfile.path}));
1293 std::unique_ptr<RecordFileReader> reader = RecordFileReader::CreateInstance(tmpfile.path);
1294 ASSERT_TRUE(reader);
1295 pid_t perf_pid = getpid();
1296 ASSERT_TRUE(reader->ReadDataSection([&](std::unique_ptr<Record> r) {
1297 if (r->type() == PERF_RECORD_SAMPLE) {
1298 if (static_cast<SampleRecord*>(r.get())->tid_data.pid == perf_pid) {
1299 return false;
1300 }
1301 }
1302 return true;
1303 }));
1304 }
1305 }
1306
1307 // @CddTest = 6.1/C-0-2
TEST(record_cmd,tp_filter_option)1308 TEST(record_cmd, tp_filter_option) {
1309 TEST_REQUIRE_KERNEL_EVENTS();
1310 TEST_REQUIRE_TRACEPOINT_EVENTS();
1311 // Test string operands both with quotes and without quotes.
1312 for (const auto& filter :
1313 std::vector<std::string>({"prev_comm != 'sleep'", "prev_comm != sleep"})) {
1314 TemporaryFile tmpfile;
1315 ASSERT_TRUE(RunRecordCmd({"-e", "sched:sched_switch", "--tp-filter", filter}, tmpfile.path))
1316 << filter;
1317 CaptureStdout capture;
1318 ASSERT_TRUE(capture.Start());
1319 ASSERT_TRUE(CreateCommandInstance("dump")->Run({tmpfile.path}));
1320 std::string data = capture.Finish();
1321 // Check that samples with prev_comm == sleep are filtered out. Although we do the check all the
1322 // time, it only makes sense when running as root. Tracepoint event fields are not allowed
1323 // to record unless running as root.
1324 ASSERT_EQ(data.find("prev_comm: sleep"), std::string::npos) << filter;
1325 }
1326 }
1327
1328 // @CddTest = 6.1/C-0-2
TEST(record_cmd,ParseAddrFilterOption)1329 TEST(record_cmd, ParseAddrFilterOption) {
1330 auto option_to_str = [](const std::string& option) {
1331 auto filters = ParseAddrFilterOption(option);
1332 std::string s;
1333 for (auto& filter : filters) {
1334 if (!s.empty()) {
1335 s += ',';
1336 }
1337 s += filter.ToString();
1338 }
1339 return s;
1340 };
1341 std::string path;
1342 ASSERT_TRUE(Realpath(GetTestData(ELF_FILE), &path));
1343
1344 // Test file filters.
1345 ASSERT_EQ(option_to_str("filter " + path), "filter 0x0/0x73c@" + path);
1346 ASSERT_EQ(option_to_str("filter 0x400502-0x400527@" + path), "filter 0x502/0x25@" + path);
1347 ASSERT_EQ(option_to_str("start 0x400502@" + path + ",stop 0x400527@" + path),
1348 "start 0x502@" + path + ",stop 0x527@" + path);
1349
1350 // Test '-' in file path. Create a temporary file with '-' in name.
1351 TemporaryDir tmpdir;
1352 fs::path tmpfile = fs::path(tmpdir.path) / "elf-with-hyphen";
1353 ASSERT_TRUE(fs::copy_file(path, tmpfile));
1354 ASSERT_EQ(option_to_str("filter " + tmpfile.string()), "filter 0x0/0x73c@" + tmpfile.string());
1355
1356 // Test kernel filters.
1357 ASSERT_EQ(option_to_str("filter 0x12345678-0x1234567a"), "filter 0x12345678/0x2");
1358 ASSERT_EQ(option_to_str("start 0x12345678,stop 0x1234567a"), "start 0x12345678,stop 0x1234567a");
1359 }
1360
1361 // @CddTest = 6.1/C-0-2
TEST(record_cmd,kprobe_option)1362 TEST(record_cmd, kprobe_option) {
1363 TEST_REQUIRE_ROOT();
1364 EventSelectionSet event_selection_set(false);
1365 ProbeEvents probe_events(event_selection_set);
1366 if (!probe_events.IsProbeSupported(ProbeEventType::kKprobe)) {
1367 GTEST_LOG_(INFO) << "Skip this test as kprobe isn't supported by the kernel.";
1368 return;
1369 }
1370 ASSERT_TRUE(RunRecordCmd({"-e", "kprobes:myprobe", "--kprobe", "p:myprobe do_sys_openat2"}));
1371 // A default kprobe event is created if not given an explicit --kprobe option.
1372 ASSERT_TRUE(RunRecordCmd({"-e", "kprobes:do_sys_openat2"}));
1373 ASSERT_TRUE(RunRecordCmd({"--group", "kprobes:do_sys_openat2"}));
1374 }
1375
1376 // @CddTest = 6.1/C-0-2
TEST(record_cmd,uprobe_option)1377 TEST(record_cmd, uprobe_option) {
1378 TEST_REQUIRE_ROOT();
1379 EventSelectionSet event_selection_set(false);
1380 ProbeEvents probe_events(event_selection_set);
1381 if (!probe_events.IsProbeSupported(ProbeEventType::kUprobe)) {
1382 GTEST_LOG_(INFO) << "Skip this test as uprobe isn't supported by the kernel.";
1383 return;
1384 }
1385 if (!IsRegularFile("/system/lib64/libc.so")) {
1386 GTEST_LOG_(INFO) << "Skip this test as /system/lib64/libc.so doesn't exist";
1387 return;
1388 }
1389 ASSERT_TRUE(RunRecordCmd(
1390 {"-e", "uprobes:myprobe", "--uprobe", "p:myprobe /system/lib64/libc.so:0x88e80"}));
1391 ASSERT_TRUE(RunRecordCmd(
1392 {"-e", "uprobes:p_libc_0x88e80", "--uprobe", "p /system/lib64/libc.so:0x88e80"}));
1393 ASSERT_TRUE(RunRecordCmd(
1394 {"-e", "uprobes:myprobe", "--uprobe", "r:myprobe /system/lib64/libc.so:0x88e80"}));
1395 ASSERT_TRUE(RunRecordCmd(
1396 {"-e", "uprobes:p_libc_0x88e80", "--uprobe", "r /system/lib64/libc.so:0x88e80"}));
1397 }
1398
1399 // @CddTest = 6.1/C-0-2
TEST(record_cmd,record_filter_options)1400 TEST(record_cmd, record_filter_options) {
1401 ASSERT_TRUE(
1402 RunRecordCmd({"--exclude-pid", "1,2", "--exclude-tid", "3,4", "--exclude-process-name",
1403 "processA", "--exclude-thread-name", "threadA", "--exclude-uid", "5,6"}));
1404 ASSERT_TRUE(
1405 RunRecordCmd({"--include-pid", "1,2", "--include-tid", "3,4", "--include-process-name",
1406 "processB", "--include-thread-name", "threadB", "--include-uid", "5,6"}));
1407 }
1408
1409 // @CddTest = 6.1/C-0-2
TEST(record_cmd,keep_failed_unwinding_result_option)1410 TEST(record_cmd, keep_failed_unwinding_result_option) {
1411 OMIT_TEST_ON_NON_NATIVE_ABIS();
1412 std::vector<std::unique_ptr<Workload>> workloads;
1413 CreateProcesses(1, &workloads);
1414 std::string pid = std::to_string(workloads[0]->GetPid());
1415 ASSERT_TRUE(RunRecordCmd(
1416 {"-p", pid, "-g", "--keep-failed-unwinding-result", "--keep-failed-unwinding-debug-info"}));
1417 }
1418
1419 // @CddTest = 6.1/C-0-2
TEST(record_cmd,kernel_address_warning)1420 TEST(record_cmd, kernel_address_warning) {
1421 TEST_REQUIRE_KERNEL_EVENTS();
1422 TEST_REQUIRE_NON_ROOT();
1423 const std::string warning_msg = "Access to kernel symbol addresses is restricted.";
1424 CapturedStderr capture;
1425
1426 // When excluding kernel samples, no kernel address warning is printed.
1427 ResetKernelAddressWarning();
1428 TemporaryFile tmpfile;
1429 ASSERT_TRUE(RunRecordCmd({"-e", "cpu-clock:u"}, tmpfile.path));
1430 capture.Stop();
1431 ASSERT_EQ(capture.str().find(warning_msg), std::string::npos);
1432
1433 // When not excluding kernel samples, kernel address warning is printed once.
1434 capture.Reset();
1435 capture.Start();
1436 ResetKernelAddressWarning();
1437 ASSERT_TRUE(RunRecordCmd({"-e", "cpu-clock"}, tmpfile.path));
1438 capture.Stop();
1439 std::string output = capture.str();
1440 auto pos = output.find(warning_msg);
1441 ASSERT_NE(pos, std::string::npos);
1442 ASSERT_EQ(output.find(warning_msg, pos + warning_msg.size()), std::string::npos);
1443 }
1444
1445 // @CddTest = 6.1/C-0-2
TEST(record_cmd,add_meta_info_option)1446 TEST(record_cmd, add_meta_info_option) {
1447 TemporaryFile tmpfile;
1448 ASSERT_TRUE(RunRecordCmd({"--add-meta-info", "key1=value1", "--add-meta-info", "key2=value2"},
1449 tmpfile.path));
1450 auto reader = RecordFileReader::CreateInstance(tmpfile.path);
1451 ASSERT_TRUE(reader);
1452
1453 const std::unordered_map<std::string, std::string>& meta_info = reader->GetMetaInfoFeature();
1454 auto it = meta_info.find("key1");
1455 ASSERT_NE(it, meta_info.end());
1456 ASSERT_EQ(it->second, "value1");
1457 it = meta_info.find("key2");
1458 ASSERT_NE(it, meta_info.end());
1459 ASSERT_EQ(it->second, "value2");
1460
1461 // Report error for invalid meta info.
1462 ASSERT_FALSE(RunRecordCmd({"--add-meta-info", "key1"}, tmpfile.path));
1463 ASSERT_FALSE(RunRecordCmd({"--add-meta-info", "key1="}, tmpfile.path));
1464 ASSERT_FALSE(RunRecordCmd({"--add-meta-info", "=value1"}, tmpfile.path));
1465 }
1466
1467 // @CddTest = 6.1/C-0-2
TEST(record_cmd,device_meta_info)1468 TEST(record_cmd, device_meta_info) {
1469 #if defined(__ANDROID__)
1470 TemporaryFile tmpfile;
1471 ASSERT_TRUE(RunRecordCmd({}, tmpfile.path));
1472 auto reader = RecordFileReader::CreateInstance(tmpfile.path);
1473 ASSERT_TRUE(reader);
1474
1475 const std::unordered_map<std::string, std::string>& meta_info = reader->GetMetaInfoFeature();
1476 auto it = meta_info.find("android_sdk_version");
1477 ASSERT_NE(it, meta_info.end());
1478 ASSERT_FALSE(it->second.empty());
1479 it = meta_info.find("android_build_type");
1480 ASSERT_NE(it, meta_info.end());
1481 ASSERT_FALSE(it->second.empty());
1482 #else
1483 GTEST_LOG_(INFO) << "This test tests a function only available on Android.";
1484 #endif
1485 }
1486
1487 // @CddTest = 6.1/C-0-2
TEST(record_cmd,add_counter_option)1488 TEST(record_cmd, add_counter_option) {
1489 TEST_REQUIRE_HW_COUNTER();
1490 TemporaryFile tmpfile;
1491 ASSERT_TRUE(RecordCmd()->Run({"-e", "cpu-cycles:u", "--add-counter", "instructions:u",
1492 "--no-inherit", "-o", tmpfile.path, "sleep", "1"}));
1493 std::unique_ptr<RecordFileReader> reader = RecordFileReader::CreateInstance(tmpfile.path);
1494 ASSERT_TRUE(reader);
1495 bool has_sample = false;
1496 ASSERT_TRUE(reader->ReadDataSection([&](std::unique_ptr<Record> r) {
1497 if (r->type() == PERF_RECORD_SAMPLE) {
1498 has_sample = true;
1499 auto sr = static_cast<SampleRecord*>(r.get());
1500 if (sr->read_data.counts.size() != 2 || sr->read_data.ids.size() != 2) {
1501 return false;
1502 }
1503 }
1504 return true;
1505 }));
1506 ASSERT_TRUE(has_sample);
1507 }
1508
1509 // @CddTest = 6.1/C-0-2
TEST(record_cmd,user_buffer_size_option)1510 TEST(record_cmd, user_buffer_size_option) {
1511 ASSERT_TRUE(RunRecordCmd({"--user-buffer-size", "256M"}));
1512 }
1513
1514 // @CddTest = 6.1/C-0-2
TEST(record_cmd,record_process_name)1515 TEST(record_cmd, record_process_name) {
1516 TemporaryFile tmpfile;
1517 ASSERT_TRUE(RecordCmd()->Run({"-e", GetDefaultEvent(), "-o", tmpfile.path, "sleep", SLEEP_SEC}));
1518 std::unique_ptr<RecordFileReader> reader = RecordFileReader::CreateInstance(tmpfile.path);
1519 ASSERT_TRUE(reader);
1520 bool has_comm = false;
1521 ASSERT_TRUE(reader->ReadDataSection([&](std::unique_ptr<Record> r) {
1522 if (r->type() == PERF_RECORD_COMM) {
1523 CommRecord* cr = static_cast<CommRecord*>(r.get());
1524 if (strcmp(cr->comm, "sleep") == 0) {
1525 has_comm = true;
1526 }
1527 }
1528 return true;
1529 }));
1530 ASSERT_TRUE(has_comm);
1531 }
1532
1533 // @CddTest = 6.1/C-0-2
TEST(record_cmd,delay_option)1534 TEST(record_cmd, delay_option) {
1535 TemporaryFile tmpfile;
1536 ASSERT_TRUE(RecordCmd()->Run(
1537 {"-o", tmpfile.path, "-e", GetDefaultEvent(), "--delay", "100", "sleep", "1"}));
1538 }
1539
1540 // @CddTest = 6.1/C-0-2
TEST(record_cmd,compression_option)1541 TEST(record_cmd, compression_option) {
1542 TemporaryFile tmpfile;
1543 ASSERT_TRUE(RunRecordCmd({"-z"}, tmpfile.path));
1544 std::unique_ptr<RecordFileReader> reader = RecordFileReader::CreateInstance(tmpfile.path);
1545 ASSERT_TRUE(reader != nullptr);
1546 std::vector<std::unique_ptr<Record>> records = reader->DataSection();
1547 ASSERT_GT(records.size(), 0U);
1548
1549 ASSERT_TRUE(RunRecordCmd({"-z=3"}, tmpfile.path));
1550 }
1551
1552 // @CddTest = 6.1/C-0-2
TEST(record_cmd,child_process)1553 TEST(record_cmd, child_process) {
1554 // Test that we can run simpleperf to record samples for a child process in shell.
1555 TemporaryFile tmpfile;
1556 ASSERT_TRUE(Workload::RunCmd({"/system/bin/simpleperf", "record", "-e", GetDefaultEvent(), "-o",
1557 tmpfile.path, "sleep", SLEEP_SEC},
1558 true));
1559 }
1560