• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2019 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 #include <sys/wait.h>
21 
22 #include <random>
23 
24 #include "perfetto/base/logging.h"
25 #include "perfetto/tracing/core/data_source_config.h"
26 #include "src/base/test/test_task_runner.h"
27 #include "test/android_test_utils.h"
28 #include "test/gtest_and_gmock.h"
29 #include "test/test_helper.h"
30 
31 #include "protos/perfetto/config/profiling/heapprofd_config.gen.h"
32 #include "protos/perfetto/trace/profiling/profile_common.gen.h"
33 #include "protos/perfetto/trace/profiling/profile_packet.gen.h"
34 #include "protos/perfetto/trace/trace_packet.gen.h"
35 
36 namespace perfetto {
37 namespace {
38 
39 // Size of individual (repeated) allocations done by the test apps (must be kept
40 // in sync with their sources).
41 constexpr uint64_t kTestSamplingInterval = 4096;
42 constexpr uint64_t kExpectedIndividualAllocSz = 4153;
43 // Tests rely on the sampling behaviour where allocations larger than the
44 // sampling interval are recorded at their actual size.
45 static_assert(kExpectedIndividualAllocSz > kTestSamplingInterval,
46               "kTestSamplingInterval invalid");
47 
48 // Activity that runs a JNI thread that repeatedly calls
49 // malloc(kExpectedIndividualAllocSz).
50 static char kMallocActivity[] = "MainActivity";
51 // Activity that runs a java thread that repeatedly constructs small java
52 // objects.
53 static char kJavaAllocActivity[] = "JavaAllocActivity";
54 
RandomSessionName()55 std::string RandomSessionName() {
56   std::random_device rd;
57   std::default_random_engine generator(rd());
58   std::uniform_int_distribution<> distribution('a', 'z');
59 
60   constexpr size_t kSessionNameLen = 20;
61   std::string result(kSessionNameLen, '\0');
62   for (size_t i = 0; i < kSessionNameLen; ++i)
63     result[i] = static_cast<char>(distribution(generator));
64   return result;
65 }
66 
67 // Starts the activity `activity` of the app `app_name` and later starts
68 // recording a trace with the allocations in `heap_names`.
69 //
70 // `heap_names` is a list of the heap names whose allocations will be recorded.
71 // An empty list means that only the allocations in the default malloc heap
72 // ("libc.malloc") are recorded.
73 //
74 // Returns the recorded trace.
ProfileRuntime(const std::string & app_name,const std::string & activity,const std::vector<std::string> & heap_names)75 std::vector<protos::gen::TracePacket> ProfileRuntime(
76     const std::string& app_name,
77     const std::string& activity,
78     const std::vector<std::string>& heap_names) {
79   base::TestTaskRunner task_runner;
80 
81   // (re)start the target app's main activity
82   if (IsAppRunning(app_name)) {
83     StopApp(app_name, "old.app.stopped", &task_runner);
84     task_runner.RunUntilCheckpoint("old.app.stopped", 10000 /*ms*/);
85   }
86   StartAppActivity(app_name, activity, "target.app.running", &task_runner,
87                    /*delay_ms=*/100);
88   task_runner.RunUntilCheckpoint("target.app.running", 10000 /*ms*/);
89 
90   // set up tracing
91   TestHelper helper(&task_runner);
92   helper.ConnectConsumer();
93   helper.WaitForConsumerConnect();
94 
95   TraceConfig trace_config;
96   trace_config.add_buffers()->set_size_kb(10 * 1024);
97   trace_config.set_duration_ms(4000);
98   trace_config.set_unique_session_name(RandomSessionName().c_str());
99 
100   auto* ds_config = trace_config.add_data_sources()->mutable_config();
101   ds_config->set_name("android.heapprofd");
102   ds_config->set_target_buffer(0);
103 
104   protos::gen::HeapprofdConfig heapprofd_config;
105   heapprofd_config.set_sampling_interval_bytes(kTestSamplingInterval);
106   heapprofd_config.add_process_cmdline(app_name.c_str());
107   heapprofd_config.set_block_client(true);
108   heapprofd_config.set_all(false);
109   for (const std::string& heap_name : heap_names) {
110     heapprofd_config.add_heaps(heap_name);
111   }
112   ds_config->set_heapprofd_config_raw(heapprofd_config.SerializeAsString());
113 
114   // start tracing
115   helper.StartTracing(trace_config);
116   helper.WaitForTracingDisabled();
117   helper.ReadData();
118   helper.WaitForReadData();
119 
120   return helper.trace();
121 }
122 
123 // Starts recording a trace with the allocations in `heap_names` and later
124 // starts the activity `activity` of the app `app_name`
125 //
126 // `heap_names` is a list of the heap names whose allocations will be recorded.
127 // An empty list means that only the allocation in the default malloc heap
128 // ("libc.malloc") are recorded.
129 //
130 // Returns the recorded trace.
ProfileStartup(const std::string & app_name,const std::string & activity,const std::vector<std::string> & heap_names,const bool enable_extra_guardrails=false)131 std::vector<protos::gen::TracePacket> ProfileStartup(
132     const std::string& app_name,
133     const std::string& activity,
134     const std::vector<std::string>& heap_names,
135     const bool enable_extra_guardrails = false) {
136   base::TestTaskRunner task_runner;
137 
138   if (IsAppRunning(app_name)) {
139     StopApp(app_name, "old.app.stopped", &task_runner);
140     task_runner.RunUntilCheckpoint("old.app.stopped", 10000 /*ms*/);
141   }
142 
143   // set up tracing
144   TestHelper helper(&task_runner);
145   helper.ConnectConsumer();
146   helper.WaitForConsumerConnect();
147 
148   TraceConfig trace_config;
149   trace_config.add_buffers()->set_size_kb(10 * 1024);
150   trace_config.set_duration_ms(4000);
151   trace_config.set_enable_extra_guardrails(enable_extra_guardrails);
152   trace_config.set_unique_session_name(RandomSessionName().c_str());
153 
154   auto* ds_config = trace_config.add_data_sources()->mutable_config();
155   ds_config->set_name("android.heapprofd");
156   ds_config->set_target_buffer(0);
157 
158   protos::gen::HeapprofdConfig heapprofd_config;
159   heapprofd_config.set_sampling_interval_bytes(kTestSamplingInterval);
160   heapprofd_config.add_process_cmdline(app_name.c_str());
161   heapprofd_config.set_block_client(true);
162   heapprofd_config.set_all(false);
163   for (const std::string& heap_name : heap_names) {
164     heapprofd_config.add_heaps(heap_name);
165   }
166   ds_config->set_heapprofd_config_raw(heapprofd_config.SerializeAsString());
167 
168   // start tracing
169   helper.StartTracing(trace_config);
170 
171   // start app
172   StartAppActivity(app_name, activity, "target.app.running", &task_runner,
173                    /*delay_ms=*/100);
174   task_runner.RunUntilCheckpoint("target.app.running", 10000 /*ms*/);
175 
176   helper.WaitForTracingDisabled();
177   helper.ReadData();
178   helper.WaitForReadData();
179 
180   return helper.trace();
181 }
182 
183 // Check that `packets` contain some allocations performed by kMallocActivity.
AssertExpectedMallocsPresent(const std::vector<protos::gen::TracePacket> & packets)184 void AssertExpectedMallocsPresent(
185     const std::vector<protos::gen::TracePacket>& packets) {
186   ASSERT_GT(packets.size(), 0u);
187 
188   // TODO(rsavitski): assert particular stack frames once we clarify the
189   // expected behaviour of unwinding native libs within an apk.
190   // Until then, look for an allocation that is a multiple of the expected
191   // allocation size.
192   bool found_alloc = false;
193   bool found_proc_dump = false;
194   for (const auto& packet : packets) {
195     for (const auto& proc_dump : packet.profile_packet().process_dumps()) {
196       found_proc_dump = true;
197       for (const auto& sample : proc_dump.samples()) {
198         if (sample.self_allocated() > 0 &&
199             sample.self_allocated() % kExpectedIndividualAllocSz == 0) {
200           found_alloc = true;
201 
202           EXPECT_TRUE(sample.self_freed() > 0 &&
203                       sample.self_freed() % kExpectedIndividualAllocSz == 0)
204               << "self_freed: " << sample.self_freed();
205         }
206       }
207     }
208   }
209   ASSERT_TRUE(found_proc_dump);
210   ASSERT_TRUE(found_alloc);
211 }
212 
213 // Check that `packets` contain some allocations performed by
214 // kJavaAllocActivity.
AssertExpectedArtAllocsPresent(const std::vector<protos::gen::TracePacket> & packets)215 void AssertExpectedArtAllocsPresent(
216     const std::vector<protos::gen::TracePacket>& packets) {
217   ASSERT_GT(packets.size(), 0u);
218 
219   bool found_alloc = false;
220   bool found_proc_dump = false;
221   for (const auto& packet : packets) {
222     for (const auto& proc_dump : packet.profile_packet().process_dumps()) {
223       found_proc_dump = true;
224       for (const auto& sample : proc_dump.samples()) {
225         if (sample.self_allocated() > 0) {
226           found_alloc = true;
227         }
228       }
229     }
230   }
231   ASSERT_TRUE(found_proc_dump);
232   ASSERT_TRUE(found_alloc);
233 }
234 
AssertNoProfileContents(const std::vector<protos::gen::TracePacket> & packets)235 void AssertNoProfileContents(
236     const std::vector<protos::gen::TracePacket>& packets) {
237   // If profile packets are present, they must be empty.
238   for (const auto& packet : packets) {
239     ASSERT_EQ(packet.profile_packet().process_dumps_size(), 0);
240   }
241 }
242 
TEST(HeapprofdCtsTest,DebuggableAppRuntime)243 TEST(HeapprofdCtsTest, DebuggableAppRuntime) {
244   std::string app_name = "android.perfetto.cts.app.debuggable";
245   const auto& packets =
246       ProfileRuntime(app_name, kMallocActivity, /*heap_names=*/{});
247   AssertExpectedMallocsPresent(packets);
248   StopApp(app_name);
249 }
250 
TEST(HeapprofdCtsTest,DebuggableAppStartup)251 TEST(HeapprofdCtsTest, DebuggableAppStartup) {
252   std::string app_name = "android.perfetto.cts.app.debuggable";
253   const auto& packets =
254       ProfileStartup(app_name, kMallocActivity, /*heap_names=*/{});
255   AssertExpectedMallocsPresent(packets);
256   StopApp(app_name);
257 }
258 
TEST(HeapprofdCtsTest,ProfileableAppRuntime)259 TEST(HeapprofdCtsTest, ProfileableAppRuntime) {
260   std::string app_name = "android.perfetto.cts.app.profileable";
261   const auto& packets =
262       ProfileRuntime(app_name, kMallocActivity, /*heap_names=*/{});
263   AssertExpectedMallocsPresent(packets);
264   StopApp(app_name);
265 }
266 
TEST(HeapprofdCtsTest,ProfileableAppStartup)267 TEST(HeapprofdCtsTest, ProfileableAppStartup) {
268   std::string app_name = "android.perfetto.cts.app.profileable";
269   const auto& packets =
270       ProfileStartup(app_name, kMallocActivity, /*heap_names=*/{});
271   AssertExpectedMallocsPresent(packets);
272   StopApp(app_name);
273 }
274 
TEST(HeapprofdCtsTest,ReleaseAppRuntime)275 TEST(HeapprofdCtsTest, ReleaseAppRuntime) {
276   std::string app_name = "android.perfetto.cts.app.release";
277   const auto& packets =
278       ProfileRuntime(app_name, kMallocActivity, /*heap_names=*/{});
279 
280   if (IsUserBuild())
281     AssertNoProfileContents(packets);
282   else
283     AssertExpectedMallocsPresent(packets);
284   StopApp(app_name);
285 }
286 
TEST(HeapprofdCtsTest,ReleaseAppStartup)287 TEST(HeapprofdCtsTest, ReleaseAppStartup) {
288   std::string app_name = "android.perfetto.cts.app.release";
289   const auto& packets =
290       ProfileStartup(app_name, kMallocActivity, /*heap_names=*/{});
291 
292   if (IsUserBuild())
293     AssertNoProfileContents(packets);
294   else
295     AssertExpectedMallocsPresent(packets);
296   StopApp(app_name);
297 }
298 
TEST(HeapprofdCtsTest,NonProfileableAppRuntime)299 TEST(HeapprofdCtsTest, NonProfileableAppRuntime) {
300   std::string app_name = "android.perfetto.cts.app.nonprofileable";
301   const auto& packets =
302       ProfileRuntime(app_name, kMallocActivity, /*heap_names=*/{});
303   if (IsUserBuild())
304     AssertNoProfileContents(packets);
305   else
306     AssertExpectedMallocsPresent(packets);
307   StopApp(app_name);
308 }
309 
TEST(HeapprofdCtsTest,NonProfileableAppStartup)310 TEST(HeapprofdCtsTest, NonProfileableAppStartup) {
311   std::string app_name = "android.perfetto.cts.app.nonprofileable";
312   const auto& packets =
313       ProfileStartup(app_name, kMallocActivity, /*heap_names=*/{});
314   if (IsUserBuild())
315     AssertNoProfileContents(packets);
316   else
317     AssertExpectedMallocsPresent(packets);
318   StopApp(app_name);
319 }
320 
TEST(HeapprofdCtsTest,JavaHeapRuntime)321 TEST(HeapprofdCtsTest, JavaHeapRuntime) {
322   std::string app_name = "android.perfetto.cts.app.debuggable";
323   const auto& packets = ProfileRuntime(app_name, kJavaAllocActivity,
324                                        /*heap_names=*/{"com.android.art"});
325   AssertExpectedArtAllocsPresent(packets);
326   StopApp(app_name);
327 }
328 
TEST(HeapprofdCtsTest,JavaHeapStartup)329 TEST(HeapprofdCtsTest, JavaHeapStartup) {
330   std::string app_name = "android.perfetto.cts.app.debuggable";
331   const auto& packets = ProfileStartup(app_name, kJavaAllocActivity,
332                                        /*heap_names=*/{"com.android.art"});
333   AssertExpectedArtAllocsPresent(packets);
334   StopApp(app_name);
335 }
336 
337 }  // namespace
338 }  // namespace perfetto
339