• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <android-base/file.h>
20 #include <android-base/stringprintf.h>
21 #include <android-base/strings.h>
22 
23 #include <thread>
24 
25 #include "ProbeEvents.h"
26 #include "cmd_stat_impl.h"
27 #include "command.h"
28 #include "environment.h"
29 #include "event_selection_set.h"
30 #include "get_test_data.h"
31 #include "test_util.h"
32 
33 using namespace simpleperf;
34 
StatCmd()35 static std::unique_ptr<Command> StatCmd() {
36   return CreateCommandInstance("stat");
37 }
38 
39 // @CddTest = 6.1/C-0-2
TEST(stat_cmd,no_options)40 TEST(stat_cmd, no_options) {
41   ASSERT_TRUE(StatCmd()->Run({"sleep", "1"}));
42 }
43 
44 // @CddTest = 6.1/C-0-2
TEST(stat_cmd,event_option)45 TEST(stat_cmd, event_option) {
46   TEST_REQUIRE_HW_COUNTER();
47   ASSERT_TRUE(StatCmd()->Run({"-e", "cpu-cycles:u,instructions:u", "sleep", "1"}));
48 }
49 
50 // @CddTest = 6.1/C-0-2
TEST(stat_cmd,system_wide_option)51 TEST(stat_cmd, system_wide_option) {
52   TEST_IN_ROOT(ASSERT_TRUE(StatCmd()->Run({"-a", "sleep", "1"})));
53 }
54 
55 // @CddTest = 6.1/C-0-2
TEST(stat_cmd,verbose_option)56 TEST(stat_cmd, verbose_option) {
57   TEST_REQUIRE_HW_COUNTER();
58   ASSERT_TRUE(StatCmd()->Run({"--verbose", "-e", "cpu-cycles:u", "sleep", "1"}));
59 }
60 
61 // @CddTest = 6.1/C-0-2
TEST(stat_cmd,tracepoint_event)62 TEST(stat_cmd, tracepoint_event) {
63   TEST_IN_ROOT(ASSERT_TRUE(StatCmd()->Run({"-a", "-e", "sched:sched_switch", "sleep", "1"})));
64 }
65 
66 // @CddTest = 6.1/C-0-2
TEST(stat_cmd,rN_event)67 TEST(stat_cmd, rN_event) {
68   TEST_REQUIRE_HW_COUNTER();
69   OMIT_TEST_ON_NON_NATIVE_ABIS();
70   size_t event_number;
71   if (GetTargetArch() == ARCH_ARM64 || GetTargetArch() == ARCH_ARM) {
72     // As in D5.10.2 of the ARMv8 manual, ARM defines the event number space for PMU. part of the
73     // space is for common event numbers (which will stay the same for all ARM chips), part of the
74     // space is for implementation defined events. Here 0x08 is a common event for instructions.
75     event_number = 0x08;
76   } else if (GetTargetArch() == ARCH_X86_32 || GetTargetArch() == ARCH_X86_64) {
77     // As in volume 3 chapter 19 of the Intel manual, 0x00c0 is the event number for instruction.
78     event_number = 0x00c0;
79   } else if (GetTargetArch() == ARCH_RISCV64) {
80     //  RISCV_PMU_INSTRET = 1
81     event_number = 0x1;
82   } else {
83     GTEST_LOG_(INFO) << "Omit arch " << GetTargetArch();
84     return;
85   }
86   std::string event_name = android::base::StringPrintf("r%zx:u", event_number);
87   ASSERT_TRUE(StatCmd()->Run({"-e", event_name, "sleep", "1"}));
88 }
89 
90 // @CddTest = 6.1/C-0-2
TEST(stat_cmd,pmu_event)91 TEST(stat_cmd, pmu_event) {
92   TEST_REQUIRE_PMU_COUNTER();
93   TEST_REQUIRE_HW_COUNTER();
94   std::string event_string;
95   if (GetTargetArch() == ARCH_X86_64) {
96     event_string = "cpu/instructions/";
97   } else if (GetTargetArch() == ARCH_ARM64) {
98     event_string = "armv8_pmuv3/inst_retired/";
99   } else if (GetTargetArch() == ARCH_RISCV64) {
100     event_string = "cpu/instructions/";
101   } else {
102     GTEST_LOG_(INFO) << "Omit arch " << GetTargetArch();
103     return;
104   }
105   TEST_IN_ROOT(ASSERT_TRUE(StatCmd()->Run({"-a", "-e", event_string, "sleep", "1"})));
106 }
107 
108 // @CddTest = 6.1/C-0-2
TEST(stat_cmd,event_modifier)109 TEST(stat_cmd, event_modifier) {
110   TEST_REQUIRE_HW_COUNTER();
111   TEST_REQUIRE_ROOT();
112   ASSERT_TRUE(StatCmd()->Run({"-e", "cpu-cycles:u,cpu-cycles:k", "sleep", "1"}));
113 }
114 
RunWorkloadFunction()115 void RunWorkloadFunction() {
116   while (true) {
117     for (volatile int i = 0; i < 10000; ++i);
118     usleep(1);
119   }
120 }
121 
CreateProcesses(size_t count,std::vector<std::unique_ptr<Workload>> * workloads)122 void CreateProcesses(size_t count, std::vector<std::unique_ptr<Workload>>* workloads) {
123   workloads->clear();
124   // Create workloads run longer than profiling time.
125   for (size_t i = 0; i < count; ++i) {
126     std::unique_ptr<Workload> workload;
127     workload = Workload::CreateWorkload(RunWorkloadFunction);
128     ASSERT_TRUE(workload != nullptr);
129     ASSERT_TRUE(workload->Start());
130     workloads->push_back(std::move(workload));
131   }
132 }
133 
134 // @CddTest = 6.1/C-0-2
TEST(stat_cmd,existing_processes)135 TEST(stat_cmd, existing_processes) {
136   std::vector<std::unique_ptr<Workload>> workloads;
137   CreateProcesses(2, &workloads);
138   std::string pid_list =
139       android::base::StringPrintf("%d,%d", workloads[0]->GetPid(), workloads[1]->GetPid());
140   ASSERT_TRUE(StatCmd()->Run({"-p", pid_list, "sleep", "1"}));
141 }
142 
143 // @CddTest = 6.1/C-0-2
TEST(stat_cmd,existing_threads)144 TEST(stat_cmd, existing_threads) {
145   std::vector<std::unique_ptr<Workload>> workloads;
146   CreateProcesses(2, &workloads);
147   // Process id can be used as thread id in linux.
148   std::string tid_list =
149       android::base::StringPrintf("%d,%d", workloads[0]->GetPid(), workloads[1]->GetPid());
150   ASSERT_TRUE(StatCmd()->Run({"-t", tid_list, "sleep", "1"}));
151 }
152 
153 // @CddTest = 6.1/C-0-2
TEST(stat_cmd,no_monitored_threads)154 TEST(stat_cmd, no_monitored_threads) {
155   ASSERT_FALSE(StatCmd()->Run({}));
156   ASSERT_FALSE(StatCmd()->Run({""}));
157 }
158 
159 // @CddTest = 6.1/C-0-2
TEST(stat_cmd,group_option)160 TEST(stat_cmd, group_option) {
161   TEST_REQUIRE_KERNEL_EVENTS();
162   TEST_REQUIRE_HW_COUNTER();
163   ASSERT_TRUE(StatCmd()->Run({"--group", "cpu-clock,page-faults", "sleep", "1"}));
164   ASSERT_TRUE(StatCmd()->Run({"--group", "cpu-cycles,instructions", "--group",
165                               "cpu-cycles:u,instructions:u", "--group",
166                               "cpu-cycles:k,instructions:k", "sleep", "1"}));
167 }
168 
169 // @CddTest = 6.1/C-0-2
TEST(stat_cmd,auto_generated_summary)170 TEST(stat_cmd, auto_generated_summary) {
171   TEST_REQUIRE_KERNEL_EVENTS();
172   TEST_REQUIRE_HW_COUNTER();
173   TemporaryFile tmp_file;
174   ASSERT_TRUE(StatCmd()->Run(
175       {"--group", "instructions:u,instructions:k", "-o", tmp_file.path, "sleep", "1"}));
176   std::string s;
177   ASSERT_TRUE(android::base::ReadFileToString(tmp_file.path, &s));
178   size_t pos = s.find("instructions:u");
179   ASSERT_NE(s.npos, pos);
180   pos = s.find("instructions:k", pos);
181   ASSERT_NE(s.npos, pos);
182   pos += strlen("instructions:k");
183   // Check if the summary of instructions is generated.
184   ASSERT_NE(s.npos, s.find("instructions", pos));
185 }
186 
187 // @CddTest = 6.1/C-0-2
TEST(stat_cmd,duration_option)188 TEST(stat_cmd, duration_option) {
189   ASSERT_TRUE(StatCmd()->Run({"--duration", "1.2", "-p", std::to_string(getpid()), "--in-app"}));
190   ASSERT_TRUE(StatCmd()->Run({"--duration", "1", "sleep", "2"}));
191 }
192 
193 // @CddTest = 6.1/C-0-2
TEST(stat_cmd,interval_option)194 TEST(stat_cmd, interval_option) {
195   TemporaryFile tmp_file;
196   ASSERT_TRUE(StatCmd()->Run(
197       {"--interval", "500.0", "--duration", "1.2", "-o", tmp_file.path, "sleep", "2"}));
198   std::string s;
199   ASSERT_TRUE(android::base::ReadFileToString(tmp_file.path, &s));
200   size_t count = 0;
201   size_t pos = 0;
202   std::string subs = "statistics:";
203   while ((pos = s.find(subs, pos)) != s.npos) {
204     pos += subs.size();
205     ++count;
206   }
207   ASSERT_EQ(count, 2UL);
208 }
209 
210 // @CddTest = 6.1/C-0-2
TEST(stat_cmd,interval_option_in_system_wide)211 TEST(stat_cmd, interval_option_in_system_wide) {
212   TEST_IN_ROOT(ASSERT_TRUE(StatCmd()->Run({"-a", "--interval", "100", "--duration", "0.3"})));
213 }
214 
215 // @CddTest = 6.1/C-0-2
TEST(stat_cmd,interval_only_values_option)216 TEST(stat_cmd, interval_only_values_option) {
217   ASSERT_TRUE(StatCmd()->Run({"--interval", "500", "--interval-only-values", "sleep", "2"}));
218   TEST_IN_ROOT(ASSERT_TRUE(
219       StatCmd()->Run({"-a", "--interval", "100", "--interval-only-values", "--duration", "0.3"})));
220 }
221 
222 // @CddTest = 6.1/C-0-2
TEST(stat_cmd,no_modifier_for_clock_events)223 TEST(stat_cmd, no_modifier_for_clock_events) {
224   TEST_REQUIRE_KERNEL_EVENTS();
225   for (const std::string& e : {"cpu-clock", "task-clock"}) {
226     for (const std::string& m : {"u", "k"}) {
227       ASSERT_FALSE(StatCmd()->Run({"-e", e + ":" + m, "sleep", "0.1"}))
228           << "event " << e << ":" << m;
229     }
230   }
231 }
232 
233 // @CddTest = 6.1/C-0-2
TEST(stat_cmd,handle_SIGHUP)234 TEST(stat_cmd, handle_SIGHUP) {
235   std::thread thread([]() {
236     sleep(1);
237     kill(getpid(), SIGHUP);
238   });
239   thread.detach();
240   ASSERT_TRUE(StatCmd()->Run({"sleep", "1000000"}));
241 }
242 
243 // @CddTest = 6.1/C-0-2
TEST(stat_cmd,stop_when_no_more_targets)244 TEST(stat_cmd, stop_when_no_more_targets) {
245   std::atomic<int> tid(0);
246   std::thread thread([&]() {
247     tid = gettid();
248     sleep(1);
249   });
250   thread.detach();
251   while (tid == 0);
252   ASSERT_TRUE(StatCmd()->Run({"-t", std::to_string(tid), "--in-app"}));
253 }
254 
255 // @CddTest = 6.1/C-0-2
TEST(stat_cmd,sample_rate_should_be_zero)256 TEST(stat_cmd, sample_rate_should_be_zero) {
257   TEST_REQUIRE_HW_COUNTER();
258   EventSelectionSet set(true);
259   ASSERT_TRUE(set.AddEventType("cpu-cycles:u"));
260   set.AddMonitoredProcesses({getpid()});
261   set.SetCpusForNewEvents({-1});
262   ASSERT_TRUE(set.OpenEventFiles());
263   const EventAttrIds& attrs = set.GetEventAttrWithId();
264   ASSERT_GT(attrs.size(), 0u);
265   for (auto& attr : attrs) {
266     ASSERT_EQ(attr.attr.sample_period, 0u);
267     ASSERT_EQ(attr.attr.sample_freq, 0u);
268     ASSERT_EQ(attr.attr.freq, 0u);
269   }
270 }
271 
272 // @CddTest = 6.1/C-0-2
TEST(stat_cmd,calculating_cpu_frequency)273 TEST(stat_cmd, calculating_cpu_frequency) {
274   TEST_REQUIRE_KERNEL_EVENTS();
275   TEST_REQUIRE_HW_COUNTER();
276   CaptureStdout capture;
277   ASSERT_TRUE(capture.Start());
278   ASSERT_TRUE(StatCmd()->Run({"--csv", "--group", "task-clock,cpu-cycles", "sleep", "1"}));
279   std::string output = capture.Finish();
280   double task_clock_in_ms = 0;
281   uint64_t cpu_cycle_count = 0;
282   double cpu_frequency = 0;
283   for (auto& line : android::base::Split(output, "\n")) {
284     if (line.find("task-clock") != std::string::npos) {
285       ASSERT_EQ(sscanf(line.c_str(), "%lf(ms)", &task_clock_in_ms), 1);
286     } else if (line.find("cpu-cycles") != std::string::npos) {
287       ASSERT_EQ(
288           sscanf(line.c_str(), "%" SCNu64 ",cpu-cycles,%lf", &cpu_cycle_count, &cpu_frequency), 2);
289     }
290   }
291   ASSERT_NE(task_clock_in_ms, 0.0f);
292   ASSERT_NE(cpu_cycle_count, 0u);
293   ASSERT_NE(cpu_frequency, 0.0f);
294   double calculated_frequency = cpu_cycle_count / task_clock_in_ms / 1e6;
295   // Accept error up to 1e-3. Because the stat cmd print values with precision 1e-6.
296   ASSERT_NEAR(cpu_frequency, calculated_frequency, 1e-3);
297 }
298 
299 // @CddTest = 6.1/C-0-2
TEST(stat_cmd,set_comm_in_another_thread)300 TEST(stat_cmd, set_comm_in_another_thread) {
301   TEST_REQUIRE_KERNEL_EVENTS();
302   // Test a kernel bug which was fixed in 3.15. If kernel panic happens, please cherry pick kernel
303   // patch: e041e328c4b41e perf: Fix perf_event_comm() vs. exec() assumption
304   TEST_REQUIRE_HW_COUNTER();
305 
306   for (size_t loop = 0; loop < 3; ++loop) {
307     std::atomic<int> child_tid(0);
308     std::atomic<bool> stop_child(false);
309     std::thread child([&]() {
310       child_tid = gettid();
311       // stay on a cpu to make the monitored events of the child thread on that cpu.
312       while (!stop_child) {
313       }
314     });
315 
316     while (child_tid == 0) {
317     }
318 
319     {
320       EventSelectionSet set(true);
321       ASSERT_TRUE(set.AddEventType("cpu-cycles"));
322       set.AddMonitoredThreads({child_tid});
323       set.SetCpusForNewEvents({-1});
324       ASSERT_TRUE(set.OpenEventFiles());
325 
326       EventSelectionSet set2(true);
327       ASSERT_TRUE(set2.AddEventType("instructions"));
328       set2.AddMonitoredThreads({gettid()});
329       set2.SetCpusForNewEvents({-1});
330       ASSERT_TRUE(set2.OpenEventFiles());
331 
332       // For kernels with the bug, setting comm will make the monitored events of the child thread
333       // on the cpu of the current thread.
334       ASSERT_TRUE(android::base::WriteStringToFile("child",
335                                                    "/proc/" + std::to_string(child_tid) + "/comm"));
336       // Release monitored events. For kernels with the bug, the events still exist on the cpu of
337       // the child thread.
338     }
339 
340     stop_child = true;
341     child.join();
342     // Sleep 1s to enter and exit cpu idle, which may abort the kernel.
343     sleep(1);
344   }
345 }
346 
TestStatingApps(const std::string & app_name)347 static void TestStatingApps(const std::string& app_name) {
348   // Bring the app to foreground.
349   ASSERT_TRUE(Workload::RunCmd({"am", "start", app_name + "/.MainActivity"}));
350   ASSERT_TRUE(StatCmd()->Run({"--app", app_name, "--duration", "3"}));
351 }
352 
353 // @CddTest = 6.1/C-0-2
TEST(stat_cmd,app_option_for_debuggable_app)354 TEST(stat_cmd, app_option_for_debuggable_app) {
355   TEST_REQUIRE_APPS();
356   TestStatingApps("com.android.simpleperf.debuggable");
357 }
358 
359 // @CddTest = 6.1/C-0-2
TEST(stat_cmd,app_option_for_profileable_app)360 TEST(stat_cmd, app_option_for_profileable_app) {
361   TEST_REQUIRE_APPS();
362   TestStatingApps("com.android.simpleperf.profileable");
363 }
364 
365 // @CddTest = 6.1/C-0-2
TEST(stat_cmd,use_devfreq_counters_option)366 TEST(stat_cmd, use_devfreq_counters_option) {
367 #if defined(__ANDROID__)
368   TEST_IN_ROOT(StatCmd()->Run({"--use-devfreq-counters", "sleep", "0.1"}));
369 #else
370   GTEST_LOG_(INFO) << "This test tests an option only available on Android.";
371 #endif
372 }
373 
374 // @CddTest = 6.1/C-0-2
TEST(stat_cmd,per_thread_option)375 TEST(stat_cmd, per_thread_option) {
376   ASSERT_TRUE(StatCmd()->Run({"--per-thread", "sleep", "0.1"}));
377   TEST_IN_ROOT(StatCmd()->Run({"--per-thread", "-a", "--duration", "0.1"}));
378 }
379 
380 // @CddTest = 6.1/C-0-2
TEST(stat_cmd,monitor_new_thread_option)381 TEST(stat_cmd, monitor_new_thread_option) {
382   ASSERT_TRUE(
383       StatCmd()->Run({"--per-thread", "--monitor-new-thread", "--no-inherit", "sleep", "0.1"}));
384   TEST_IN_ROOT(StatCmd()->Run(
385       {"--per-thread", "--monitor-new-thread", "--no-inherit", "-a", "--duration", "0.1"}));
386 }
387 
388 // @CddTest = 6.1/C-0-2
TEST(stat_cmd,per_core_option)389 TEST(stat_cmd, per_core_option) {
390   ASSERT_TRUE(StatCmd()->Run({"--per-core", "sleep", "0.1"}));
391   TEST_IN_ROOT(StatCmd()->Run({"--per-core", "-a", "--duration", "0.1"}));
392 }
393 
394 // @CddTest = 6.1/C-0-2
TEST(stat_cmd,sort_option)395 TEST(stat_cmd, sort_option) {
396   ASSERT_TRUE(
397       StatCmd()->Run({"--per-thread", "--per-core", "--sort", "cpu,count", "sleep", "0.1"}));
398 }
399 
400 // @CddTest = 6.1/C-0-2
TEST(stat_cmd,counter_sum)401 TEST(stat_cmd, counter_sum) {
402   PerfCounter counter;
403   counter.value = 1;
404   counter.time_enabled = 2;
405   counter.time_running = 3;
406   CounterSum a;
407   a.FromCounter(counter);
408   ASSERT_EQ(a.value, 1);
409   ASSERT_EQ(a.time_enabled, 2);
410   ASSERT_EQ(a.time_running, 3);
411   CounterSum b = a + a;
412   ASSERT_EQ(b.value, 2);
413   ASSERT_EQ(b.time_enabled, 4);
414   ASSERT_EQ(b.time_running, 6);
415   CounterSum c = a - a;
416   ASSERT_EQ(c.value, 0);
417   ASSERT_EQ(c.time_enabled, 0);
418   ASSERT_EQ(c.time_running, 0);
419   b.ToCounter(counter);
420   ASSERT_EQ(counter.value, 2);
421   ASSERT_EQ(counter.time_enabled, 4);
422   ASSERT_EQ(counter.time_running, 6);
423 }
424 
425 // @CddTest = 6.1/C-0-2
TEST(stat_cmd,print_hw_counter_option)426 TEST(stat_cmd, print_hw_counter_option) {
427   ASSERT_TRUE(StatCmd()->Run({"--print-hw-counter"}));
428 }
429 
430 // @CddTest = 6.1/C-0-2
TEST(stat_cmd,record_different_counters_for_different_cpus)431 TEST(stat_cmd, record_different_counters_for_different_cpus) {
432   TEST_REQUIRE_HW_COUNTER();
433   std::vector<int> online_cpus = GetOnlineCpus();
434   ASSERT_FALSE(online_cpus.empty());
435   std::string cpu0 = std::to_string(online_cpus[0]);
436   std::string cpu1 = std::to_string(online_cpus.back());
437 
438   CaptureStdout capture;
439   ASSERT_TRUE(capture.Start());
440   ASSERT_TRUE(StatCmd()->Run({"--csv", "--cpu", cpu0, "-e", "cpu-cycles:u", "--cpu", cpu1, "-e",
441                               "instructions:u", "--verbose", "sleep", SLEEP_SEC}));
442   std::string output = capture.Finish();
443   int mask = 0;
444   for (auto& line : android::base::Split(output, "\n")) {
445     if (android::base::StartsWith(line, "cpu-cycles,")) {
446       ASSERT_NE(line.find("cpu," + cpu0 + ","), line.npos) << output;
447       mask |= 1;
448     } else if (android::base::StartsWith(line, "instructions,")) {
449       ASSERT_NE(line.find("cpu," + cpu1 + ","), line.npos) << output;
450       mask |= 2;
451     }
452   }
453   ASSERT_EQ(mask, 3) << output;
454 }
455 
456 // @CddTest = 6.1/C-0-2
TEST(stat_cmd,kprobe_option)457 TEST(stat_cmd, kprobe_option) {
458   TEST_REQUIRE_ROOT();
459   EventSelectionSet event_selection_set(false);
460   ProbeEvents probe_events(event_selection_set);
461   if (!probe_events.IsProbeSupported(ProbeEventType::kKprobe)) {
462     GTEST_LOG_(INFO) << "Skip this test as kprobe isn't supported by the kernel.";
463     return;
464   }
465   ASSERT_TRUE(StatCmd()->Run({"-e", "kprobes:myprobe", "--kprobe", "p:myprobe do_sys_openat2", "-a",
466                               "--duration", SLEEP_SEC}));
467   // A default kprobe event is created if not given an explicit --kprobe option.
468   ASSERT_TRUE(StatCmd()->Run({"-e", "kprobes:do_sys_openat2", "-a", "--duration", SLEEP_SEC}));
469   ASSERT_TRUE(StatCmd()->Run({"--group", "kprobes:do_sys_openat2", "-a", "--duration", SLEEP_SEC}));
470 }
471 
472 // @CddTest = 6.1/C-0-2
TEST(stat_cmd,uprobe_option)473 TEST(stat_cmd, uprobe_option) {
474   TEST_REQUIRE_ROOT();
475   EventSelectionSet event_selection_set(false);
476   ProbeEvents probe_events(event_selection_set);
477   if (!probe_events.IsProbeSupported(ProbeEventType::kUprobe)) {
478     GTEST_LOG_(INFO) << "Skip this test as uprobe isn't supported by the kernel.";
479     return;
480   }
481   if (!IsRegularFile("/system/lib64/libc.so")) {
482     GTEST_LOG_(INFO) << "Skip this test as /system/lib64/libc.so doesn't exist";
483     return;
484   }
485   ASSERT_TRUE(
486       StatCmd()->Run({"-e", "uprobes:myprobe", "--uprobe",
487                       "p:myprobe /system/lib64/libc.so:0x88e80", "-a", "--duration", SLEEP_SEC}));
488   ASSERT_TRUE(StatCmd()->Run({"-e", "uprobes:p_libc_0x88e80", "--uprobe",
489                               "p /system/lib64/libc.so:0x88e80", "-a", "--duration", SLEEP_SEC}));
490   ASSERT_TRUE(
491       StatCmd()->Run({"-e", "uprobes:myprobe", "--uprobe",
492                       "r:myprobe /system/lib64/libc.so:0x88e80", "-a", "--duration", SLEEP_SEC}));
493   ASSERT_TRUE(StatCmd()->Run({"-e", "uprobes:p_libc_0x88e80", "--uprobe",
494                               "r /system/lib64/libc.so:0x88e80", "-a", "--duration", SLEEP_SEC}));
495 }
496 
497 // @CddTest = 6.1/C-0-2
TEST(stat_cmd,tp_filter_option)498 TEST(stat_cmd, tp_filter_option) {
499   TEST_REQUIRE_HOST_ROOT();
500   TEST_REQUIRE_TRACEPOINT_EVENTS();
501   TEST_REQUIRE_KERNEL_EVENTS();
502   ASSERT_TRUE(StatCmd()->Run(
503       {"-e", "sched:sched_switch", "--tp-filter", "prev_comm != sleep", "sleep", SLEEP_SEC}));
504 }
505 
506 // @CddTest = 6.1/C-0-2
507 class StatCmdSummaryBuilderTest : public ::testing::Test {
508  protected:
509   struct CounterArg {
510     int event_id = 0;
511     int tid = 0;
512     int cpu = 0;
513     int value = 1;
514     int time_enabled = 1;
515     int time_running = 1;
516   };
517 
SetUp()518   void SetUp() override { sort_keys_ = {"count_per_thread", "tid", "cpu", "count"}; }
519 
AddCounter(const CounterArg & arg)520   void AddCounter(const CounterArg& arg) {
521     if (thread_map_.count(arg.tid) == 0) {
522       ThreadInfo& thread = thread_map_[arg.tid];
523       thread.pid = thread.tid = arg.tid;
524       thread.name = "thread" + std::to_string(arg.tid);
525     }
526     if (arg.event_id >= counters_.size()) {
527       counters_.resize(arg.event_id + 1);
528       counters_[arg.event_id].group_id = 0;
529       counters_[arg.event_id].event_name = "event" + std::to_string(arg.event_id);
530     }
531     CountersInfo& info = counters_[arg.event_id];
532     info.counters.resize(info.counters.size() + 1);
533     CounterInfo& counter = info.counters.back();
534     counter.tid = arg.tid;
535     counter.cpu = arg.cpu;
536     counter.counter.id = 0;
537     counter.counter.value = arg.value;
538     counter.counter.time_enabled = arg.time_enabled;
539     counter.counter.time_running = arg.time_running;
540   }
541 
BuildSummary(bool report_per_thread,bool report_per_core)542   std::vector<CounterSummary> BuildSummary(bool report_per_thread, bool report_per_core) {
543     std::optional<SummaryComparator> comparator =
544         BuildSummaryComparator(sort_keys_, report_per_thread, report_per_core);
545     CounterSummaryBuilder builder(report_per_thread, report_per_core, false, thread_map_,
546                                   comparator);
547     for (auto& info : counters_) {
548       builder.AddCountersForOneEventType(info);
549     }
550     return builder.Build();
551   }
552 
553   std::unordered_map<pid_t, ThreadInfo> thread_map_;
554   std::vector<CountersInfo> counters_;
555   std::vector<std::string> sort_keys_;
556 };
557 
558 // @CddTest = 6.1/C-0-2
TEST_F(StatCmdSummaryBuilderTest,multiple_events)559 TEST_F(StatCmdSummaryBuilderTest, multiple_events) {
560   AddCounter({.event_id = 0, .value = 1, .time_enabled = 1, .time_running = 1});
561   AddCounter({.event_id = 1, .value = 2, .time_enabled = 2, .time_running = 2});
562   std::vector<CounterSummary> summaries = BuildSummary(false, false);
563   ASSERT_EQ(summaries.size(), 2);
564   ASSERT_EQ(summaries[0].type_name, "event0");
565   ASSERT_EQ(summaries[0].count, 1);
566   ASSERT_NEAR(summaries[0].scale, 1.0, 1e-5);
567   ASSERT_EQ(summaries[1].type_name, "event1");
568   ASSERT_EQ(summaries[1].count, 2);
569   ASSERT_NEAR(summaries[1].scale, 1.0, 1e-5);
570 }
571 
572 // @CddTest = 6.1/C-0-2
TEST_F(StatCmdSummaryBuilderTest,default_aggregate)573 TEST_F(StatCmdSummaryBuilderTest, default_aggregate) {
574   AddCounter({.tid = 0, .cpu = 0, .value = 1, .time_enabled = 1, .time_running = 1});
575   AddCounter({.tid = 0, .cpu = 1, .value = 1, .time_enabled = 1, .time_running = 1});
576   AddCounter({.tid = 1, .cpu = 0, .value = 1, .time_enabled = 1, .time_running = 1});
577   AddCounter({.tid = 1, .cpu = 1, .value = 2, .time_enabled = 2, .time_running = 1});
578   std::vector<CounterSummary> summaries = BuildSummary(false, false);
579   ASSERT_EQ(summaries.size(), 1);
580   ASSERT_EQ(summaries[0].count, 5);
581   ASSERT_NEAR(summaries[0].scale, 1.25, 1e-5);
582 }
583 
584 // @CddTest = 6.1/C-0-2
TEST_F(StatCmdSummaryBuilderTest,per_thread_aggregate)585 TEST_F(StatCmdSummaryBuilderTest, per_thread_aggregate) {
586   AddCounter({.tid = 0, .cpu = 0, .value = 1, .time_enabled = 1, .time_running = 1});
587   AddCounter({.tid = 0, .cpu = 1, .value = 1, .time_enabled = 1, .time_running = 1});
588   AddCounter({.tid = 1, .cpu = 0, .value = 1, .time_enabled = 1, .time_running = 1});
589   AddCounter({.tid = 1, .cpu = 1, .value = 2, .time_enabled = 2, .time_running = 1});
590   std::vector<CounterSummary> summaries = BuildSummary(true, false);
591   ASSERT_EQ(summaries.size(), 2);
592   ASSERT_EQ(summaries[0].thread->tid, 1);
593   ASSERT_EQ(summaries[0].cpu, -1);
594   ASSERT_EQ(summaries[0].count, 3);
595   ASSERT_NEAR(summaries[0].scale, 1.5, 1e-5);
596   ASSERT_EQ(summaries[1].thread->tid, 0);
597   ASSERT_EQ(summaries[0].cpu, -1);
598   ASSERT_EQ(summaries[1].count, 2);
599   ASSERT_NEAR(summaries[1].scale, 1.0, 1e-5);
600 }
601 
602 // @CddTest = 6.1/C-0-2
TEST_F(StatCmdSummaryBuilderTest,per_core_aggregate)603 TEST_F(StatCmdSummaryBuilderTest, per_core_aggregate) {
604   AddCounter({.tid = 0, .cpu = 0, .value = 1, .time_enabled = 1, .time_running = 1});
605   AddCounter({.tid = 0, .cpu = 1, .value = 1, .time_enabled = 1, .time_running = 1});
606   AddCounter({.tid = 1, .cpu = 0, .value = 1, .time_enabled = 1, .time_running = 1});
607   AddCounter({.tid = 1, .cpu = 1, .value = 2, .time_enabled = 2, .time_running = 1});
608   std::vector<CounterSummary> summaries = BuildSummary(false, true);
609   ASSERT_TRUE(summaries[0].thread == nullptr);
610   ASSERT_EQ(summaries[0].cpu, 0);
611   ASSERT_EQ(summaries[0].count, 2);
612   ASSERT_NEAR(summaries[0].scale, 1.0, 1e-5);
613   ASSERT_EQ(summaries.size(), 2);
614   ASSERT_TRUE(summaries[1].thread == nullptr);
615   ASSERT_EQ(summaries[1].cpu, 1);
616   ASSERT_EQ(summaries[1].count, 3);
617   ASSERT_NEAR(summaries[1].scale, 1.5, 1e-5);
618 }
619 
620 // @CddTest = 6.1/C-0-2
TEST_F(StatCmdSummaryBuilderTest,per_thread_core_aggregate)621 TEST_F(StatCmdSummaryBuilderTest, per_thread_core_aggregate) {
622   AddCounter({.tid = 0, .cpu = 0, .value = 1, .time_enabled = 1, .time_running = 1});
623   AddCounter({.tid = 0, .cpu = 1, .value = 2, .time_enabled = 1, .time_running = 1});
624   AddCounter({.tid = 1, .cpu = 0, .value = 3, .time_enabled = 1, .time_running = 1});
625   AddCounter({.tid = 1, .cpu = 1, .value = 4, .time_enabled = 2, .time_running = 1});
626   std::vector<CounterSummary> summaries = BuildSummary(true, true);
627   ASSERT_EQ(summaries.size(), 4);
628   ASSERT_EQ(summaries[0].thread->tid, 1);
629   ASSERT_EQ(summaries[0].cpu, 0);
630   ASSERT_EQ(summaries[0].count, 3);
631   ASSERT_NEAR(summaries[0].scale, 1.0, 1e-5);
632   ASSERT_EQ(summaries[1].thread->tid, 1);
633   ASSERT_EQ(summaries[1].cpu, 1);
634   ASSERT_EQ(summaries[1].count, 4);
635   ASSERT_NEAR(summaries[1].scale, 2.0, 1e-5);
636   ASSERT_EQ(summaries[2].thread->tid, 0);
637   ASSERT_EQ(summaries[2].cpu, 0);
638   ASSERT_EQ(summaries[2].count, 1);
639   ASSERT_NEAR(summaries[2].scale, 1.0, 1e-5);
640   ASSERT_EQ(summaries[3].thread->tid, 0);
641   ASSERT_EQ(summaries[3].cpu, 1);
642   ASSERT_EQ(summaries[3].count, 2);
643   ASSERT_NEAR(summaries[3].scale, 1.0, 1e-5);
644 }
645 
646 // @CddTest = 6.1/C-0-2
TEST_F(StatCmdSummaryBuilderTest,sort_key_count)647 TEST_F(StatCmdSummaryBuilderTest, sort_key_count) {
648   sort_keys_ = {"count"};
649   AddCounter({.tid = 0, .cpu = 0, .value = 1});
650   AddCounter({.tid = 1, .cpu = 1, .value = 2});
651   std::vector<CounterSummary> summaries = BuildSummary(true, true);
652   ASSERT_EQ(summaries[0].count, 2);
653   ASSERT_EQ(summaries[1].count, 1);
654 }
655 
656 // @CddTest = 6.1/C-0-2
TEST_F(StatCmdSummaryBuilderTest,sort_key_count_per_thread)657 TEST_F(StatCmdSummaryBuilderTest, sort_key_count_per_thread) {
658   sort_keys_ = {"count_per_thread", "count"};
659   AddCounter({.tid = 0, .cpu = 0, .value = 1});
660   AddCounter({.tid = 0, .cpu = 1, .value = 5});
661   AddCounter({.tid = 1, .cpu = 0, .value = 3});
662   std::vector<CounterSummary> summaries = BuildSummary(true, true);
663   ASSERT_EQ(summaries[0].count, 5);
664   ASSERT_EQ(summaries[1].count, 1);
665   ASSERT_EQ(summaries[2].count, 3);
666 }
667 
668 // @CddTest = 6.1/C-0-2
TEST_F(StatCmdSummaryBuilderTest,sort_key_cpu)669 TEST_F(StatCmdSummaryBuilderTest, sort_key_cpu) {
670   sort_keys_ = {"cpu"};
671   AddCounter({.tid = 0, .cpu = 1, .value = 2});
672   AddCounter({.tid = 1, .cpu = 0, .value = 1});
673   std::vector<CounterSummary> summaries = BuildSummary(false, true);
674   ASSERT_EQ(summaries[0].cpu, 0);
675   ASSERT_EQ(summaries[1].cpu, 1);
676 }
677 
678 // @CddTest = 6.1/C-0-2
TEST_F(StatCmdSummaryBuilderTest,sort_key_pid_tid_name)679 TEST_F(StatCmdSummaryBuilderTest, sort_key_pid_tid_name) {
680   AddCounter({.tid = 0, .cpu = 0, .value = 1});
681   AddCounter({.tid = 1, .cpu = 0, .value = 2});
682 
683   for (auto& key : std::vector<std::string>({"tid", "pid", "comm"})) {
684     sort_keys_ = {key};
685     std::vector<CounterSummary> summaries = BuildSummary(true, false);
686     ASSERT_EQ(summaries[0].count, 1) << "key = " << key;
687     ASSERT_EQ(summaries[1].count, 2) << "key = " << key;
688   }
689 }
690 
691 // @CddTest = 6.1/C-0-2
692 class StatCmdSummariesTest : public ::testing::Test {
693  protected:
AddSummary(const std::string event_name,pid_t tid,int cpu,uint64_t count,uint64_t runtime_in_ns)694   void AddSummary(const std::string event_name, pid_t tid, int cpu, uint64_t count,
695                   uint64_t runtime_in_ns) {
696     ThreadInfo* thread = nullptr;
697     if (tid != -1) {
698       thread = &thread_map_[tid];
699     }
700     summary_v_.emplace_back(event_name, "", 0, thread, cpu, count, runtime_in_ns, 1.0, false,
701                             false);
702   }
703 
GetComment(size_t index)704   const std::string* GetComment(size_t index) {
705     if (!summaries_) {
706       summaries_.reset(new CounterSummaries(std::move(summary_v_), false));
707       summaries_->GenerateComments(1.0);
708     }
709     if (index < summaries_->Summaries().size()) {
710       return &(summaries_->Summaries()[index].comment);
711     }
712     return nullptr;
713   }
714 
715   std::unordered_map<pid_t, ThreadInfo> thread_map_;
716   std::vector<CounterSummary> summary_v_;
717   std::unique_ptr<CounterSummaries> summaries_;
718 };
719 
720 // @CddTest = 6.1/C-0-2
TEST_F(StatCmdSummariesTest,task_clock_comment)721 TEST_F(StatCmdSummariesTest, task_clock_comment) {
722   AddSummary("task-clock", -1, -1, 1e9, 0);
723   AddSummary("task-clock", 0, -1, 2e9, 0);
724   AddSummary("task-clock", -1, 0, 0.5e9, 0);
725   AddSummary("task-clock", 1, 1, 3e9, 0);
726   ASSERT_EQ(*GetComment(0), "1.000000 cpus used");
727   ASSERT_EQ(*GetComment(1), "2.000000 cpus used");
728   ASSERT_EQ(*GetComment(2), "0.500000 cpus used");
729   ASSERT_EQ(*GetComment(3), "3.000000 cpus used");
730 }
731 
732 // @CddTest = 6.1/C-0-2
TEST_F(StatCmdSummariesTest,cpu_cycles_comment)733 TEST_F(StatCmdSummariesTest, cpu_cycles_comment) {
734   AddSummary("cpu-cycles", -1, -1, 100, 100);
735   AddSummary("cpu-cycles", 0, -1, 200, 100);
736   AddSummary("cpu-cycles", -1, 0, 50, 100);
737   AddSummary("cpu-cycles", 1, 1, 300, 100);
738   ASSERT_EQ(*GetComment(0), "1.000000 GHz");
739   ASSERT_EQ(*GetComment(1), "2.000000 GHz");
740   ASSERT_EQ(*GetComment(2), "0.500000 GHz");
741   ASSERT_EQ(*GetComment(3), "3.000000 GHz");
742 }
743 
744 // @CddTest = 6.1/C-0-2
TEST_F(StatCmdSummariesTest,rate_comment)745 TEST_F(StatCmdSummariesTest, rate_comment) {
746   AddSummary("branch-misses", -1, -1, 1e9, 1e9);
747   AddSummary("branch-misses", 0, -1, 1e6, 1e9);
748   AddSummary("branch-misses", -1, 0, 1e3, 1e9);
749   AddSummary("branch-misses", 1, 1, 1, 1e9);
750   ASSERT_EQ(*GetComment(0), "1.000 G/sec");
751   ASSERT_EQ(*GetComment(1), "1.000 M/sec");
752   ASSERT_EQ(*GetComment(2), "1.000 K/sec");
753   ASSERT_EQ(*GetComment(3), "1.000 /sec");
754 }
755