blob: 63d58dba6cf7ade236cbcec60498992f56ada8e9 [file] [log] [blame]
Than McIntosh7e2f4e92015-03-05 11:05:02 -05001/*
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
Than McIntosh7e2f4e92015-03-05 11:05:02 -050017#include <algorithm>
18#include <cctype>
Andreas Gampe54237f82018-01-18 21:20:36 -080019#include <functional>
Andreas Gampe0c09e0e2018-03-13 16:04:01 -070020#include <iterator>
Andreas Gampe32695342018-01-03 22:28:18 -080021#include <memory>
Andreas Gampe54237f82018-01-18 21:20:36 -080022#include <mutex>
Than McIntosh7e2f4e92015-03-05 11:05:02 -050023#include <regex>
Andreas Gampe32695342018-01-03 22:28:18 -080024#include <string>
25
26#include <fcntl.h>
Than McIntosh7e2f4e92015-03-05 11:05:02 -050027#include <stdio.h>
Andreas Gampe32695342018-01-03 22:28:18 -080028#include <libgen.h>
Than McIntosh7e2f4e92015-03-05 11:05:02 -050029#include <sys/types.h>
30#include <sys/stat.h>
Than McIntosh7e2f4e92015-03-05 11:05:02 -050031
Andreas Gampe32695342018-01-03 22:28:18 -080032#include <android-base/file.h>
33#include <android-base/logging.h>
Andreas Gamped9084f62018-01-10 11:37:20 -080034#include <android-base/macros.h>
Elliott Hughes66dd09e2015-12-04 14:00:57 -080035#include <android-base/stringprintf.h>
Andreas Gamped9084f62018-01-10 11:37:20 -080036#include <android-base/strings.h>
Andreas Gampe32695342018-01-03 22:28:18 -080037#include <android-base/test_utils.h>
Andreas Gampe54237f82018-01-18 21:20:36 -080038#include <android-base/thread_annotations.h>
Andreas Gampe32695342018-01-03 22:28:18 -080039#include <gtest/gtest.h>
Andreas Gampe894b3f92018-03-22 19:48:48 -070040#include <zlib.h>
Dehao Chenf4605012015-05-07 13:16:35 -070041
Andreas Gampee44ae142017-12-21 10:02:23 -080042#include "config.h"
Than McIntosh8c7c7db2015-09-03 15:16:04 -040043#include "configreader.h"
Andreas Gampecbc02bc2018-03-21 16:05:26 -070044#include "map_utils.h"
Andreas Gampee44ae142017-12-21 10:02:23 -080045#include "perfprofdcore.h"
Andreas Gampe04672dd2018-03-28 14:28:18 -070046#include "perfprofd_cmdline.h"
Andreas Gampeb019ddc2018-04-02 10:58:32 -070047#include "perfprofd_threaded_handler.h"
Andreas Gampe77ca78a2018-03-21 16:02:02 -070048#include "quipper_helper.h"
Andreas Gampef9a35612018-01-04 14:22:50 -080049#include "symbolizer.h"
Than McIntosh7e2f4e92015-03-05 11:05:02 -050050
Andreas Gampe0c09e0e2018-03-13 16:04:01 -070051#include "perfprofd_record.pb.h"
Than McIntosh7e2f4e92015-03-05 11:05:02 -050052
Andreas Gampe77ca78a2018-03-21 16:02:02 -070053using namespace android::perfprofd::quipper;
54
Andreas Gampeb5c37092018-03-22 20:25:33 -070055static_assert(android::base::kEnableDChecks, "Expected DCHECKs to be enabled");
56
Than McIntosh7e2f4e92015-03-05 11:05:02 -050057//
58// Set to argv[0] on startup
59//
Andreas Gampe32695342018-01-03 22:28:18 -080060static std::string gExecutableRealpath;
Than McIntosh7e2f4e92015-03-05 11:05:02 -050061
Andreas Gamped9084f62018-01-10 11:37:20 -080062namespace {
63
64using android::base::LogId;
65using android::base::LogSeverity;
66
Andreas Gampe54237f82018-01-18 21:20:36 -080067class TestLogHelper {
68 public:
69 void Install() {
70 using namespace std::placeholders;
71 android::base::SetLogger(
72 std::bind(&TestLogHelper::TestLogFunction, this, _1, _2, _3, _4, _5, _6));
73 }
Andreas Gamped9084f62018-01-10 11:37:20 -080074
Andreas Gampe54237f82018-01-18 21:20:36 -080075 std::string JoinTestLog(const char* delimiter) {
76 std::unique_lock<std::mutex> ul(lock_);
77 return android::base::Join(test_log_messages_, delimiter);
78 }
Andreas Gampe0c09e0e2018-03-13 16:04:01 -070079 template <typename Predicate>
80 std::string JoinTestLog(const char* delimiter, Predicate pred) {
81 std::unique_lock<std::mutex> ul(lock_);
82 std::vector<std::string> tmp;
83 std::copy_if(test_log_messages_.begin(),
84 test_log_messages_.end(),
85 std::back_inserter(tmp),
86 pred);
87 return android::base::Join(tmp, delimiter);
88 }
Andreas Gamped9084f62018-01-10 11:37:20 -080089
Andreas Gampe54237f82018-01-18 21:20:36 -080090 private:
Andreas Gampecbc02bc2018-03-21 16:05:26 -070091 void TestLogFunction(LogId log_id,
Andreas Gampe54237f82018-01-18 21:20:36 -080092 LogSeverity severity,
93 const char* tag,
Andreas Gampecbc02bc2018-03-21 16:05:26 -070094 const char* file,
95 unsigned int line,
Andreas Gampe54237f82018-01-18 21:20:36 -080096 const char* message) {
97 std::unique_lock<std::mutex> ul(lock_);
98 constexpr char log_characters[] = "VDIWEFF";
99 char severity_char = log_characters[severity];
100 test_log_messages_.push_back(android::base::StringPrintf("%c: %s", severity_char, message));
Andreas Gampecbc02bc2018-03-21 16:05:26 -0700101
102 if (severity >= LogSeverity::FATAL_WITHOUT_ABORT) {
103 android::base::StderrLogger(log_id, severity, tag, file, line, message);
104 }
Andreas Gampe54237f82018-01-18 21:20:36 -0800105 }
106
107 private:
108 std::mutex lock_;
109
110 std::vector<std::string> test_log_messages_;
111};
Andreas Gamped9084f62018-01-10 11:37:20 -0800112
113} // namespace
114
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500115// Path to perf executable on device
116#define PERFPATH "/system/bin/perf"
117
118// Temporary config file that we will emit for the daemon to read
119#define CONFIGFILE "perfprofd.conf"
120
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500121static bool bothWhiteSpace(char lhs, char rhs)
122{
123 return (std::isspace(lhs) && std::isspace(rhs));
124}
125
126//
127// Squeeze out repeated whitespace from expected/actual logs.
128//
129static std::string squeezeWhite(const std::string &str,
130 const char *tag,
131 bool dump=false)
132{
133 if (dump) { fprintf(stderr, "raw %s is %s\n", tag, str.c_str()); }
134 std::string result(str);
Alexey Alexandrova5cbb7a2016-09-24 17:05:28 -0700135 std::replace(result.begin(), result.end(), '\n', ' ');
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500136 auto new_end = std::unique(result.begin(), result.end(), bothWhiteSpace);
137 result.erase(new_end, result.end());
138 while (result.begin() != result.end() && std::isspace(*result.rbegin())) {
139 result.pop_back();
140 }
141 if (dump) { fprintf(stderr, "squeezed %s is %s\n", tag, result.c_str()); }
142 return result;
143}
144
Alexey Alexandrova5cbb7a2016-09-24 17:05:28 -0700145//
146// Replace all occurrences of a string with another string.
147//
148static std::string replaceAll(const std::string &str,
149 const std::string &from,
150 const std::string &to)
151{
152 std::string ret = "";
153 size_t pos = 0;
154 while (pos < str.size()) {
155 size_t found = str.find(from, pos);
156 if (found == std::string::npos) {
157 ret += str.substr(pos);
158 break;
159 }
160 ret += str.substr(pos, found - pos) + to;
161 pos = found + from.size();
162 }
163 return ret;
164}
165
166//
167// Replace occurrences of special variables in the string.
168//
Andreas Gampe51389ce2018-03-13 20:55:56 -0700169#ifdef __ANDROID__
Alexey Alexandrova5cbb7a2016-09-24 17:05:28 -0700170static std::string expandVars(const std::string &str) {
171#ifdef __LP64__
172 return replaceAll(str, "$NATIVE_TESTS", "/data/nativetest64");
173#else
174 return replaceAll(str, "$NATIVE_TESTS", "/data/nativetest");
175#endif
176}
Andreas Gampe51389ce2018-03-13 20:55:56 -0700177#endif
Alexey Alexandrova5cbb7a2016-09-24 17:05:28 -0700178
Andreas Gampe54237f82018-01-18 21:20:36 -0800179class PerfProfdTest : public testing::Test {
180 protected:
181 virtual void SetUp() {
182 test_logger.Install();
183 create_dirs();
184 }
185
186 virtual void TearDown() {
187 android::base::SetLogger(android::base::StderrLogger);
188
189 // TODO: proper management of test files. For now, use old system() code.
190 for (const auto dir : { &dest_dir, &conf_dir }) {
191 std::string cmd("rm -rf ");
192 cmd += *dir;
193 int ret = system(cmd.c_str());
194 CHECK_EQ(0, ret);
195 }
196 }
197
198 protected:
199 //
200 // Check to see if the log messages emitted by the daemon
201 // match the expected result. By default we use a partial
202 // match, e.g. if we see the expected excerpt anywhere in the
203 // result, it's a match (for exact match, set exact to true)
204 //
Andreas Gamped0525702018-06-12 09:56:11 -0700205 ::testing::AssertionResult CompareLogMessages(const std::string& expected,
206 bool exactMatch = false) {
Andreas Gampe54237f82018-01-18 21:20:36 -0800207 std::string sqexp = squeezeWhite(expected, "expected");
Andreas Gampe0c09e0e2018-03-13 16:04:01 -0700208
209 // Strip out JIT errors.
210 std::regex jit_regex("E: Failed to open ELF file: [^ ]*ashmem/dalvik-jit-code-cache.*");
211 auto strip_jit = [&](const std::string& str) {
212 std::smatch jit_match;
213 return !std::regex_match(str, jit_match, jit_regex);
214 };
215 std::string sqact = squeezeWhite(test_logger.JoinTestLog(" ", strip_jit), "actual");
216
Andreas Gampe54237f82018-01-18 21:20:36 -0800217 if (exactMatch) {
Andreas Gamped0525702018-06-12 09:56:11 -0700218 if (sqexp == sqact) {
219 return ::testing::AssertionSuccess() << sqexp << " is equal to " << sqact;
Andreas Gampe54237f82018-01-18 21:20:36 -0800220 }
Andreas Gamped0525702018-06-12 09:56:11 -0700221 return ::testing::AssertionFailure() << "Expected:" << std::endl << sqexp << std::endl
222 << "Received:" << std::endl << sqact;
223 } else {
224 if (sqact.find(sqexp) == std::string::npos) {
225 return ::testing::AssertionFailure()
226 << "Expected to find:" << std::endl << sqexp << std::endl
227 << "in:" << std::endl << sqact;
228 }
229 return ::testing::AssertionSuccess() << sqexp << " was found in " << sqact;
Andreas Gampe54237f82018-01-18 21:20:36 -0800230 }
231 }
232
233 // test_dir is the directory containing the test executable and
234 // any files associated with the test (will be created by the harness).
235 std::string test_dir;
236
237 // dest_dir is a temporary directory that we're using as the destination directory.
238 // It is backed by temp_dir1.
239 std::string dest_dir;
240
241 // conf_dir is a temporary directory that we're using as the configuration directory.
242 // It is backed by temp_dir2.
243 std::string conf_dir;
244
245 TestLogHelper test_logger;
246
247 private:
248 void create_dirs() {
249 temp_dir1.reset(new TemporaryDir());
250 temp_dir2.reset(new TemporaryDir());
251 dest_dir = temp_dir1->path;
252 conf_dir = temp_dir2->path;
253 test_dir = android::base::Dirname(gExecutableRealpath);
254 }
255
256 std::unique_ptr<TemporaryDir> temp_dir1;
257 std::unique_ptr<TemporaryDir> temp_dir2;
258};
259
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500260///
261/// Helper class to kick off a run of the perfprofd daemon with a specific
262/// config file.
263///
264class PerfProfdRunner {
265 public:
Andreas Gampe32695342018-01-03 22:28:18 -0800266 explicit PerfProfdRunner(const std::string& config_dir)
267 : config_dir_(config_dir)
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500268 {
Andreas Gampe32695342018-01-03 22:28:18 -0800269 config_path_ = config_dir + "/" CONFIGFILE;
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500270 }
271
272 ~PerfProfdRunner()
273 {
Dehao Chenf4605012015-05-07 13:16:35 -0700274 remove_processed_file();
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500275 }
276
277 void addToConfig(const std::string &line)
278 {
279 config_text_ += line;
280 config_text_ += "\n";
281 }
282
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500283 void remove_semaphore_file()
284 {
Andreas Gampe32695342018-01-03 22:28:18 -0800285 std::string semaphore(config_dir_);
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500286 semaphore += "/" SEMAPHORE_FILENAME;
287 unlink(semaphore.c_str());
288 }
289
290 void create_semaphore_file()
291 {
Andreas Gampe32695342018-01-03 22:28:18 -0800292 std::string semaphore(config_dir_);
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500293 semaphore += "/" SEMAPHORE_FILENAME;
George Burgess IV609b7652017-01-31 22:46:46 -0800294 close(open(semaphore.c_str(), O_WRONLY|O_CREAT, 0600));
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500295 }
296
Dehao Chenf4605012015-05-07 13:16:35 -0700297 void write_processed_file(int start_seq, int end_seq)
298 {
Andreas Gampe32695342018-01-03 22:28:18 -0800299 std::string processed = config_dir_ + "/" PROCESSED_FILENAME;
Dehao Chenf4605012015-05-07 13:16:35 -0700300 FILE *fp = fopen(processed.c_str(), "w");
301 for (int i = start_seq; i < end_seq; i++) {
302 fprintf(fp, "%d\n", i);
303 }
304 fclose(fp);
305 }
306
307 void remove_processed_file()
308 {
Andreas Gampe32695342018-01-03 22:28:18 -0800309 std::string processed = config_dir_ + "/" PROCESSED_FILENAME;
Dehao Chenf4605012015-05-07 13:16:35 -0700310 unlink(processed.c_str());
311 }
312
Andreas Gampe517f4e92017-12-21 10:26:36 -0800313 struct LoggingConfig : public Config {
314 void Sleep(size_t seconds) override {
315 // Log sleep calls but don't sleep.
Andreas Gamped9084f62018-01-10 11:37:20 -0800316 LOG(INFO) << "sleep " << seconds << " seconds";
Andreas Gampe517f4e92017-12-21 10:26:36 -0800317 }
Andreas Gampea3498502017-12-27 11:23:41 -0800318
319 bool IsProfilingEnabled() const override {
320 //
321 // Check for existence of semaphore file in config directory
322 //
323 if (access(config_directory.c_str(), F_OK) == -1) {
Andreas Gamped9084f62018-01-10 11:37:20 -0800324 PLOG(WARNING) << "unable to open config directory " << config_directory;
Andreas Gampea3498502017-12-27 11:23:41 -0800325 return false;
326 }
327
328 // Check for existence of semaphore file
329 std::string semaphore_filepath = config_directory
330 + "/" + SEMAPHORE_FILENAME;
331 if (access(semaphore_filepath.c_str(), F_OK) == -1) {
332 return false;
333 }
334
335 return true;
336 }
Andreas Gampe517f4e92017-12-21 10:26:36 -0800337 };
338
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500339 int invoke()
340 {
341 static const char *argv[3] = { "perfprofd", "-c", "" };
342 argv[2] = config_path_.c_str();
343
344 writeConfigFile(config_path_, config_text_);
Than McIntosh07f00fd2015-04-17 15:10:43 -0400345
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500346 // execute daemon main
Andreas Gampe517f4e92017-12-21 10:26:36 -0800347 LoggingConfig config;
Andreas Gampee44ae142017-12-21 10:02:23 -0800348 return perfprofd_main(3, (char **) argv, &config);
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500349 }
350
351 private:
Andreas Gampe32695342018-01-03 22:28:18 -0800352 std::string config_dir_;
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500353 std::string config_path_;
354 std::string config_text_;
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500355
356 void writeConfigFile(const std::string &config_path,
357 const std::string &config_text)
358 {
359 FILE *fp = fopen(config_path.c_str(), "w");
360 ASSERT_TRUE(fp != nullptr);
361 fprintf(fp, "%s\n", config_text.c_str());
362 fclose(fp);
363 }
364};
365
366//......................................................................
367
Andreas Gampe32695342018-01-03 22:28:18 -0800368static std::string encoded_file_path(const std::string& dest_dir,
369 int seq) {
370 return android::base::StringPrintf("%s/perf.data.encoded.%d",
371 dest_dir.c_str(), seq);
372}
373
374static void readEncodedProfile(const std::string& dest_dir,
Andreas Gampe894b3f92018-03-22 19:48:48 -0700375 bool compressed,
Andreas Gampe0c09e0e2018-03-13 16:04:01 -0700376 android::perfprofd::PerfprofdRecord& encodedProfile)
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500377{
378 struct stat statb;
Andreas Gampe32695342018-01-03 22:28:18 -0800379 int perf_data_stat_result = stat(encoded_file_path(dest_dir, 0).c_str(), &statb);
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500380 ASSERT_NE(-1, perf_data_stat_result);
381
382 // read
383 std::string encoded;
384 encoded.resize(statb.st_size);
Andreas Gampe32695342018-01-03 22:28:18 -0800385 FILE *ifp = fopen(encoded_file_path(dest_dir, 0).c_str(), "r");
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500386 ASSERT_NE(nullptr, ifp);
387 size_t items_read = fread((void*) encoded.data(), statb.st_size, 1, ifp);
388 ASSERT_EQ(1, items_read);
389 fclose(ifp);
390
Andreas Gampe894b3f92018-03-22 19:48:48 -0700391 // uncompress
392 if (compressed && !encoded.empty()) {
393 z_stream stream;
394 stream.zalloc = Z_NULL;
395 stream.zfree = Z_NULL;
396 stream.opaque = Z_NULL;
397
398 {
399 constexpr int kWindowBits = 15;
400 constexpr int kGzipEncoding = 16;
401 int init_result = inflateInit2(&stream, kWindowBits | kGzipEncoding);
402 if (init_result != Z_OK) {
403 LOG(ERROR) << "Could not initialize libz stream " << init_result;
404 return;
405 }
406 }
407
408 std::string buf;
409 buf.reserve(2 * encoded.size());
410 stream.avail_in = encoded.size();
411 stream.next_in = reinterpret_cast<Bytef*>(const_cast<char*>(encoded.data()));
412
413 int result;
414 do {
415 uint8_t chunk[1024];
416 stream.next_out = static_cast<Bytef*>(chunk);
417 stream.avail_out = arraysize(chunk);
418
419 result = inflate(&stream, 0);
420 const size_t amount = arraysize(chunk) - stream.avail_out;
421 if (amount > 0) {
422 if (buf.capacity() - buf.size() < amount) {
423 buf.reserve(buf.capacity() + 64u * 1024u);
424 CHECK_LE(amount, buf.capacity() - buf.size());
425 }
426 size_t index = buf.size();
427 buf.resize(buf.size() + amount);
428 memcpy(reinterpret_cast<uint8_t*>(const_cast<char*>(buf.data())) + index, chunk, amount);
429 }
430 } while (result == Z_OK);
431 inflateEnd(&stream);
432 if (result != Z_STREAM_END) {
433 LOG(ERROR) << "Finished with not-Z_STREAM_END " << result;
434 return;
435 }
436 encoded = buf;
437 }
438
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500439 // decode
440 encodedProfile.ParseFromString(encoded);
Than McIntosh124dd422015-04-29 14:48:32 -0400441}
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500442
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500443#define RAW_RESULT(x) #x
444
Alexey Alexandrova5cbb7a2016-09-24 17:05:28 -0700445TEST_F(PerfProfdTest, TestUtil)
446{
447 EXPECT_EQ("", replaceAll("", "", ""));
448 EXPECT_EQ("zzbc", replaceAll("abc", "a", "zz"));
449 EXPECT_EQ("azzc", replaceAll("abc", "b", "zz"));
450 EXPECT_EQ("abzz", replaceAll("abc", "c", "zz"));
451 EXPECT_EQ("xxyyzz", replaceAll("abc", "abc", "xxyyzz"));
452}
453
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500454TEST_F(PerfProfdTest, MissingGMS)
455{
456 //
457 // AWP requires cooperation between the daemon and the GMS core
458 // piece. If we're running on a device that has an old or damaged
Dehao Chen58bade32015-05-05 15:03:48 -0700459 // version of GMS core, then the config directory we're interested in
460 // may not be there. This test insures that the daemon does the
461 // right thing in this case.
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500462 //
Andreas Gampe32695342018-01-03 22:28:18 -0800463 PerfProfdRunner runner(conf_dir);
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500464 runner.addToConfig("only_debug_build=0");
Than McIntoshf353d8b2015-05-21 14:44:34 -0400465 runner.addToConfig("trace_config_read=0");
Dehao Chen58bade32015-05-05 15:03:48 -0700466 runner.addToConfig("config_directory=/does/not/exist");
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500467 runner.addToConfig("main_loop_iterations=1");
468 runner.addToConfig("use_fixed_seed=1");
469 runner.addToConfig("collection_interval=100");
470
471 // Kick off daemon
472 int daemon_main_return_code = runner.invoke();
473
474 // Check return code from daemon
475 EXPECT_EQ(0, daemon_main_return_code);
476
477 // Verify log contents
478 const std::string expected = RAW_RESULT(
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500479 I: sleep 90 seconds
Andreas Gamped9084f62018-01-10 11:37:20 -0800480 W: unable to open config directory /does/not/exist: No such file or directory
Dehao Chen58bade32015-05-05 15:03:48 -0700481 I: profile collection skipped (missing config directory)
482 );
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500483
484 // check to make sure entire log matches
Andreas Gamped0525702018-06-12 09:56:11 -0700485 EXPECT_TRUE(CompareLogMessages(expected));
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500486}
487
Dehao Chen58bade32015-05-05 15:03:48 -0700488
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500489TEST_F(PerfProfdTest, MissingOptInSemaphoreFile)
490{
491 //
492 // Android device owners must opt in to "collect and report usage
493 // data" in order for us to be able to collect profiles. The opt-in
494 // check is performed in the GMS core component; if the check
495 // passes, then it creates a semaphore file for the daemon to pick
496 // up on.
497 //
Andreas Gampe32695342018-01-03 22:28:18 -0800498 PerfProfdRunner runner(conf_dir);
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500499 runner.addToConfig("only_debug_build=0");
Andreas Gampe32695342018-01-03 22:28:18 -0800500 std::string cfparam("config_directory="); cfparam += conf_dir;
Dehao Chen58bade32015-05-05 15:03:48 -0700501 runner.addToConfig(cfparam);
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500502 std::string ddparam("destination_directory="); ddparam += dest_dir;
503 runner.addToConfig(ddparam);
504 runner.addToConfig("main_loop_iterations=1");
505 runner.addToConfig("use_fixed_seed=1");
506 runner.addToConfig("collection_interval=100");
507
508 runner.remove_semaphore_file();
509
510 // Kick off daemon
511 int daemon_main_return_code = runner.invoke();
512
513 // Check return code from daemon
514 EXPECT_EQ(0, daemon_main_return_code);
515
516 // Verify log contents
517 const std::string expected = RAW_RESULT(
Andreas Gampe44e63a72018-01-03 12:39:53 -0800518 I: profile collection skipped (missing config directory)
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500519 );
520 // check to make sure log excerpt matches
Andreas Gamped0525702018-06-12 09:56:11 -0700521 EXPECT_TRUE(CompareLogMessages(expected));
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500522}
523
524TEST_F(PerfProfdTest, MissingPerfExecutable)
525{
526 //
Than McIntosh07f00fd2015-04-17 15:10:43 -0400527 // Perfprofd uses the 'simpleperf' tool to collect profiles
528 // (although this may conceivably change in the future). This test
529 // checks to make sure that if 'simpleperf' is not present we bail out
530 // from collecting profiles.
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500531 //
Andreas Gampe32695342018-01-03 22:28:18 -0800532 PerfProfdRunner runner(conf_dir);
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500533 runner.addToConfig("only_debug_build=0");
534 runner.addToConfig("trace_config_read=1");
Andreas Gampe32695342018-01-03 22:28:18 -0800535 std::string cfparam("config_directory="); cfparam += conf_dir;
Dehao Chen58bade32015-05-05 15:03:48 -0700536 runner.addToConfig(cfparam);
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500537 std::string ddparam("destination_directory="); ddparam += dest_dir;
538 runner.addToConfig(ddparam);
539 runner.addToConfig("main_loop_iterations=1");
540 runner.addToConfig("use_fixed_seed=1");
541 runner.addToConfig("collection_interval=100");
542 runner.addToConfig("perf_path=/does/not/exist");
543
544 // Create semaphore file
545 runner.create_semaphore_file();
546
547 // Kick off daemon
548 int daemon_main_return_code = runner.invoke();
549
550 // Check return code from daemon
551 EXPECT_EQ(0, daemon_main_return_code);
552
553 // expected log contents
554 const std::string expected = RAW_RESULT(
555 I: profile collection skipped (missing 'perf' executable)
556 );
557 // check to make sure log excerpt matches
Andreas Gamped0525702018-06-12 09:56:11 -0700558 EXPECT_TRUE(CompareLogMessages(expected));
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500559}
560
561TEST_F(PerfProfdTest, BadPerfRun)
562{
563 //
Than McIntosh07f00fd2015-04-17 15:10:43 -0400564 // Perf tools tend to be tightly coupled with a specific kernel
565 // version -- if things are out of sync perf could fail or
566 // crash. This test makes sure that we detect such a case and log
567 // the error.
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500568 //
Andreas Gampe32695342018-01-03 22:28:18 -0800569 PerfProfdRunner runner(conf_dir);
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500570 runner.addToConfig("only_debug_build=0");
Andreas Gampe32695342018-01-03 22:28:18 -0800571 std::string cfparam("config_directory="); cfparam += conf_dir;
Dehao Chen58bade32015-05-05 15:03:48 -0700572 runner.addToConfig(cfparam);
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500573 std::string ddparam("destination_directory="); ddparam += dest_dir;
574 runner.addToConfig(ddparam);
575 runner.addToConfig("main_loop_iterations=1");
576 runner.addToConfig("use_fixed_seed=1");
577 runner.addToConfig("collection_interval=100");
Andreas Gampe51389ce2018-03-13 20:55:56 -0700578#ifdef __ANDROID__
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500579 runner.addToConfig("perf_path=/system/bin/false");
Andreas Gampe51389ce2018-03-13 20:55:56 -0700580#else
581 runner.addToConfig("perf_path=/bin/false");
582#endif
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500583
584 // Create semaphore file
585 runner.create_semaphore_file();
586
587 // Kick off daemon
588 int daemon_main_return_code = runner.invoke();
589
590 // Check return code from daemon
591 EXPECT_EQ(0, daemon_main_return_code);
592
Andreas Gampe36a0b892018-06-12 09:54:42 -0700593 // Verify log contents. Because of perferr logging containing pids and test paths,
594 // it is easier to have three expected parts.
595 const std::string expected1 = "W: perf bad exit status 1";
596 const std::string expected2 = "W: /bin/false record";
597 const std::string expected3 = "W: profile collection failed";
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500598
599 // check to make sure log excerpt matches
Andreas Gampe36a0b892018-06-12 09:54:42 -0700600 EXPECT_TRUE(CompareLogMessages(expected1));
601 EXPECT_TRUE(CompareLogMessages(expected2));
602 EXPECT_TRUE(CompareLogMessages(expected3));
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500603}
604
605TEST_F(PerfProfdTest, ConfigFileParsing)
606{
607 //
608 // Gracefully handly malformed items in the config file
609 //
Andreas Gampe32695342018-01-03 22:28:18 -0800610 PerfProfdRunner runner(conf_dir);
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500611 runner.addToConfig("only_debug_build=0");
612 runner.addToConfig("main_loop_iterations=1");
613 runner.addToConfig("collection_interval=100");
614 runner.addToConfig("use_fixed_seed=1");
615 runner.addToConfig("destination_directory=/does/not/exist");
616
617 // assorted bad syntax
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500618 runner.addToConfig("collection_interval=-1");
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500619 runner.addToConfig("nonexistent_key=something");
620 runner.addToConfig("no_equals_stmt");
621
622 // Kick off daemon
623 int daemon_main_return_code = runner.invoke();
624
625 // Check return code from daemon
626 EXPECT_EQ(0, daemon_main_return_code);
627
628 // Verify log contents
629 const std::string expected = RAW_RESULT(
Andreas Gampeac743a32018-05-24 09:43:37 -0700630 W: line 6: specified value 18446744073709551615 for 'collection_interval' outside permitted range [0 4294967295]
631 W: line 7: unknown option 'nonexistent_key'
Andreas Gampe59a18212018-04-30 16:55:15 -0700632 W: line 8: line malformed (no '=' found)
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500633 );
634
635 // check to make sure log excerpt matches
Andreas Gamped0525702018-06-12 09:56:11 -0700636 EXPECT_TRUE(CompareLogMessages(expected));
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500637}
638
Than McIntosh8c7c7db2015-09-03 15:16:04 -0400639TEST_F(PerfProfdTest, ProfileCollectionAnnotations)
640{
641 unsigned util1 = collect_cpu_utilization();
642 EXPECT_LE(util1, 100);
643 EXPECT_GE(util1, 0);
644
645 // NB: expectation is that when we run this test, the device will be
646 // completed booted, will be on charger, and will not have the camera
647 // active.
648 EXPECT_FALSE(get_booting());
Andreas Gampe51389ce2018-03-13 20:55:56 -0700649#ifdef __ANDROID__
Than McIntosh8c7c7db2015-09-03 15:16:04 -0400650 EXPECT_TRUE(get_charging());
Andreas Gampe51389ce2018-03-13 20:55:56 -0700651#endif
Than McIntosh8c7c7db2015-09-03 15:16:04 -0400652 EXPECT_FALSE(get_camera_active());
653}
654
Andreas Gampe0c09e0e2018-03-13 16:04:01 -0700655namespace {
656
Andreas Gampe0c09e0e2018-03-13 16:04:01 -0700657template <typename Iterator>
658size_t CountEvents(const quipper::PerfDataProto& proto) {
659 size_t count = 0;
660 for (Iterator it(proto); it != it.end(); ++it) {
661 count++;
662 }
663 return count;
664}
665
666size_t CountCommEvents(const quipper::PerfDataProto& proto) {
667 return CountEvents<CommEventIterator>(proto);
668}
669size_t CountMmapEvents(const quipper::PerfDataProto& proto) {
670 return CountEvents<MmapEventIterator>(proto);
671}
672size_t CountSampleEvents(const quipper::PerfDataProto& proto) {
673 return CountEvents<SampleEventIterator>(proto);
674}
675size_t CountForkEvents(const quipper::PerfDataProto& proto) {
676 return CountEvents<ForkEventIterator>(proto);
677}
678size_t CountExitEvents(const quipper::PerfDataProto& proto) {
679 return CountEvents<ExitEventIterator>(proto);
680}
681
682std::string CreateStats(const quipper::PerfDataProto& proto) {
683 std::ostringstream oss;
684 oss << "Mmap events: " << CountMmapEvents(proto) << std::endl;
685 oss << "Sample events: " << CountSampleEvents(proto) << std::endl;
686 oss << "Comm events: " << CountCommEvents(proto) << std::endl;
687 oss << "Fork events: " << CountForkEvents(proto) << std::endl;
688 oss << "Exit events: " << CountExitEvents(proto) << std::endl;
689 return oss.str();
690}
691
692std::string FormatSampleEvent(const quipper::PerfDataProto_SampleEvent& sample) {
693 std::ostringstream oss;
694 if (sample.has_pid()) {
695 oss << "pid=" << sample.pid();
696 }
697 if (sample.has_tid()) {
698 oss << " tid=" << sample.tid();
699 }
700 if (sample.has_ip()) {
701 oss << " ip=" << sample.ip();
702 }
703 if (sample.has_addr()) {
704 oss << " addr=" << sample.addr();
705 }
706 if (sample.callchain_size() > 0) {
707 oss << " callchain=";
708 for (uint64_t cc : sample.callchain()) {
709 oss << "->" << cc;
710 }
711 }
712 return oss.str();
713}
714
715}
716
Andreas Gampe894b3f92018-03-22 19:48:48 -0700717struct BasicRunWithCannedPerf : PerfProfdTest {
718 void VerifyBasicCannedProfile(const android::perfprofd::PerfprofdRecord& encodedProfile) {
Andreas Gampe15236cf2018-05-23 10:51:46 -0700719 const quipper::PerfDataProto& perf_data = encodedProfile;
Andreas Gampe894b3f92018-03-22 19:48:48 -0700720
721 // Expect 21108 events.
722 EXPECT_EQ(21108, perf_data.events_size()) << CreateStats(perf_data);
723
724 EXPECT_EQ(48, CountMmapEvents(perf_data)) << CreateStats(perf_data);
725 EXPECT_EQ(19986, CountSampleEvents(perf_data)) << CreateStats(perf_data);
726 EXPECT_EQ(1033, CountCommEvents(perf_data)) << CreateStats(perf_data);
727 EXPECT_EQ(15, CountForkEvents(perf_data)) << CreateStats(perf_data);
728 EXPECT_EQ(26, CountExitEvents(perf_data)) << CreateStats(perf_data);
729
730 if (HasNonfatalFailure()) {
731 FAIL();
732 }
733
734 {
735 MmapEventIterator mmap(perf_data);
736 constexpr std::pair<const char*, uint64_t> kMmapEvents[] = {
737 std::make_pair("[kernel.kallsyms]_text", 0),
738 std::make_pair("/system/lib/libc.so", 3067412480u),
739 std::make_pair("/system/vendor/lib/libdsutils.so", 3069911040u),
740 std::make_pair("/system/lib/libc.so", 3067191296u),
741 std::make_pair("/system/lib/libc++.so", 3069210624u),
742 std::make_pair("/data/dalvik-cache/arm/system@framework@boot.oat", 1900048384u),
743 std::make_pair("/system/lib/libjavacore.so", 2957135872u),
744 std::make_pair("/system/vendor/lib/libqmi_encdec.so", 3006644224u),
745 std::make_pair("/data/dalvik-cache/arm/system@framework@wifi-service.jar@classes.dex",
746 3010351104u),
747 std::make_pair("/system/lib/libart.so", 3024150528u),
748 std::make_pair("/system/lib/libz.so", 3056410624u),
749 std::make_pair("/system/lib/libicui18n.so", 3057610752u),
750 };
751 for (auto& pair : kMmapEvents) {
752 EXPECT_STREQ(pair.first, mmap->mmap_event().filename().c_str());
753 EXPECT_EQ(pair.second, mmap->mmap_event().start()) << pair.first;
754 ++mmap;
755 }
756 }
757
758 {
759 CommEventIterator comm(perf_data);
760 constexpr const char* kCommEvents[] = {
761 "init", "kthreadd", "ksoftirqd/0", "kworker/u:0H", "migration/0", "khelper",
762 "netns", "modem_notifier", "smd_channel_clo", "smsm_cb_wq", "rpm-smd", "kworker/u:1H",
763 };
764 for (auto str : kCommEvents) {
765 EXPECT_STREQ(str, comm->comm_event().comm().c_str());
766 ++comm;
767 }
768 }
769
770 {
771 SampleEventIterator samples(perf_data);
772 constexpr const char* kSampleEvents[] = {
773 "pid=0 tid=0 ip=3222720196",
774 "pid=0 tid=0 ip=3222910876",
775 "pid=0 tid=0 ip=3222910876",
776 "pid=0 tid=0 ip=3222910876",
777 "pid=0 tid=0 ip=3222910876",
778 "pid=0 tid=0 ip=3222910876",
779 "pid=0 tid=0 ip=3222910876",
780 "pid=3 tid=3 ip=3231975108",
781 "pid=5926 tid=5926 ip=3231964952",
782 "pid=5926 tid=5926 ip=3225342428",
783 "pid=5926 tid=5926 ip=3223841448",
784 "pid=5926 tid=5926 ip=3069807920",
785 };
786 for (auto str : kSampleEvents) {
787 EXPECT_STREQ(str, FormatSampleEvent(samples->sample_event()).c_str());
788 ++samples;
789 }
790
791 // Skip some samples.
792 for (size_t i = 0; i != 5000; ++i) {
793 ++samples;
794 }
795 constexpr const char* kSampleEvents2[] = {
796 "pid=5938 tid=5938 ip=3069630992",
797 "pid=5938 tid=5938 ip=3069626616",
798 "pid=5938 tid=5938 ip=3069626636",
799 "pid=5938 tid=5938 ip=3069637212",
800 "pid=5938 tid=5938 ip=3069637208",
801 "pid=5938 tid=5938 ip=3069637252",
802 "pid=5938 tid=5938 ip=3069346040",
803 "pid=5938 tid=5938 ip=3069637128",
804 "pid=5938 tid=5938 ip=3069626616",
805 };
806 for (auto str : kSampleEvents2) {
807 EXPECT_STREQ(str, FormatSampleEvent(samples->sample_event()).c_str());
808 ++samples;
809 }
810
811 // Skip some samples.
812 for (size_t i = 0; i != 5000; ++i) {
813 ++samples;
814 }
815 constexpr const char* kSampleEvents3[] = {
816 "pid=5938 tid=5938 ip=3069912036",
817 "pid=5938 tid=5938 ip=3069637260",
818 "pid=5938 tid=5938 ip=3069631024",
819 "pid=5938 tid=5938 ip=3069346064",
820 "pid=5938 tid=5938 ip=3069637356",
821 "pid=5938 tid=5938 ip=3069637144",
822 "pid=5938 tid=5938 ip=3069912036",
823 "pid=5938 tid=5938 ip=3069912036",
824 "pid=5938 tid=5938 ip=3069631244",
825 };
826 for (auto str : kSampleEvents3) {
827 EXPECT_STREQ(str, FormatSampleEvent(samples->sample_event()).c_str());
828 ++samples;
829 }
830 }
831 }
832};
833
834TEST_F(BasicRunWithCannedPerf, Basic)
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500835{
836 //
837 // Verify the portion of the daemon that reads and encodes
838 // perf.data files. Here we run the encoder on a canned perf.data
839 // file and verify that the resulting protobuf contains what
840 // we think it should contain.
841 //
842 std::string input_perf_data(test_dir);
843 input_perf_data += "/canned.perf.data";
844
Than McIntosh8c7c7db2015-09-03 15:16:04 -0400845 // Set up config to avoid these annotations (they are tested elsewhere)
Andreas Gampee44ae142017-12-21 10:02:23 -0800846 ConfigReader config_reader;
847 config_reader.overrideUnsignedEntry("collect_cpu_utilization", 0);
848 config_reader.overrideUnsignedEntry("collect_charging_state", 0);
849 config_reader.overrideUnsignedEntry("collect_camera_active", 0);
Andreas Gampe894b3f92018-03-22 19:48:48 -0700850
851 // Disable compression.
852 config_reader.overrideUnsignedEntry("compress", 0);
853
Andreas Gampe517f4e92017-12-21 10:26:36 -0800854 PerfProfdRunner::LoggingConfig config;
Andreas Gampee44ae142017-12-21 10:02:23 -0800855 config_reader.FillConfig(&config);
Than McIntosh8c7c7db2015-09-03 15:16:04 -0400856
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500857 // Kick off encoder and check return code
858 PROFILE_RESULT result =
Andreas Gampef9a35612018-01-04 14:22:50 -0800859 encode_to_proto(input_perf_data, encoded_file_path(dest_dir, 0).c_str(), config, 0, nullptr);
Andreas Gampe54237f82018-01-18 21:20:36 -0800860 ASSERT_EQ(OK_PROFILE_COLLECTION, result) << test_logger.JoinTestLog(" ");
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500861
862 // Read and decode the resulting perf.data.encoded file
Andreas Gampe0c09e0e2018-03-13 16:04:01 -0700863 android::perfprofd::PerfprofdRecord encodedProfile;
Andreas Gampe894b3f92018-03-22 19:48:48 -0700864 readEncodedProfile(dest_dir, false, encodedProfile);
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500865
Andreas Gampe894b3f92018-03-22 19:48:48 -0700866 VerifyBasicCannedProfile(encodedProfile);
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500867}
868
Andreas Gampe894b3f92018-03-22 19:48:48 -0700869TEST_F(BasicRunWithCannedPerf, Compressed)
Andreas Gampef9a35612018-01-04 14:22:50 -0800870{
871 //
872 // Verify the portion of the daemon that reads and encodes
873 // perf.data files. Here we run the encoder on a canned perf.data
874 // file and verify that the resulting protobuf contains what
875 // we think it should contain.
876 //
877 std::string input_perf_data(test_dir);
878 input_perf_data += "/canned.perf.data";
879
880 // Set up config to avoid these annotations (they are tested elsewhere)
881 ConfigReader config_reader;
882 config_reader.overrideUnsignedEntry("collect_cpu_utilization", 0);
883 config_reader.overrideUnsignedEntry("collect_charging_state", 0);
884 config_reader.overrideUnsignedEntry("collect_camera_active", 0);
Andreas Gampe894b3f92018-03-22 19:48:48 -0700885
886 // Enable compression.
887 config_reader.overrideUnsignedEntry("compress", 1);
888
889 PerfProfdRunner::LoggingConfig config;
890 config_reader.FillConfig(&config);
891
892 // Kick off encoder and check return code
893 PROFILE_RESULT result =
894 encode_to_proto(input_perf_data, encoded_file_path(dest_dir, 0).c_str(), config, 0, nullptr);
895 ASSERT_EQ(OK_PROFILE_COLLECTION, result) << test_logger.JoinTestLog(" ");
896
897 // Read and decode the resulting perf.data.encoded file
898 android::perfprofd::PerfprofdRecord encodedProfile;
899 readEncodedProfile(dest_dir, true, encodedProfile);
900
901 VerifyBasicCannedProfile(encodedProfile);
902}
903
Andreas Gampecbc02bc2018-03-21 16:05:26 -0700904TEST_F(BasicRunWithCannedPerf, WithSymbolizer)
Andreas Gampe894b3f92018-03-22 19:48:48 -0700905{
906 //
907 // Verify the portion of the daemon that reads and encodes
908 // perf.data files. Here we run the encoder on a canned perf.data
909 // file and verify that the resulting protobuf contains what
910 // we think it should contain.
911 //
912 std::string input_perf_data(test_dir);
913 input_perf_data += "/canned.perf.data";
914
915 // Set up config to avoid these annotations (they are tested elsewhere)
916 ConfigReader config_reader;
917 config_reader.overrideUnsignedEntry("collect_cpu_utilization", 0);
918 config_reader.overrideUnsignedEntry("collect_charging_state", 0);
919 config_reader.overrideUnsignedEntry("collect_camera_active", 0);
920
921 // Disable compression.
922 config_reader.overrideUnsignedEntry("compress", 0);
923
Andreas Gampef9a35612018-01-04 14:22:50 -0800924 PerfProfdRunner::LoggingConfig config;
925 config_reader.FillConfig(&config);
926
927 // Kick off encoder and check return code
928 struct TestSymbolizer : public perfprofd::Symbolizer {
929 std::string Decode(const std::string& dso, uint64_t address) override {
930 return dso + "@" + std::to_string(address);
931 }
Andreas Gampecbc02bc2018-03-21 16:05:26 -0700932 bool GetMinExecutableVAddr(const std::string& dso, uint64_t* addr) override {
933 *addr = 4096;
934 return true;
935 }
Andreas Gampef9a35612018-01-04 14:22:50 -0800936 };
937 TestSymbolizer test_symbolizer;
938 PROFILE_RESULT result =
939 encode_to_proto(input_perf_data,
940 encoded_file_path(dest_dir, 0).c_str(),
941 config,
942 0,
943 &test_symbolizer);
Andreas Gampe577e6462018-01-10 20:02:20 -0800944 ASSERT_EQ(OK_PROFILE_COLLECTION, result);
Andreas Gampef9a35612018-01-04 14:22:50 -0800945
946 // Read and decode the resulting perf.data.encoded file
Andreas Gampe0c09e0e2018-03-13 16:04:01 -0700947 android::perfprofd::PerfprofdRecord encodedProfile;
Andreas Gampe894b3f92018-03-22 19:48:48 -0700948 readEncodedProfile(dest_dir, false, encodedProfile);
Andreas Gampef9a35612018-01-04 14:22:50 -0800949
Andreas Gampe894b3f92018-03-22 19:48:48 -0700950 VerifyBasicCannedProfile(encodedProfile);
Andreas Gampef9a35612018-01-04 14:22:50 -0800951
Andreas Gampe15236cf2018-05-23 10:51:46 -0700952 auto find_symbol = [&](const std::string& filename) -> const quipper::SymbolInfo* {
953 const size_t size = encodedProfile.ExtensionSize(quipper::symbol_info);
954 for (size_t i = 0; i != size; ++i) {
955 auto& symbol_info = encodedProfile.GetExtension(quipper::symbol_info, i);
Andreas Gampecbc02bc2018-03-21 16:05:26 -0700956 if (symbol_info.filename() == filename) {
957 return &symbol_info;
958 }
959 }
960 return nullptr;
961 };
962 auto all_filenames = [&]() {
963 std::ostringstream oss;
Andreas Gampe15236cf2018-05-23 10:51:46 -0700964 const size_t size = encodedProfile.ExtensionSize(quipper::symbol_info);
965 for (size_t i = 0; i != size; ++i) {
966 auto& symbol_info = encodedProfile.GetExtension(quipper::symbol_info, i);
Andreas Gampecbc02bc2018-03-21 16:05:26 -0700967 oss << " " << symbol_info.filename();
968 }
969 return oss.str();
970 };
971
972 EXPECT_TRUE(find_symbol("/data/app/com.google.android.apps.plus-1/lib/arm/libcronet.so")
973 != nullptr) << all_filenames() << test_logger.JoinTestLog("\n");
974 EXPECT_TRUE(find_symbol("/data/dalvik-cache/arm/system@framework@wifi-service.jar@classes.dex")
975 != nullptr) << all_filenames();
976 EXPECT_TRUE(find_symbol("/data/dalvik-cache/arm/data@app@com.google.android.gms-2@base.apk@"
977 "classes.dex")
978 != nullptr) << all_filenames();
979 EXPECT_TRUE(find_symbol("/data/dalvik-cache/arm/system@framework@boot.oat") != nullptr)
980 << all_filenames();
Andreas Gampef9a35612018-01-04 14:22:50 -0800981}
982
Than McIntoshe42c1f12016-06-01 12:21:42 -0400983TEST_F(PerfProfdTest, CallchainRunWithCannedPerf)
984{
985 // This test makes sure that the perf.data converter
986 // can handle call chains.
987 //
988 std::string input_perf_data(test_dir);
989 input_perf_data += "/callchain.canned.perf.data";
990
991 // Set up config to avoid these annotations (they are tested elsewhere)
Andreas Gampee44ae142017-12-21 10:02:23 -0800992 ConfigReader config_reader;
993 config_reader.overrideUnsignedEntry("collect_cpu_utilization", 0);
994 config_reader.overrideUnsignedEntry("collect_charging_state", 0);
995 config_reader.overrideUnsignedEntry("collect_camera_active", 0);
Andreas Gampe894b3f92018-03-22 19:48:48 -0700996
997 // Disable compression.
998 config_reader.overrideUnsignedEntry("compress", 0);
999
Andreas Gampe517f4e92017-12-21 10:26:36 -08001000 PerfProfdRunner::LoggingConfig config;
Andreas Gampee44ae142017-12-21 10:02:23 -08001001 config_reader.FillConfig(&config);
Than McIntoshe42c1f12016-06-01 12:21:42 -04001002
1003 // Kick off encoder and check return code
1004 PROFILE_RESULT result =
Andreas Gampef9a35612018-01-04 14:22:50 -08001005 encode_to_proto(input_perf_data, encoded_file_path(dest_dir, 0).c_str(), config, 0, nullptr);
Andreas Gampe577e6462018-01-10 20:02:20 -08001006 ASSERT_EQ(OK_PROFILE_COLLECTION, result);
Than McIntoshe42c1f12016-06-01 12:21:42 -04001007
1008 // Read and decode the resulting perf.data.encoded file
Andreas Gampe0c09e0e2018-03-13 16:04:01 -07001009 android::perfprofd::PerfprofdRecord encodedProfile;
Andreas Gampe894b3f92018-03-22 19:48:48 -07001010 readEncodedProfile(dest_dir, false, encodedProfile);
Than McIntoshe42c1f12016-06-01 12:21:42 -04001011
Andreas Gampe15236cf2018-05-23 10:51:46 -07001012 const quipper::PerfDataProto& perf_data = encodedProfile;
Than McIntoshe42c1f12016-06-01 12:21:42 -04001013
Andreas Gampe0c09e0e2018-03-13 16:04:01 -07001014 // Expect 21108 events.
1015 EXPECT_EQ(2224, perf_data.events_size()) << CreateStats(perf_data);
Than McIntoshe42c1f12016-06-01 12:21:42 -04001016
Andreas Gampe0c09e0e2018-03-13 16:04:01 -07001017 {
1018 SampleEventIterator samples(perf_data);
1019 constexpr const char* kSampleEvents[] = {
1020 "0: pid=6225 tid=6225 ip=18446743798834668032 callchain=->18446744073709551488->"
1021 "18446743798834668032->18446743798834782596->18446743798834784624->"
1022 "18446743798835055136->18446743798834788016->18446743798834789192->"
1023 "18446743798834789512->18446743798834790216->18446743798833756776",
1024 "1: pid=6225 tid=6225 ip=18446743798835685700 callchain=->18446744073709551488->"
1025 "18446743798835685700->18446743798835688704->18446743798835650964->"
1026 "18446743798834612104->18446743798834612276->18446743798835055528->"
1027 "18446743798834788016->18446743798834789192->18446743798834789512->"
1028 "18446743798834790216->18446743798833756776",
1029 "2: pid=6225 tid=6225 ip=18446743798835055804 callchain=->18446744073709551488->"
1030 "18446743798835055804->18446743798834788016->18446743798834789192->"
1031 "18446743798834789512->18446743798834790216->18446743798833756776",
1032 "3: pid=6225 tid=6225 ip=18446743798835991212 callchain=->18446744073709551488->"
1033 "18446743798835991212->18446743798834491060->18446743798834675572->"
1034 "18446743798834676516->18446743798834612172->18446743798834612276->"
1035 "18446743798835056664->18446743798834788016->18446743798834789192->"
1036 "18446743798834789512->18446743798834790216->18446743798833756776",
1037 "4: pid=6225 tid=6225 ip=18446743798844881108 callchain=->18446744073709551488->"
1038 "18446743798844881108->18446743798834836140->18446743798834846384->"
1039 "18446743798834491100->18446743798834675572->18446743798834676516->"
1040 "18446743798834612172->18446743798834612276->18446743798835056784->"
1041 "18446743798834788016->18446743798834789192->18446743798834789512->"
1042 "18446743798834790216->18446743798833756776",
1043 };
1044 size_t cmp_index = 0;
1045 for (size_t index = 0; samples != samples.end(); ++samples, ++index) {
1046 if (samples->sample_event().callchain_size() > 0) {
1047 std::ostringstream oss;
1048 oss << index << ": " << FormatSampleEvent(samples->sample_event());
1049 EXPECT_STREQ(kSampleEvents[cmp_index], oss.str().c_str());
1050 cmp_index++;
1051 if (cmp_index == arraysize(kSampleEvents)) {
1052 break;
1053 }
1054 }
1055 }
Than McIntoshe42c1f12016-06-01 12:21:42 -04001056 }
1057}
1058
Andreas Gampe51389ce2018-03-13 20:55:56 -07001059#ifdef __ANDROID__
1060
Than McIntosh7e2f4e92015-03-05 11:05:02 -05001061TEST_F(PerfProfdTest, BasicRunWithLivePerf)
1062{
1063 //
1064 // Basic test to exercise the main loop of the daemon. It includes
1065 // a live 'perf' run
1066 //
Andreas Gampe32695342018-01-03 22:28:18 -08001067 PerfProfdRunner runner(conf_dir);
Than McIntosh7e2f4e92015-03-05 11:05:02 -05001068 runner.addToConfig("only_debug_build=0");
1069 std::string ddparam("destination_directory="); ddparam += dest_dir;
1070 runner.addToConfig(ddparam);
Andreas Gampe32695342018-01-03 22:28:18 -08001071 std::string cfparam("config_directory="); cfparam += conf_dir;
Dehao Chen58bade32015-05-05 15:03:48 -07001072 runner.addToConfig(cfparam);
Than McIntosh7e2f4e92015-03-05 11:05:02 -05001073 runner.addToConfig("main_loop_iterations=1");
1074 runner.addToConfig("use_fixed_seed=12345678");
Than McIntoshf353d8b2015-05-21 14:44:34 -04001075 runner.addToConfig("max_unprocessed_profiles=100");
Than McIntosh7e2f4e92015-03-05 11:05:02 -05001076 runner.addToConfig("collection_interval=9999");
Dehao Chenf4605012015-05-07 13:16:35 -07001077 runner.addToConfig("sample_duration=2");
Andreas Gampee3033742018-01-18 21:19:06 -08001078 // Avoid the symbolizer for spurious messages.
1079 runner.addToConfig("use_elf_symbolizer=0");
Than McIntosh7e2f4e92015-03-05 11:05:02 -05001080
Andreas Gampe894b3f92018-03-22 19:48:48 -07001081 // Disable compression.
1082 runner.addToConfig("compress=0");
1083
Than McIntosh7e2f4e92015-03-05 11:05:02 -05001084 // Create semaphore file
1085 runner.create_semaphore_file();
1086
1087 // Kick off daemon
1088 int daemon_main_return_code = runner.invoke();
1089
1090 // Check return code from daemon
Andreas Gampe577e6462018-01-10 20:02:20 -08001091 ASSERT_EQ(0, daemon_main_return_code);
Than McIntosh7e2f4e92015-03-05 11:05:02 -05001092
1093 // Read and decode the resulting perf.data.encoded file
Andreas Gampe0c09e0e2018-03-13 16:04:01 -07001094 android::perfprofd::PerfprofdRecord encodedProfile;
Andreas Gampe894b3f92018-03-22 19:48:48 -07001095 readEncodedProfile(dest_dir, false, encodedProfile);
Than McIntosh7e2f4e92015-03-05 11:05:02 -05001096
1097 // Examine what we get back. Since it's a live profile, we can't
1098 // really do much in terms of verifying the contents.
Andreas Gampe15236cf2018-05-23 10:51:46 -07001099 EXPECT_LT(0, encodedProfile.events_size());
Than McIntosh7e2f4e92015-03-05 11:05:02 -05001100
1101 // Verify log contents
Andreas Gampe32695342018-01-03 22:28:18 -08001102 const std::string expected = std::string(
1103 "I: starting Android Wide Profiling daemon ") +
1104 "I: config file path set to " + conf_dir + "/perfprofd.conf " +
1105 RAW_RESULT(
Than McIntosh7e2f4e92015-03-05 11:05:02 -05001106 I: random seed set to 12345678
1107 I: sleep 674 seconds
1108 I: initiating profile collection
Andreas Gampe44e63a72018-01-03 12:39:53 -08001109 I: sleep 2 seconds
Than McIntosh7e2f4e92015-03-05 11:05:02 -05001110 I: profile collection complete
1111 I: sleep 9325 seconds
1112 I: finishing Android Wide Profiling daemon
1113 );
1114 // check to make sure log excerpt matches
Andreas Gamped0525702018-06-12 09:56:11 -07001115 EXPECT_TRUE(CompareLogMessages(expandVars(expected), true));
Than McIntosh7e2f4e92015-03-05 11:05:02 -05001116}
1117
Dehao Chenf4605012015-05-07 13:16:35 -07001118TEST_F(PerfProfdTest, MultipleRunWithLivePerf)
1119{
1120 //
1121 // Basic test to exercise the main loop of the daemon. It includes
1122 // a live 'perf' run
1123 //
Andreas Gampe32695342018-01-03 22:28:18 -08001124 PerfProfdRunner runner(conf_dir);
Dehao Chenf4605012015-05-07 13:16:35 -07001125 runner.addToConfig("only_debug_build=0");
1126 std::string ddparam("destination_directory="); ddparam += dest_dir;
1127 runner.addToConfig(ddparam);
Andreas Gampe32695342018-01-03 22:28:18 -08001128 std::string cfparam("config_directory="); cfparam += conf_dir;
Dehao Chenf4605012015-05-07 13:16:35 -07001129 runner.addToConfig(cfparam);
1130 runner.addToConfig("main_loop_iterations=3");
1131 runner.addToConfig("use_fixed_seed=12345678");
1132 runner.addToConfig("collection_interval=9999");
1133 runner.addToConfig("sample_duration=2");
Andreas Gampee3033742018-01-18 21:19:06 -08001134 // Avoid the symbolizer for spurious messages.
1135 runner.addToConfig("use_elf_symbolizer=0");
Andreas Gampe894b3f92018-03-22 19:48:48 -07001136
1137 // Disable compression.
1138 runner.addToConfig("compress=0");
1139
Dehao Chenf4605012015-05-07 13:16:35 -07001140 runner.write_processed_file(1, 2);
1141
1142 // Create semaphore file
1143 runner.create_semaphore_file();
1144
1145 // Kick off daemon
1146 int daemon_main_return_code = runner.invoke();
1147
1148 // Check return code from daemon
Andreas Gampe577e6462018-01-10 20:02:20 -08001149 ASSERT_EQ(0, daemon_main_return_code);
Dehao Chenf4605012015-05-07 13:16:35 -07001150
1151 // Read and decode the resulting perf.data.encoded file
Andreas Gampe0c09e0e2018-03-13 16:04:01 -07001152 android::perfprofd::PerfprofdRecord encodedProfile;
Andreas Gampe894b3f92018-03-22 19:48:48 -07001153 readEncodedProfile(dest_dir, false, encodedProfile);
Dehao Chenf4605012015-05-07 13:16:35 -07001154
1155 // Examine what we get back. Since it's a live profile, we can't
1156 // really do much in terms of verifying the contents.
Andreas Gampe15236cf2018-05-23 10:51:46 -07001157 EXPECT_LT(0, encodedProfile.events_size());
Dehao Chenf4605012015-05-07 13:16:35 -07001158
1159 // Examine that encoded.1 file is removed while encoded.{0|2} exists.
Andreas Gampe32695342018-01-03 22:28:18 -08001160 EXPECT_EQ(0, access(encoded_file_path(dest_dir, 0).c_str(), F_OK));
1161 EXPECT_NE(0, access(encoded_file_path(dest_dir, 1).c_str(), F_OK));
1162 EXPECT_EQ(0, access(encoded_file_path(dest_dir, 2).c_str(), F_OK));
Dehao Chenf4605012015-05-07 13:16:35 -07001163
1164 // Verify log contents
Andreas Gampe32695342018-01-03 22:28:18 -08001165 const std::string expected = std::string(
1166 "I: starting Android Wide Profiling daemon ") +
1167 "I: config file path set to " + conf_dir + "/perfprofd.conf " +
1168 RAW_RESULT(
Dehao Chenf4605012015-05-07 13:16:35 -07001169 I: random seed set to 12345678
1170 I: sleep 674 seconds
1171 I: initiating profile collection
Andreas Gampe44e63a72018-01-03 12:39:53 -08001172 I: sleep 2 seconds
Dehao Chenf4605012015-05-07 13:16:35 -07001173 I: profile collection complete
1174 I: sleep 9325 seconds
1175 I: sleep 4974 seconds
1176 I: initiating profile collection
Andreas Gampe44e63a72018-01-03 12:39:53 -08001177 I: sleep 2 seconds
Dehao Chenf4605012015-05-07 13:16:35 -07001178 I: profile collection complete
1179 I: sleep 5025 seconds
1180 I: sleep 501 seconds
1181 I: initiating profile collection
Andreas Gampe44e63a72018-01-03 12:39:53 -08001182 I: sleep 2 seconds
Dehao Chenf4605012015-05-07 13:16:35 -07001183 I: profile collection complete
1184 I: sleep 9498 seconds
1185 I: finishing Android Wide Profiling daemon
1186 );
1187 // check to make sure log excerpt matches
Andreas Gamped0525702018-06-12 09:56:11 -07001188 EXPECT_TRUE(CompareLogMessages(expandVars(expected), true));
Dehao Chenf4605012015-05-07 13:16:35 -07001189}
1190
Than McIntoshbe1b1772016-05-23 11:07:08 -04001191TEST_F(PerfProfdTest, CallChainRunWithLivePerf)
1192{
1193 //
Than McIntoshbe1b1772016-05-23 11:07:08 -04001194 // Collect a callchain profile, so as to exercise the code in
1195 // perf_data post-processing that digests callchains.
1196 //
Andreas Gampe32695342018-01-03 22:28:18 -08001197 PerfProfdRunner runner(conf_dir);
Than McIntoshbe1b1772016-05-23 11:07:08 -04001198 std::string ddparam("destination_directory="); ddparam += dest_dir;
1199 runner.addToConfig(ddparam);
Andreas Gampe32695342018-01-03 22:28:18 -08001200 std::string cfparam("config_directory="); cfparam += conf_dir;
Than McIntoshbe1b1772016-05-23 11:07:08 -04001201 runner.addToConfig(cfparam);
1202 runner.addToConfig("main_loop_iterations=1");
1203 runner.addToConfig("use_fixed_seed=12345678");
1204 runner.addToConfig("max_unprocessed_profiles=100");
1205 runner.addToConfig("collection_interval=9999");
1206 runner.addToConfig("stack_profile=1");
1207 runner.addToConfig("sample_duration=2");
Andreas Gampee3033742018-01-18 21:19:06 -08001208 // Avoid the symbolizer for spurious messages.
1209 runner.addToConfig("use_elf_symbolizer=0");
Than McIntoshbe1b1772016-05-23 11:07:08 -04001210
Andreas Gampe894b3f92018-03-22 19:48:48 -07001211 // Disable compression.
1212 runner.addToConfig("compress=0");
1213
Than McIntoshbe1b1772016-05-23 11:07:08 -04001214 // Create semaphore file
1215 runner.create_semaphore_file();
1216
1217 // Kick off daemon
1218 int daemon_main_return_code = runner.invoke();
1219
1220 // Check return code from daemon
Andreas Gampe577e6462018-01-10 20:02:20 -08001221 ASSERT_EQ(0, daemon_main_return_code);
Than McIntoshbe1b1772016-05-23 11:07:08 -04001222
1223 // Read and decode the resulting perf.data.encoded file
Andreas Gampe0c09e0e2018-03-13 16:04:01 -07001224 android::perfprofd::PerfprofdRecord encodedProfile;
Andreas Gampe894b3f92018-03-22 19:48:48 -07001225 readEncodedProfile(dest_dir, false, encodedProfile);
Than McIntoshbe1b1772016-05-23 11:07:08 -04001226
1227 // Examine what we get back. Since it's a live profile, we can't
1228 // really do much in terms of verifying the contents.
Andreas Gampe15236cf2018-05-23 10:51:46 -07001229 EXPECT_LT(0, encodedProfile.events_size());
Than McIntoshbe1b1772016-05-23 11:07:08 -04001230
1231 // Verify log contents
Andreas Gampe32695342018-01-03 22:28:18 -08001232 const std::string expected = std::string(
1233 "I: starting Android Wide Profiling daemon ") +
1234 "I: config file path set to " + conf_dir + "/perfprofd.conf " +
1235 RAW_RESULT(
Than McIntoshbe1b1772016-05-23 11:07:08 -04001236 I: random seed set to 12345678
1237 I: sleep 674 seconds
1238 I: initiating profile collection
Andreas Gampe44e63a72018-01-03 12:39:53 -08001239 I: sleep 2 seconds
Than McIntoshbe1b1772016-05-23 11:07:08 -04001240 I: profile collection complete
1241 I: sleep 9325 seconds
1242 I: finishing Android Wide Profiling daemon
1243 );
1244 // check to make sure log excerpt matches
Andreas Gamped0525702018-06-12 09:56:11 -07001245 EXPECT_TRUE(CompareLogMessages(expandVars(expected), true));
Andreas Gampe0c09e0e2018-03-13 16:04:01 -07001246
1247 // Check that we have at least one SampleEvent with a callchain.
Andreas Gampe15236cf2018-05-23 10:51:46 -07001248 SampleEventIterator samples(encodedProfile);
Andreas Gampe0c09e0e2018-03-13 16:04:01 -07001249 bool found_callchain = false;
1250 while (!found_callchain && samples != samples.end()) {
1251 found_callchain = samples->sample_event().callchain_size() > 0;
1252 }
Andreas Gampe15236cf2018-05-23 10:51:46 -07001253 EXPECT_TRUE(found_callchain) << CreateStats(encodedProfile);
Than McIntoshbe1b1772016-05-23 11:07:08 -04001254}
1255
Andreas Gampe51389ce2018-03-13 20:55:56 -07001256#endif
1257
Andreas Gampecbc02bc2018-03-21 16:05:26 -07001258class RangeMapTest : public testing::Test {
1259};
1260
1261TEST_F(RangeMapTest, TestRangeMap) {
1262 using namespace android::perfprofd;
1263
1264 RangeMap<std::string, uint64_t> map;
1265 auto print = [&]() {
1266 std::ostringstream oss;
1267 for (auto& aggr_sym : map) {
1268 oss << aggr_sym.first << "#" << aggr_sym.second.symbol;
1269 oss << "[";
1270 for (auto& x : aggr_sym.second.offsets) {
1271 oss << x << ",";
1272 }
1273 oss << "]";
1274 }
1275 return oss.str();
1276 };
1277
1278 EXPECT_STREQ("", print().c_str());
1279
1280 map.Insert("a", 10);
1281 EXPECT_STREQ("10#a[10,]", print().c_str());
1282 map.Insert("a", 100);
1283 EXPECT_STREQ("10#a[10,100,]", print().c_str());
1284 map.Insert("a", 1);
1285 EXPECT_STREQ("1#a[1,10,100,]", print().c_str());
1286 map.Insert("a", 1);
1287 EXPECT_STREQ("1#a[1,10,100,]", print().c_str());
1288 map.Insert("a", 2);
1289 EXPECT_STREQ("1#a[1,2,10,100,]", print().c_str());
1290
1291 map.Insert("b", 200);
1292 EXPECT_STREQ("1#a[1,2,10,100,]200#b[200,]", print().c_str());
1293 map.Insert("b", 199);
1294 EXPECT_STREQ("1#a[1,2,10,100,]199#b[199,200,]", print().c_str());
1295
1296 map.Insert("c", 50);
1297 EXPECT_STREQ("1#a[1,2,10,]50#c[50,]100#a[100,]199#b[199,200,]", print().c_str());
1298}
1299
Andreas Gampeb019ddc2018-04-02 10:58:32 -07001300class ThreadedHandlerTest : public PerfProfdTest {
1301 public:
1302 void SetUp() override {
1303 PerfProfdTest::SetUp();
1304 threaded_handler_.reset(new android::perfprofd::ThreadedHandler());
1305 }
1306
1307 void TearDown() override {
1308 threaded_handler_.reset();
1309 PerfProfdTest::TearDown();
1310 }
1311
1312 protected:
1313 std::unique_ptr<android::perfprofd::ThreadedHandler> threaded_handler_;
1314};
1315
1316TEST_F(ThreadedHandlerTest, Basic) {
1317 std::string error_msg;
1318 EXPECT_FALSE(threaded_handler_->StopProfiling(&error_msg));
1319}
1320
1321#ifdef __ANDROID__
1322#define ThreadedHandlerTestName(x) x
1323#else
1324#define ThreadedHandlerTestName(x) DISABLED_ ## x
1325#endif
1326
1327TEST_F(ThreadedHandlerTest, ThreadedHandlerTestName(Live)) {
1328 auto config_fn = [](android::perfprofd::ThreadedConfig& config) {
1329 // Use some values that make it likely that things don't fail quickly.
1330 config.main_loop_iterations = 0;
1331 config.collection_interval_in_s = 1000000;
1332 };
1333 std::string error_msg;
1334 ASSERT_TRUE(threaded_handler_->StartProfiling(config_fn, &error_msg)) << error_msg;
1335 EXPECT_TRUE(threaded_handler_->StopProfiling(&error_msg)) << error_msg;
1336}
1337
Than McIntosh7e2f4e92015-03-05 11:05:02 -05001338int main(int argc, char **argv) {
Andreas Gampe32695342018-01-03 22:28:18 -08001339 // Always log to cerr, so that device failures are visible.
1340 android::base::SetLogger(android::base::StderrLogger);
1341
1342 CHECK(android::base::Realpath(argv[0], &gExecutableRealpath));
1343
Than McIntosh7e2f4e92015-03-05 11:05:02 -05001344 // switch to / before starting testing (perfprofd
1345 // should be location-independent)
1346 chdir("/");
1347 testing::InitGoogleTest(&argc, argv);
1348 return RUN_ALL_TESTS();
1349}