2 * Copyright (C) 2015 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
29 #include <sys/types.h>
32 #include <android-base/file.h>
33 #include <android-base/logging.h>
34 #include <android-base/macros.h>
35 #include <android-base/stringprintf.h>
36 #include <android-base/strings.h>
37 #include <android-base/test_utils.h>
38 #include <android-base/thread_annotations.h>
39 #include <gtest/gtest.h>
43 #include "configreader.h"
44 #include "map_utils.h"
45 #include "perfprofdcore.h"
46 #include "quipper_helper.h"
47 #include "symbolizer.h"
49 #include "perfprofd_record.pb.h"
51 using namespace android::perfprofd::quipper;
53 static_assert(android::base::kEnableDChecks, "Expected DCHECKs to be enabled");
56 // Set to argv[0] on startup
58 static std::string gExecutableRealpath;
62 using android::base::LogId;
63 using android::base::LogSeverity;
68 using namespace std::placeholders;
69 android::base::SetLogger(
70 std::bind(&TestLogHelper::TestLogFunction, this, _1, _2, _3, _4, _5, _6));
73 std::string JoinTestLog(const char* delimiter) {
74 std::unique_lock<std::mutex> ul(lock_);
75 return android::base::Join(test_log_messages_, delimiter);
77 template <typename Predicate>
78 std::string JoinTestLog(const char* delimiter, Predicate pred) {
79 std::unique_lock<std::mutex> ul(lock_);
80 std::vector<std::string> tmp;
81 std::copy_if(test_log_messages_.begin(),
82 test_log_messages_.end(),
83 std::back_inserter(tmp),
85 return android::base::Join(tmp, delimiter);
89 void TestLogFunction(LogId log_id,
94 const char* message) {
95 std::unique_lock<std::mutex> ul(lock_);
96 constexpr char log_characters[] = "VDIWEFF";
97 char severity_char = log_characters[severity];
98 test_log_messages_.push_back(android::base::StringPrintf("%c: %s", severity_char, message));
100 if (severity >= LogSeverity::FATAL_WITHOUT_ABORT) {
101 android::base::StderrLogger(log_id, severity, tag, file, line, message);
108 std::vector<std::string> test_log_messages_;
113 // Path to perf executable on device
114 #define PERFPATH "/system/bin/perf"
116 // Temporary config file that we will emit for the daemon to read
117 #define CONFIGFILE "perfprofd.conf"
119 static bool bothWhiteSpace(char lhs, char rhs)
121 return (std::isspace(lhs) && std::isspace(rhs));
125 // Squeeze out repeated whitespace from expected/actual logs.
127 static std::string squeezeWhite(const std::string &str,
131 if (dump) { fprintf(stderr, "raw %s is %s\n", tag, str.c_str()); }
132 std::string result(str);
133 std::replace(result.begin(), result.end(), '\n', ' ');
134 auto new_end = std::unique(result.begin(), result.end(), bothWhiteSpace);
135 result.erase(new_end, result.end());
136 while (result.begin() != result.end() && std::isspace(*result.rbegin())) {
139 if (dump) { fprintf(stderr, "squeezed %s is %s\n", tag, result.c_str()); }
144 // Replace all occurrences of a string with another string.
146 static std::string replaceAll(const std::string &str,
147 const std::string &from,
148 const std::string &to)
150 std::string ret = "";
152 while (pos < str.size()) {
153 size_t found = str.find(from, pos);
154 if (found == std::string::npos) {
155 ret += str.substr(pos);
158 ret += str.substr(pos, found - pos) + to;
159 pos = found + from.size();
165 // Replace occurrences of special variables in the string.
168 static std::string expandVars(const std::string &str) {
170 return replaceAll(str, "$NATIVE_TESTS", "/data/nativetest64");
172 return replaceAll(str, "$NATIVE_TESTS", "/data/nativetest");
177 class PerfProfdTest : public testing::Test {
179 virtual void SetUp() {
180 test_logger.Install();
184 virtual void TearDown() {
185 android::base::SetLogger(android::base::StderrLogger);
187 // TODO: proper management of test files. For now, use old system() code.
188 for (const auto dir : { &dest_dir, &conf_dir }) {
189 std::string cmd("rm -rf ");
191 int ret = system(cmd.c_str());
198 // Check to see if the log messages emitted by the daemon
199 // match the expected result. By default we use a partial
200 // match, e.g. if we see the expected excerpt anywhere in the
201 // result, it's a match (for exact match, set exact to true)
203 void CompareLogMessages(const std::string& expected,
204 const char* testpoint,
205 bool exactMatch = false) {
206 std::string sqexp = squeezeWhite(expected, "expected");
208 // Strip out JIT errors.
209 std::regex jit_regex("E: Failed to open ELF file: [^ ]*ashmem/dalvik-jit-code-cache.*");
210 auto strip_jit = [&](const std::string& str) {
211 std::smatch jit_match;
212 return !std::regex_match(str, jit_match, jit_regex);
214 std::string sqact = squeezeWhite(test_logger.JoinTestLog(" ", strip_jit), "actual");
217 EXPECT_STREQ(sqexp.c_str(), sqact.c_str());
219 std::size_t foundpos = sqact.find(sqexp);
220 bool wasFound = true;
221 if (foundpos == std::string::npos) {
222 std::cerr << testpoint << ": expected result not found\n";
223 std::cerr << " Actual: \"" << sqact << "\"\n";
224 std::cerr << " Expected: \"" << sqexp << "\"\n";
227 EXPECT_TRUE(wasFound);
231 // test_dir is the directory containing the test executable and
232 // any files associated with the test (will be created by the harness).
233 std::string test_dir;
235 // dest_dir is a temporary directory that we're using as the destination directory.
236 // It is backed by temp_dir1.
237 std::string dest_dir;
239 // conf_dir is a temporary directory that we're using as the configuration directory.
240 // It is backed by temp_dir2.
241 std::string conf_dir;
243 TestLogHelper test_logger;
247 temp_dir1.reset(new TemporaryDir());
248 temp_dir2.reset(new TemporaryDir());
249 dest_dir = temp_dir1->path;
250 conf_dir = temp_dir2->path;
251 test_dir = android::base::Dirname(gExecutableRealpath);
254 std::unique_ptr<TemporaryDir> temp_dir1;
255 std::unique_ptr<TemporaryDir> temp_dir2;
259 /// Helper class to kick off a run of the perfprofd daemon with a specific
262 class PerfProfdRunner {
264 explicit PerfProfdRunner(const std::string& config_dir)
265 : config_dir_(config_dir)
267 config_path_ = config_dir + "/" CONFIGFILE;
272 remove_processed_file();
275 void addToConfig(const std::string &line)
277 config_text_ += line;
278 config_text_ += "\n";
281 void remove_semaphore_file()
283 std::string semaphore(config_dir_);
284 semaphore += "/" SEMAPHORE_FILENAME;
285 unlink(semaphore.c_str());
288 void create_semaphore_file()
290 std::string semaphore(config_dir_);
291 semaphore += "/" SEMAPHORE_FILENAME;
292 close(open(semaphore.c_str(), O_WRONLY|O_CREAT, 0600));
295 void write_processed_file(int start_seq, int end_seq)
297 std::string processed = config_dir_ + "/" PROCESSED_FILENAME;
298 FILE *fp = fopen(processed.c_str(), "w");
299 for (int i = start_seq; i < end_seq; i++) {
300 fprintf(fp, "%d\n", i);
305 void remove_processed_file()
307 std::string processed = config_dir_ + "/" PROCESSED_FILENAME;
308 unlink(processed.c_str());
311 struct LoggingConfig : public Config {
312 void Sleep(size_t seconds) override {
313 // Log sleep calls but don't sleep.
314 LOG(INFO) << "sleep " << seconds << " seconds";
317 bool IsProfilingEnabled() const override {
319 // Check for existence of semaphore file in config directory
321 if (access(config_directory.c_str(), F_OK) == -1) {
322 PLOG(WARNING) << "unable to open config directory " << config_directory;
326 // Check for existence of semaphore file
327 std::string semaphore_filepath = config_directory
328 + "/" + SEMAPHORE_FILENAME;
329 if (access(semaphore_filepath.c_str(), F_OK) == -1) {
339 static const char *argv[3] = { "perfprofd", "-c", "" };
340 argv[2] = config_path_.c_str();
342 writeConfigFile(config_path_, config_text_);
344 // execute daemon main
345 LoggingConfig config;
346 return perfprofd_main(3, (char **) argv, &config);
350 std::string config_dir_;
351 std::string config_path_;
352 std::string config_text_;
354 void writeConfigFile(const std::string &config_path,
355 const std::string &config_text)
357 FILE *fp = fopen(config_path.c_str(), "w");
358 ASSERT_TRUE(fp != nullptr);
359 fprintf(fp, "%s\n", config_text.c_str());
364 //......................................................................
366 static std::string encoded_file_path(const std::string& dest_dir,
368 return android::base::StringPrintf("%s/perf.data.encoded.%d",
369 dest_dir.c_str(), seq);
372 static void readEncodedProfile(const std::string& dest_dir,
374 android::perfprofd::PerfprofdRecord& encodedProfile)
377 int perf_data_stat_result = stat(encoded_file_path(dest_dir, 0).c_str(), &statb);
378 ASSERT_NE(-1, perf_data_stat_result);
382 encoded.resize(statb.st_size);
383 FILE *ifp = fopen(encoded_file_path(dest_dir, 0).c_str(), "r");
384 ASSERT_NE(nullptr, ifp);
385 size_t items_read = fread((void*) encoded.data(), statb.st_size, 1, ifp);
386 ASSERT_EQ(1, items_read);
390 if (compressed && !encoded.empty()) {
392 stream.zalloc = Z_NULL;
393 stream.zfree = Z_NULL;
394 stream.opaque = Z_NULL;
397 constexpr int kWindowBits = 15;
398 constexpr int kGzipEncoding = 16;
399 int init_result = inflateInit2(&stream, kWindowBits | kGzipEncoding);
400 if (init_result != Z_OK) {
401 LOG(ERROR) << "Could not initialize libz stream " << init_result;
407 buf.reserve(2 * encoded.size());
408 stream.avail_in = encoded.size();
409 stream.next_in = reinterpret_cast<Bytef*>(const_cast<char*>(encoded.data()));
414 stream.next_out = static_cast<Bytef*>(chunk);
415 stream.avail_out = arraysize(chunk);
417 result = inflate(&stream, 0);
418 const size_t amount = arraysize(chunk) - stream.avail_out;
420 if (buf.capacity() - buf.size() < amount) {
421 buf.reserve(buf.capacity() + 64u * 1024u);
422 CHECK_LE(amount, buf.capacity() - buf.size());
424 size_t index = buf.size();
425 buf.resize(buf.size() + amount);
426 memcpy(reinterpret_cast<uint8_t*>(const_cast<char*>(buf.data())) + index, chunk, amount);
428 } while (result == Z_OK);
430 if (result != Z_STREAM_END) {
431 LOG(ERROR) << "Finished with not-Z_STREAM_END " << result;
438 encodedProfile.ParseFromString(encoded);
441 #define RAW_RESULT(x) #x
443 TEST_F(PerfProfdTest, TestUtil)
445 EXPECT_EQ("", replaceAll("", "", ""));
446 EXPECT_EQ("zzbc", replaceAll("abc", "a", "zz"));
447 EXPECT_EQ("azzc", replaceAll("abc", "b", "zz"));
448 EXPECT_EQ("abzz", replaceAll("abc", "c", "zz"));
449 EXPECT_EQ("xxyyzz", replaceAll("abc", "abc", "xxyyzz"));
452 TEST_F(PerfProfdTest, MissingGMS)
455 // AWP requires cooperation between the daemon and the GMS core
456 // piece. If we're running on a device that has an old or damaged
457 // version of GMS core, then the config directory we're interested in
458 // may not be there. This test insures that the daemon does the
459 // right thing in this case.
461 PerfProfdRunner runner(conf_dir);
462 runner.addToConfig("only_debug_build=0");
463 runner.addToConfig("trace_config_read=0");
464 runner.addToConfig("config_directory=/does/not/exist");
465 runner.addToConfig("main_loop_iterations=1");
466 runner.addToConfig("use_fixed_seed=1");
467 runner.addToConfig("collection_interval=100");
470 int daemon_main_return_code = runner.invoke();
472 // Check return code from daemon
473 EXPECT_EQ(0, daemon_main_return_code);
475 // Verify log contents
476 const std::string expected = RAW_RESULT(
478 W: unable to open config directory /does/not/exist: No such file or directory
479 I: profile collection skipped (missing config directory)
482 // check to make sure entire log matches
483 CompareLogMessages(expected, "MissingGMS");
487 TEST_F(PerfProfdTest, MissingOptInSemaphoreFile)
490 // Android device owners must opt in to "collect and report usage
491 // data" in order for us to be able to collect profiles. The opt-in
492 // check is performed in the GMS core component; if the check
493 // passes, then it creates a semaphore file for the daemon to pick
496 PerfProfdRunner runner(conf_dir);
497 runner.addToConfig("only_debug_build=0");
498 std::string cfparam("config_directory="); cfparam += conf_dir;
499 runner.addToConfig(cfparam);
500 std::string ddparam("destination_directory="); ddparam += dest_dir;
501 runner.addToConfig(ddparam);
502 runner.addToConfig("main_loop_iterations=1");
503 runner.addToConfig("use_fixed_seed=1");
504 runner.addToConfig("collection_interval=100");
506 runner.remove_semaphore_file();
509 int daemon_main_return_code = runner.invoke();
511 // Check return code from daemon
512 EXPECT_EQ(0, daemon_main_return_code);
514 // Verify log contents
515 const std::string expected = RAW_RESULT(
516 I: profile collection skipped (missing config directory)
518 // check to make sure log excerpt matches
519 CompareLogMessages(expected, "MissingOptInSemaphoreFile");
522 TEST_F(PerfProfdTest, MissingPerfExecutable)
525 // Perfprofd uses the 'simpleperf' tool to collect profiles
526 // (although this may conceivably change in the future). This test
527 // checks to make sure that if 'simpleperf' is not present we bail out
528 // from collecting profiles.
530 PerfProfdRunner runner(conf_dir);
531 runner.addToConfig("only_debug_build=0");
532 runner.addToConfig("trace_config_read=1");
533 std::string cfparam("config_directory="); cfparam += conf_dir;
534 runner.addToConfig(cfparam);
535 std::string ddparam("destination_directory="); ddparam += dest_dir;
536 runner.addToConfig(ddparam);
537 runner.addToConfig("main_loop_iterations=1");
538 runner.addToConfig("use_fixed_seed=1");
539 runner.addToConfig("collection_interval=100");
540 runner.addToConfig("perf_path=/does/not/exist");
542 // Create semaphore file
543 runner.create_semaphore_file();
546 int daemon_main_return_code = runner.invoke();
548 // Check return code from daemon
549 EXPECT_EQ(0, daemon_main_return_code);
551 // expected log contents
552 const std::string expected = RAW_RESULT(
553 I: profile collection skipped (missing 'perf' executable)
555 // check to make sure log excerpt matches
556 CompareLogMessages(expected, "MissingPerfExecutable");
559 TEST_F(PerfProfdTest, BadPerfRun)
562 // Perf tools tend to be tightly coupled with a specific kernel
563 // version -- if things are out of sync perf could fail or
564 // crash. This test makes sure that we detect such a case and log
567 PerfProfdRunner runner(conf_dir);
568 runner.addToConfig("only_debug_build=0");
569 std::string cfparam("config_directory="); cfparam += conf_dir;
570 runner.addToConfig(cfparam);
571 std::string ddparam("destination_directory="); ddparam += dest_dir;
572 runner.addToConfig(ddparam);
573 runner.addToConfig("main_loop_iterations=1");
574 runner.addToConfig("use_fixed_seed=1");
575 runner.addToConfig("collection_interval=100");
577 runner.addToConfig("perf_path=/system/bin/false");
579 runner.addToConfig("perf_path=/bin/false");
582 // Create semaphore file
583 runner.create_semaphore_file();
586 int daemon_main_return_code = runner.invoke();
588 // Check return code from daemon
589 EXPECT_EQ(0, daemon_main_return_code);
591 // Verify log contents
592 const std::string expected = RAW_RESULT(
593 W: perf bad exit status 1
594 W: profile collection failed
597 // check to make sure log excerpt matches
598 CompareLogMessages(expected, "BadPerfRun");
601 TEST_F(PerfProfdTest, ConfigFileParsing)
604 // Gracefully handly malformed items in the config file
606 PerfProfdRunner runner(conf_dir);
607 runner.addToConfig("only_debug_build=0");
608 runner.addToConfig("main_loop_iterations=1");
609 runner.addToConfig("collection_interval=100");
610 runner.addToConfig("use_fixed_seed=1");
611 runner.addToConfig("destination_directory=/does/not/exist");
613 // assorted bad syntax
614 runner.addToConfig("collection_interval=0");
615 runner.addToConfig("collection_interval=-1");
616 runner.addToConfig("collection_interval=2");
617 runner.addToConfig("nonexistent_key=something");
618 runner.addToConfig("no_equals_stmt");
621 int daemon_main_return_code = runner.invoke();
623 // Check return code from daemon
624 EXPECT_EQ(0, daemon_main_return_code);
626 // Verify log contents
627 const std::string expected = RAW_RESULT(
628 W: line 6: specified value 0 for 'collection_interval' outside permitted range [100 4294967295] (ignored)
629 W: line 7: malformed unsigned value (ignored)
630 W: line 8: specified value 2 for 'collection_interval' outside permitted range [100 4294967295] (ignored)
631 W: line 9: unknown option 'nonexistent_key' ignored
632 W: line 10: line malformed (no '=' found)
635 // check to make sure log excerpt matches
636 CompareLogMessages(expected, "ConfigFileParsing");
639 TEST_F(PerfProfdTest, ProfileCollectionAnnotations)
641 unsigned util1 = collect_cpu_utilization();
642 EXPECT_LE(util1, 100);
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
648 EXPECT_FALSE(get_booting());
650 EXPECT_TRUE(get_charging());
652 EXPECT_FALSE(get_camera_active());
657 template <typename Iterator>
658 size_t CountEvents(const quipper::PerfDataProto& proto) {
660 for (Iterator it(proto); it != it.end(); ++it) {
666 size_t CountCommEvents(const quipper::PerfDataProto& proto) {
667 return CountEvents<CommEventIterator>(proto);
669 size_t CountMmapEvents(const quipper::PerfDataProto& proto) {
670 return CountEvents<MmapEventIterator>(proto);
672 size_t CountSampleEvents(const quipper::PerfDataProto& proto) {
673 return CountEvents<SampleEventIterator>(proto);
675 size_t CountForkEvents(const quipper::PerfDataProto& proto) {
676 return CountEvents<ForkEventIterator>(proto);
678 size_t CountExitEvents(const quipper::PerfDataProto& proto) {
679 return CountEvents<ExitEventIterator>(proto);
682 std::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;
692 std::string FormatSampleEvent(const quipper::PerfDataProto_SampleEvent& sample) {
693 std::ostringstream oss;
694 if (sample.has_pid()) {
695 oss << "pid=" << sample.pid();
697 if (sample.has_tid()) {
698 oss << " tid=" << sample.tid();
700 if (sample.has_ip()) {
701 oss << " ip=" << sample.ip();
703 if (sample.has_addr()) {
704 oss << " addr=" << sample.addr();
706 if (sample.callchain_size() > 0) {
707 oss << " callchain=";
708 for (uint64_t cc : sample.callchain()) {
717 struct BasicRunWithCannedPerf : PerfProfdTest {
718 void VerifyBasicCannedProfile(const android::perfprofd::PerfprofdRecord& encodedProfile) {
719 ASSERT_TRUE(encodedProfile.has_perf_data()) << test_logger.JoinTestLog(" ");
720 const quipper::PerfDataProto& perf_data = encodedProfile.perf_data();
722 // Expect 21108 events.
723 EXPECT_EQ(21108, perf_data.events_size()) << CreateStats(perf_data);
725 EXPECT_EQ(48, CountMmapEvents(perf_data)) << CreateStats(perf_data);
726 EXPECT_EQ(19986, CountSampleEvents(perf_data)) << CreateStats(perf_data);
727 EXPECT_EQ(1033, CountCommEvents(perf_data)) << CreateStats(perf_data);
728 EXPECT_EQ(15, CountForkEvents(perf_data)) << CreateStats(perf_data);
729 EXPECT_EQ(26, CountExitEvents(perf_data)) << CreateStats(perf_data);
731 if (HasNonfatalFailure()) {
736 MmapEventIterator mmap(perf_data);
737 constexpr std::pair<const char*, uint64_t> kMmapEvents[] = {
738 std::make_pair("[kernel.kallsyms]_text", 0),
739 std::make_pair("/system/lib/libc.so", 3067412480u),
740 std::make_pair("/system/vendor/lib/libdsutils.so", 3069911040u),
741 std::make_pair("/system/lib/libc.so", 3067191296u),
742 std::make_pair("/system/lib/libc++.so", 3069210624u),
743 std::make_pair("/data/dalvik-cache/arm/system@framework@boot.oat", 1900048384u),
744 std::make_pair("/system/lib/libjavacore.so", 2957135872u),
745 std::make_pair("/system/vendor/lib/libqmi_encdec.so", 3006644224u),
746 std::make_pair("/data/dalvik-cache/arm/system@framework@wifi-service.jar@classes.dex",
748 std::make_pair("/system/lib/libart.so", 3024150528u),
749 std::make_pair("/system/lib/libz.so", 3056410624u),
750 std::make_pair("/system/lib/libicui18n.so", 3057610752u),
752 for (auto& pair : kMmapEvents) {
753 EXPECT_STREQ(pair.first, mmap->mmap_event().filename().c_str());
754 EXPECT_EQ(pair.second, mmap->mmap_event().start()) << pair.first;
760 CommEventIterator comm(perf_data);
761 constexpr const char* kCommEvents[] = {
762 "init", "kthreadd", "ksoftirqd/0", "kworker/u:0H", "migration/0", "khelper",
763 "netns", "modem_notifier", "smd_channel_clo", "smsm_cb_wq", "rpm-smd", "kworker/u:1H",
765 for (auto str : kCommEvents) {
766 EXPECT_STREQ(str, comm->comm_event().comm().c_str());
772 SampleEventIterator samples(perf_data);
773 constexpr const char* kSampleEvents[] = {
774 "pid=0 tid=0 ip=3222720196",
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=0 tid=0 ip=3222910876",
781 "pid=3 tid=3 ip=3231975108",
782 "pid=5926 tid=5926 ip=3231964952",
783 "pid=5926 tid=5926 ip=3225342428",
784 "pid=5926 tid=5926 ip=3223841448",
785 "pid=5926 tid=5926 ip=3069807920",
787 for (auto str : kSampleEvents) {
788 EXPECT_STREQ(str, FormatSampleEvent(samples->sample_event()).c_str());
792 // Skip some samples.
793 for (size_t i = 0; i != 5000; ++i) {
796 constexpr const char* kSampleEvents2[] = {
797 "pid=5938 tid=5938 ip=3069630992",
798 "pid=5938 tid=5938 ip=3069626616",
799 "pid=5938 tid=5938 ip=3069626636",
800 "pid=5938 tid=5938 ip=3069637212",
801 "pid=5938 tid=5938 ip=3069637208",
802 "pid=5938 tid=5938 ip=3069637252",
803 "pid=5938 tid=5938 ip=3069346040",
804 "pid=5938 tid=5938 ip=3069637128",
805 "pid=5938 tid=5938 ip=3069626616",
807 for (auto str : kSampleEvents2) {
808 EXPECT_STREQ(str, FormatSampleEvent(samples->sample_event()).c_str());
812 // Skip some samples.
813 for (size_t i = 0; i != 5000; ++i) {
816 constexpr const char* kSampleEvents3[] = {
817 "pid=5938 tid=5938 ip=3069912036",
818 "pid=5938 tid=5938 ip=3069637260",
819 "pid=5938 tid=5938 ip=3069631024",
820 "pid=5938 tid=5938 ip=3069346064",
821 "pid=5938 tid=5938 ip=3069637356",
822 "pid=5938 tid=5938 ip=3069637144",
823 "pid=5938 tid=5938 ip=3069912036",
824 "pid=5938 tid=5938 ip=3069912036",
825 "pid=5938 tid=5938 ip=3069631244",
827 for (auto str : kSampleEvents3) {
828 EXPECT_STREQ(str, FormatSampleEvent(samples->sample_event()).c_str());
835 TEST_F(BasicRunWithCannedPerf, Basic)
838 // Verify the portion of the daemon that reads and encodes
839 // perf.data files. Here we run the encoder on a canned perf.data
840 // file and verify that the resulting protobuf contains what
841 // we think it should contain.
843 std::string input_perf_data(test_dir);
844 input_perf_data += "/canned.perf.data";
846 // Set up config to avoid these annotations (they are tested elsewhere)
847 ConfigReader config_reader;
848 config_reader.overrideUnsignedEntry("collect_cpu_utilization", 0);
849 config_reader.overrideUnsignedEntry("collect_charging_state", 0);
850 config_reader.overrideUnsignedEntry("collect_camera_active", 0);
852 // Disable compression.
853 config_reader.overrideUnsignedEntry("compress", 0);
855 PerfProfdRunner::LoggingConfig config;
856 config_reader.FillConfig(&config);
858 // Kick off encoder and check return code
859 PROFILE_RESULT result =
860 encode_to_proto(input_perf_data, encoded_file_path(dest_dir, 0).c_str(), config, 0, nullptr);
861 ASSERT_EQ(OK_PROFILE_COLLECTION, result) << test_logger.JoinTestLog(" ");
863 // Read and decode the resulting perf.data.encoded file
864 android::perfprofd::PerfprofdRecord encodedProfile;
865 readEncodedProfile(dest_dir, false, encodedProfile);
867 VerifyBasicCannedProfile(encodedProfile);
870 TEST_F(BasicRunWithCannedPerf, Compressed)
873 // Verify the portion of the daemon that reads and encodes
874 // perf.data files. Here we run the encoder on a canned perf.data
875 // file and verify that the resulting protobuf contains what
876 // we think it should contain.
878 std::string input_perf_data(test_dir);
879 input_perf_data += "/canned.perf.data";
881 // Set up config to avoid these annotations (they are tested elsewhere)
882 ConfigReader config_reader;
883 config_reader.overrideUnsignedEntry("collect_cpu_utilization", 0);
884 config_reader.overrideUnsignedEntry("collect_charging_state", 0);
885 config_reader.overrideUnsignedEntry("collect_camera_active", 0);
887 // Enable compression.
888 config_reader.overrideUnsignedEntry("compress", 1);
890 PerfProfdRunner::LoggingConfig config;
891 config_reader.FillConfig(&config);
893 // Kick off encoder and check return code
894 PROFILE_RESULT result =
895 encode_to_proto(input_perf_data, encoded_file_path(dest_dir, 0).c_str(), config, 0, nullptr);
896 ASSERT_EQ(OK_PROFILE_COLLECTION, result) << test_logger.JoinTestLog(" ");
898 // Read and decode the resulting perf.data.encoded file
899 android::perfprofd::PerfprofdRecord encodedProfile;
900 readEncodedProfile(dest_dir, true, encodedProfile);
902 VerifyBasicCannedProfile(encodedProfile);
905 TEST_F(BasicRunWithCannedPerf, WithSymbolizer)
908 // Verify the portion of the daemon that reads and encodes
909 // perf.data files. Here we run the encoder on a canned perf.data
910 // file and verify that the resulting protobuf contains what
911 // we think it should contain.
913 std::string input_perf_data(test_dir);
914 input_perf_data += "/canned.perf.data";
916 // Set up config to avoid these annotations (they are tested elsewhere)
917 ConfigReader config_reader;
918 config_reader.overrideUnsignedEntry("collect_cpu_utilization", 0);
919 config_reader.overrideUnsignedEntry("collect_charging_state", 0);
920 config_reader.overrideUnsignedEntry("collect_camera_active", 0);
922 // Disable compression.
923 config_reader.overrideUnsignedEntry("compress", 0);
925 PerfProfdRunner::LoggingConfig config;
926 config_reader.FillConfig(&config);
928 // Kick off encoder and check return code
929 struct TestSymbolizer : public perfprofd::Symbolizer {
930 std::string Decode(const std::string& dso, uint64_t address) override {
931 return dso + "@" + std::to_string(address);
933 bool GetMinExecutableVAddr(const std::string& dso, uint64_t* addr) override {
938 TestSymbolizer test_symbolizer;
939 PROFILE_RESULT result =
940 encode_to_proto(input_perf_data,
941 encoded_file_path(dest_dir, 0).c_str(),
945 ASSERT_EQ(OK_PROFILE_COLLECTION, result);
947 // Read and decode the resulting perf.data.encoded file
948 android::perfprofd::PerfprofdRecord encodedProfile;
949 readEncodedProfile(dest_dir, false, encodedProfile);
951 VerifyBasicCannedProfile(encodedProfile);
953 auto find_symbol = [&](const std::string& filename)
954 -> const android::perfprofd::PerfprofdRecord_SymbolInfo* {
955 for (auto& symbol_info : encodedProfile.symbol_info()) {
956 if (symbol_info.filename() == filename) {
962 auto all_filenames = [&]() {
963 std::ostringstream oss;
964 for (auto& symbol_info : encodedProfile.symbol_info()) {
965 oss << " " << symbol_info.filename();
970 EXPECT_TRUE(find_symbol("/data/app/com.google.android.apps.plus-1/lib/arm/libcronet.so")
971 != nullptr) << all_filenames() << test_logger.JoinTestLog("\n");
972 EXPECT_TRUE(find_symbol("/data/dalvik-cache/arm/system@framework@wifi-service.jar@classes.dex")
973 != nullptr) << all_filenames();
974 EXPECT_TRUE(find_symbol("/data/dalvik-cache/arm/data@app@com.google.android.gms-2@base.apk@"
976 != nullptr) << all_filenames();
977 EXPECT_TRUE(find_symbol("/data/dalvik-cache/arm/system@framework@boot.oat") != nullptr)
981 TEST_F(PerfProfdTest, CallchainRunWithCannedPerf)
983 // This test makes sure that the perf.data converter
984 // can handle call chains.
986 std::string input_perf_data(test_dir);
987 input_perf_data += "/callchain.canned.perf.data";
989 // Set up config to avoid these annotations (they are tested elsewhere)
990 ConfigReader config_reader;
991 config_reader.overrideUnsignedEntry("collect_cpu_utilization", 0);
992 config_reader.overrideUnsignedEntry("collect_charging_state", 0);
993 config_reader.overrideUnsignedEntry("collect_camera_active", 0);
995 // Disable compression.
996 config_reader.overrideUnsignedEntry("compress", 0);
998 PerfProfdRunner::LoggingConfig config;
999 config_reader.FillConfig(&config);
1001 // Kick off encoder and check return code
1002 PROFILE_RESULT result =
1003 encode_to_proto(input_perf_data, encoded_file_path(dest_dir, 0).c_str(), config, 0, nullptr);
1004 ASSERT_EQ(OK_PROFILE_COLLECTION, result);
1006 // Read and decode the resulting perf.data.encoded file
1007 android::perfprofd::PerfprofdRecord encodedProfile;
1008 readEncodedProfile(dest_dir, false, encodedProfile);
1011 ASSERT_TRUE(encodedProfile.has_perf_data());
1012 const quipper::PerfDataProto& perf_data = encodedProfile.perf_data();
1014 // Expect 21108 events.
1015 EXPECT_EQ(2224, perf_data.events_size()) << CreateStats(perf_data);
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",
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());
1051 if (cmp_index == arraysize(kSampleEvents)) {
1061 TEST_F(PerfProfdTest, BasicRunWithLivePerf)
1064 // Basic test to exercise the main loop of the daemon. It includes
1065 // a live 'perf' run
1067 PerfProfdRunner runner(conf_dir);
1068 runner.addToConfig("only_debug_build=0");
1069 std::string ddparam("destination_directory="); ddparam += dest_dir;
1070 runner.addToConfig(ddparam);
1071 std::string cfparam("config_directory="); cfparam += conf_dir;
1072 runner.addToConfig(cfparam);
1073 runner.addToConfig("main_loop_iterations=1");
1074 runner.addToConfig("use_fixed_seed=12345678");
1075 runner.addToConfig("max_unprocessed_profiles=100");
1076 runner.addToConfig("collection_interval=9999");
1077 runner.addToConfig("sample_duration=2");
1078 // Avoid the symbolizer for spurious messages.
1079 runner.addToConfig("use_elf_symbolizer=0");
1081 // Disable compression.
1082 runner.addToConfig("compress=0");
1084 // Create semaphore file
1085 runner.create_semaphore_file();
1088 int daemon_main_return_code = runner.invoke();
1090 // Check return code from daemon
1091 ASSERT_EQ(0, daemon_main_return_code);
1093 // Read and decode the resulting perf.data.encoded file
1094 android::perfprofd::PerfprofdRecord encodedProfile;
1095 readEncodedProfile(dest_dir, false, encodedProfile);
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.
1099 EXPECT_LT(0, encodedProfile.perf_data().events_size());
1101 // Verify log contents
1102 const std::string expected = std::string(
1103 "I: starting Android Wide Profiling daemon ") +
1104 "I: config file path set to " + conf_dir + "/perfprofd.conf " +
1106 I: random seed set to 12345678
1107 I: sleep 674 seconds
1108 I: initiating profile collection
1110 I: profile collection complete
1111 I: sleep 9325 seconds
1112 I: finishing Android Wide Profiling daemon
1114 // check to make sure log excerpt matches
1115 CompareLogMessages(expandVars(expected), "BasicRunWithLivePerf", true);
1118 TEST_F(PerfProfdTest, MultipleRunWithLivePerf)
1121 // Basic test to exercise the main loop of the daemon. It includes
1122 // a live 'perf' run
1124 PerfProfdRunner runner(conf_dir);
1125 runner.addToConfig("only_debug_build=0");
1126 std::string ddparam("destination_directory="); ddparam += dest_dir;
1127 runner.addToConfig(ddparam);
1128 std::string cfparam("config_directory="); cfparam += conf_dir;
1129 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");
1134 // Avoid the symbolizer for spurious messages.
1135 runner.addToConfig("use_elf_symbolizer=0");
1137 // Disable compression.
1138 runner.addToConfig("compress=0");
1140 runner.write_processed_file(1, 2);
1142 // Create semaphore file
1143 runner.create_semaphore_file();
1146 int daemon_main_return_code = runner.invoke();
1148 // Check return code from daemon
1149 ASSERT_EQ(0, daemon_main_return_code);
1151 // Read and decode the resulting perf.data.encoded file
1152 android::perfprofd::PerfprofdRecord encodedProfile;
1153 readEncodedProfile(dest_dir, false, encodedProfile);
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.
1157 EXPECT_LT(0, encodedProfile.perf_data().events_size());
1159 // Examine that encoded.1 file is removed while encoded.{0|2} exists.
1160 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));
1164 // Verify log contents
1165 const std::string expected = std::string(
1166 "I: starting Android Wide Profiling daemon ") +
1167 "I: config file path set to " + conf_dir + "/perfprofd.conf " +
1169 I: random seed set to 12345678
1170 I: sleep 674 seconds
1171 I: initiating profile collection
1173 I: profile collection complete
1174 I: sleep 9325 seconds
1175 I: sleep 4974 seconds
1176 I: initiating profile collection
1178 I: profile collection complete
1179 I: sleep 5025 seconds
1180 I: sleep 501 seconds
1181 I: initiating profile collection
1183 I: profile collection complete
1184 I: sleep 9498 seconds
1185 I: finishing Android Wide Profiling daemon
1187 // check to make sure log excerpt matches
1188 CompareLogMessages(expandVars(expected), "BasicRunWithLivePerf", true);
1191 TEST_F(PerfProfdTest, CallChainRunWithLivePerf)
1194 // Collect a callchain profile, so as to exercise the code in
1195 // perf_data post-processing that digests callchains.
1197 PerfProfdRunner runner(conf_dir);
1198 std::string ddparam("destination_directory="); ddparam += dest_dir;
1199 runner.addToConfig(ddparam);
1200 std::string cfparam("config_directory="); cfparam += conf_dir;
1201 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");
1208 // Avoid the symbolizer for spurious messages.
1209 runner.addToConfig("use_elf_symbolizer=0");
1211 // Disable compression.
1212 runner.addToConfig("compress=0");
1214 // Create semaphore file
1215 runner.create_semaphore_file();
1218 int daemon_main_return_code = runner.invoke();
1220 // Check return code from daemon
1221 ASSERT_EQ(0, daemon_main_return_code);
1223 // Read and decode the resulting perf.data.encoded file
1224 android::perfprofd::PerfprofdRecord encodedProfile;
1225 readEncodedProfile(dest_dir, false, encodedProfile);
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.
1229 EXPECT_LT(0, encodedProfile.perf_data().events_size());
1231 // Verify log contents
1232 const std::string expected = std::string(
1233 "I: starting Android Wide Profiling daemon ") +
1234 "I: config file path set to " + conf_dir + "/perfprofd.conf " +
1236 I: random seed set to 12345678
1237 I: sleep 674 seconds
1238 I: initiating profile collection
1240 I: profile collection complete
1241 I: sleep 9325 seconds
1242 I: finishing Android Wide Profiling daemon
1244 // check to make sure log excerpt matches
1245 CompareLogMessages(expandVars(expected), "CallChainRunWithLivePerf", true);
1247 // Check that we have at least one SampleEvent with a callchain.
1248 SampleEventIterator samples(encodedProfile.perf_data());
1249 bool found_callchain = false;
1250 while (!found_callchain && samples != samples.end()) {
1251 found_callchain = samples->sample_event().callchain_size() > 0;
1253 EXPECT_TRUE(found_callchain) << CreateStats(encodedProfile.perf_data());
1258 class RangeMapTest : public testing::Test {
1261 TEST_F(RangeMapTest, TestRangeMap) {
1262 using namespace android::perfprofd;
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;
1270 for (auto& x : aggr_sym.second.offsets) {
1278 EXPECT_STREQ("", print().c_str());
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());
1285 EXPECT_STREQ("1#a[1,10,100,]", print().c_str());
1287 EXPECT_STREQ("1#a[1,10,100,]", print().c_str());
1289 EXPECT_STREQ("1#a[1,2,10,100,]", print().c_str());
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());
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());
1300 int main(int argc, char **argv) {
1301 // Always log to cerr, so that device failures are visible.
1302 android::base::SetLogger(android::base::StderrLogger);
1304 CHECK(android::base::Realpath(argv[0], &gExecutableRealpath));
1306 // switch to / before starting testing (perfprofd
1307 // should be location-independent)
1309 testing::InitGoogleTest(&argc, argv);
1310 return RUN_ALL_TESTS();