1 /*
2  * Copyright (C) 2020 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 <stdlib.h>
18 #include <sys/system_properties.h>
19 #include <sys/types.h>
20 
21 #include "perfetto/base/logging.h"
22 #include "perfetto/tracing/core/data_source_config.h"
23 #include "src/base/test/test_task_runner.h"
24 #include "test/cts/utils.h"
25 #include "test/gtest_and_gmock.h"
26 #include "test/test_helper.h"
27 
28 #include "protos/perfetto/config/profiling/perf_event_config.gen.h"
29 #include "protos/perfetto/trace/profiling/profile_common.gen.h"
30 #include "protos/perfetto/trace/profiling/profile_packet.gen.h"
31 #include "protos/perfetto/trace/trace_packet.gen.h"
32 
33 namespace perfetto {
34 namespace {
35 
36 // Skip these tests if the device in question doesn't have the necessary kernel
37 // LSM hooks in perf_event_open. This comes up when a device with an older
38 // kernel upgrades to R.
HasPerfLsmHooks()39 bool HasPerfLsmHooks() {
40   char buf[PROP_VALUE_MAX + 1] = {};
41   int ret = __system_property_get("sys.init.perf_lsm_hooks", buf);
42   PERFETTO_CHECK(ret >= 0);
43   return std::string(buf) == "1";
44 }
45 
ProfileSystemWide(std::string app_name)46 std::vector<protos::gen::TracePacket> ProfileSystemWide(std::string app_name) {
47   base::TestTaskRunner task_runner;
48 
49   // (re)start the target app's main activity
50   if (IsAppRunning(app_name)) {
51     StopApp(app_name, "old.app.stopped", &task_runner);
52     task_runner.RunUntilCheckpoint("old.app.stopped", 1000 /*ms*/);
53   }
54   StartAppActivity(app_name, "BusyWaitActivity", "target.app.running",
55                    &task_runner,
56                    /*delay_ms=*/100);
57   task_runner.RunUntilCheckpoint("target.app.running", 1000 /*ms*/);
58 
59   // set up tracing
60   TestHelper helper(&task_runner);
61   helper.ConnectConsumer();
62   helper.WaitForConsumerConnect();
63 
64   TraceConfig trace_config;
65   trace_config.add_buffers()->set_size_kb(20 * 1024);
66   trace_config.set_duration_ms(3000);
67   trace_config.set_data_source_stop_timeout_ms(8000);
68 
69   auto* ds_config = trace_config.add_data_sources()->mutable_config();
70   ds_config->set_name("linux.perf");
71   ds_config->set_target_buffer(0);
72 
73   protos::gen::PerfEventConfig perf_config;
74 
75   perf_config.set_all_cpus(true);
76   perf_config.set_sampling_frequency(10);  // Hz
77   ds_config->set_perf_event_config_raw(perf_config.SerializeAsString());
78 
79   // start tracing
80   helper.StartTracing(trace_config);
81   helper.WaitForTracingDisabled(15000 /*ms*/);
82   helper.ReadData();
83   helper.WaitForReadData();
84 
85   return helper.trace();
86 }
87 
AssertHasSampledStacksForPid(std::vector<protos::gen::TracePacket> packets,int pid)88 void AssertHasSampledStacksForPid(std::vector<protos::gen::TracePacket> packets,
89                                   int pid) {
90   uint32_t target_pid = static_cast<uint32_t>(pid);
91   ASSERT_GT(packets.size(), 0u);
92 
93   int total_perf_packets = 0;
94   int lost_records_packets = 0;
95   int full_samples = 0;
96   int target_samples = 0;
97   int target_skipped_samples = 0;
98   for (const auto& packet : packets) {
99     if (!packet.has_perf_sample())
100       continue;
101 
102     total_perf_packets++;
103     EXPECT_GT(packet.timestamp(), 0u) << "all packets should have a timestamp";
104     const auto& sample = packet.perf_sample();
105     if (sample.has_kernel_records_lost()) {
106       lost_records_packets++;
107       continue;
108     }
109     if (sample.has_sample_skipped_reason()) {
110       if (sample.pid() == target_pid)
111         target_skipped_samples++;
112       continue;
113     }
114 
115     full_samples++;
116     EXPECT_GT(sample.tid(), 0u);
117     EXPECT_GT(sample.callstack_iid(), 0u);
118 
119     if (sample.pid() == target_pid)
120       target_samples++;
121   }
122 
123   EXPECT_GT(target_samples, 0)
124       << "target_pid: " << target_pid << ", packets.size(): " << packets.size()
125       << ", total_perf_packets: " << total_perf_packets
126       << ", full_samples: " << full_samples
127       << ", lost_records_packets: " << lost_records_packets
128       << ", target_skipped_samples: " << target_skipped_samples << "\n";
129 }
130 
AssertNoStacksForPid(std::vector<protos::gen::TracePacket> packets,int pid)131 void AssertNoStacksForPid(std::vector<protos::gen::TracePacket> packets,
132                           int pid) {
133   uint32_t target_pid = static_cast<uint32_t>(pid);
134   // The process can still be sampled, but the stacks should be discarded
135   // without unwinding.
136   for (const auto& packet : packets) {
137     if (packet.perf_sample().pid() == target_pid) {
138       EXPECT_EQ(packet.perf_sample().callstack_iid(), 0u);
139       EXPECT_TRUE(packet.perf_sample().has_sample_skipped_reason());
140     }
141   }
142 }
143 
TEST(TracedPerfCtsTest,SystemWideDebuggableApp)144 TEST(TracedPerfCtsTest, SystemWideDebuggableApp) {
145   if (!HasPerfLsmHooks())
146     GTEST_SKIP() << "skipped due to lack of perf_event_open LSM hooks";
147 
148   std::string app_name = "android.perfetto.cts.app.debuggable";
149   const auto& packets = ProfileSystemWide(app_name);
150   int app_pid = PidForProcessName(app_name);
151   ASSERT_GT(app_pid, 0) << "failed to find pid for target process";
152 
153   AssertHasSampledStacksForPid(packets, app_pid);
154   PERFETTO_CHECK(IsAppRunning(app_name));
155   StopApp(app_name);
156 }
157 
TEST(TracedPerfCtsTest,SystemWideProfileableApp)158 TEST(TracedPerfCtsTest, SystemWideProfileableApp) {
159   if (!HasPerfLsmHooks())
160     GTEST_SKIP() << "skipped due to lack of perf_event_open LSM hooks";
161 
162   std::string app_name = "android.perfetto.cts.app.profileable";
163   const auto& packets = ProfileSystemWide(app_name);
164   int app_pid = PidForProcessName(app_name);
165   ASSERT_GT(app_pid, 0) << "failed to find pid for target process";
166 
167   AssertHasSampledStacksForPid(packets, app_pid);
168   PERFETTO_CHECK(IsAppRunning(app_name));
169   StopApp(app_name);
170 }
171 
TEST(TracedPerfCtsTest,SystemWideReleaseApp)172 TEST(TracedPerfCtsTest, SystemWideReleaseApp) {
173   if (!HasPerfLsmHooks())
174     GTEST_SKIP() << "skipped due to lack of perf_event_open LSM hooks";
175 
176   std::string app_name = "android.perfetto.cts.app.release";
177   const auto& packets = ProfileSystemWide(app_name);
178   int app_pid = PidForProcessName(app_name);
179   ASSERT_GT(app_pid, 0) << "failed to find pid for target process";
180 
181   if (IsDebuggableBuild())
182     AssertHasSampledStacksForPid(packets, app_pid);
183   else
184     AssertNoStacksForPid(packets, app_pid);
185 
186   PERFETTO_CHECK(IsAppRunning(app_name));
187   StopApp(app_name);
188 }
189 
190 }  // namespace
191 }  // namespace perfetto
192