OSDN Git Service

Perfprofd: Use external quipper
[android-x86/system-extras.git] / perfprofd / tests / perfprofd_test.cc
1 /*
2  * Copyright (C) 2015 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <algorithm>
18 #include <cctype>
19 #include <functional>
20 #include <iterator>
21 #include <memory>
22 #include <mutex>
23 #include <regex>
24 #include <string>
25
26 #include <fcntl.h>
27 #include <stdio.h>
28 #include <libgen.h>
29 #include <sys/types.h>
30 #include <sys/stat.h>
31
32 #include <android-base/file.h>
33 #include <android-base/logging.h>
34 #include <android-base/macros.h>
35 #include <android-base/properties.h>
36 #include <android-base/stringprintf.h>
37 #include <android-base/strings.h>
38 #include <android-base/test_utils.h>
39 #include <android-base/thread_annotations.h>
40 #include <gtest/gtest.h>
41
42 #include "config.h"
43 #include "configreader.h"
44 #include "perfprofdcore.h"
45 #include "symbolizer.h"
46
47 #include "perfprofd_record.pb.h"
48
49 //
50 // Set to argv[0] on startup
51 //
52 static std::string gExecutableRealpath;
53
54 namespace {
55
56 using android::base::LogId;
57 using android::base::LogSeverity;
58
59 class TestLogHelper {
60  public:
61   void Install() {
62     using namespace std::placeholders;
63     android::base::SetLogger(
64         std::bind(&TestLogHelper::TestLogFunction, this, _1, _2, _3, _4, _5, _6));
65   }
66
67   std::string JoinTestLog(const char* delimiter) {
68     std::unique_lock<std::mutex> ul(lock_);
69     return android::base::Join(test_log_messages_, delimiter);
70   }
71   template <typename Predicate>
72   std::string JoinTestLog(const char* delimiter, Predicate pred) {
73     std::unique_lock<std::mutex> ul(lock_);
74     std::vector<std::string> tmp;
75     std::copy_if(test_log_messages_.begin(),
76                  test_log_messages_.end(),
77                  std::back_inserter(tmp),
78                  pred);
79     return android::base::Join(tmp, delimiter);
80   }
81
82  private:
83   void TestLogFunction(LogId log_id ATTRIBUTE_UNUSED,
84                        LogSeverity severity,
85                        const char* tag,
86                        const char* file ATTRIBUTE_UNUSED,
87                        unsigned int line ATTRIBUTE_UNUSED,
88                        const char* message) {
89     std::unique_lock<std::mutex> ul(lock_);
90     constexpr char log_characters[] = "VDIWEFF";
91     char severity_char = log_characters[severity];
92     test_log_messages_.push_back(android::base::StringPrintf("%c: %s", severity_char, message));
93   }
94
95  private:
96   std::mutex lock_;
97
98   std::vector<std::string> test_log_messages_;
99 };
100
101 }  // namespace
102
103 // Path to perf executable on device
104 #define PERFPATH "/system/bin/perf"
105
106 // Temporary config file that we will emit for the daemon to read
107 #define CONFIGFILE "perfprofd.conf"
108
109 static bool bothWhiteSpace(char lhs, char rhs)
110 {
111   return (std::isspace(lhs) && std::isspace(rhs));
112 }
113
114 //
115 // Squeeze out repeated whitespace from expected/actual logs.
116 //
117 static std::string squeezeWhite(const std::string &str,
118                                 const char *tag,
119                                 bool dump=false)
120 {
121   if (dump) { fprintf(stderr, "raw %s is %s\n", tag, str.c_str()); }
122   std::string result(str);
123   std::replace(result.begin(), result.end(), '\n', ' ');
124   auto new_end = std::unique(result.begin(), result.end(), bothWhiteSpace);
125   result.erase(new_end, result.end());
126   while (result.begin() != result.end() && std::isspace(*result.rbegin())) {
127     result.pop_back();
128   }
129   if (dump) { fprintf(stderr, "squeezed %s is %s\n", tag, result.c_str()); }
130   return result;
131 }
132
133 //
134 // Replace all occurrences of a string with another string.
135 //
136 static std::string replaceAll(const std::string &str,
137                               const std::string &from,
138                               const std::string &to)
139 {
140   std::string ret = "";
141   size_t pos = 0;
142   while (pos < str.size()) {
143     size_t found = str.find(from, pos);
144     if (found == std::string::npos) {
145       ret += str.substr(pos);
146       break;
147     }
148     ret += str.substr(pos, found - pos) + to;
149     pos = found + from.size();
150   }
151   return ret;
152 }
153
154 //
155 // Replace occurrences of special variables in the string.
156 //
157 static std::string expandVars(const std::string &str) {
158 #ifdef __LP64__
159   return replaceAll(str, "$NATIVE_TESTS", "/data/nativetest64");
160 #else
161   return replaceAll(str, "$NATIVE_TESTS", "/data/nativetest");
162 #endif
163 }
164
165 class PerfProfdTest : public testing::Test {
166  protected:
167   virtual void SetUp() {
168     test_logger.Install();
169     create_dirs();
170   }
171
172   virtual void TearDown() {
173     android::base::SetLogger(android::base::StderrLogger);
174
175     // TODO: proper management of test files. For now, use old system() code.
176     for (const auto dir : { &dest_dir, &conf_dir }) {
177       std::string cmd("rm -rf ");
178       cmd += *dir;
179       int ret = system(cmd.c_str());
180       CHECK_EQ(0, ret);
181     }
182   }
183
184  protected:
185   //
186   // Check to see if the log messages emitted by the daemon
187   // match the expected result. By default we use a partial
188   // match, e.g. if we see the expected excerpt anywhere in the
189   // result, it's a match (for exact match, set exact to true)
190   //
191   void CompareLogMessages(const std::string& expected,
192                           const char* testpoint,
193                           bool exactMatch = false) {
194      std::string sqexp = squeezeWhite(expected, "expected");
195
196      // Strip out JIT errors.
197      std::regex jit_regex("E: Failed to open ELF file: [^ ]*ashmem/dalvik-jit-code-cache.*");
198      auto strip_jit = [&](const std::string& str) {
199        std::smatch jit_match;
200        return !std::regex_match(str, jit_match, jit_regex);
201      };
202      std::string sqact = squeezeWhite(test_logger.JoinTestLog(" ", strip_jit), "actual");
203
204      if (exactMatch) {
205        EXPECT_STREQ(sqexp.c_str(), sqact.c_str());
206      } else {
207        std::size_t foundpos = sqact.find(sqexp);
208        bool wasFound = true;
209        if (foundpos == std::string::npos) {
210          std::cerr << testpoint << ": expected result not found\n";
211          std::cerr << " Actual: \"" << sqact << "\"\n";
212          std::cerr << " Expected: \"" << sqexp << "\"\n";
213          wasFound = false;
214        }
215        EXPECT_TRUE(wasFound);
216      }
217   }
218
219   // test_dir is the directory containing the test executable and
220   // any files associated with the test (will be created by the harness).
221   std::string test_dir;
222
223   // dest_dir is a temporary directory that we're using as the destination directory.
224   // It is backed by temp_dir1.
225   std::string dest_dir;
226
227   // conf_dir is a temporary directory that we're using as the configuration directory.
228   // It is backed by temp_dir2.
229   std::string conf_dir;
230
231   TestLogHelper test_logger;
232
233  private:
234   void create_dirs() {
235     temp_dir1.reset(new TemporaryDir());
236     temp_dir2.reset(new TemporaryDir());
237     dest_dir = temp_dir1->path;
238     conf_dir = temp_dir2->path;
239     test_dir = android::base::Dirname(gExecutableRealpath);
240   }
241
242   std::unique_ptr<TemporaryDir> temp_dir1;
243   std::unique_ptr<TemporaryDir> temp_dir2;
244 };
245
246 ///
247 /// Helper class to kick off a run of the perfprofd daemon with a specific
248 /// config file.
249 ///
250 class PerfProfdRunner {
251  public:
252   explicit PerfProfdRunner(const std::string& config_dir)
253       : config_dir_(config_dir)
254   {
255     config_path_ = config_dir + "/" CONFIGFILE;
256   }
257
258   ~PerfProfdRunner()
259   {
260     remove_processed_file();
261   }
262
263   void addToConfig(const std::string &line)
264   {
265     config_text_ += line;
266     config_text_ += "\n";
267   }
268
269   void remove_semaphore_file()
270   {
271     std::string semaphore(config_dir_);
272     semaphore += "/" SEMAPHORE_FILENAME;
273     unlink(semaphore.c_str());
274   }
275
276   void create_semaphore_file()
277   {
278     std::string semaphore(config_dir_);
279     semaphore += "/" SEMAPHORE_FILENAME;
280     close(open(semaphore.c_str(), O_WRONLY|O_CREAT, 0600));
281   }
282
283   void write_processed_file(int start_seq, int end_seq)
284   {
285     std::string processed = config_dir_ + "/" PROCESSED_FILENAME;
286     FILE *fp = fopen(processed.c_str(), "w");
287     for (int i = start_seq; i < end_seq; i++) {
288       fprintf(fp, "%d\n", i);
289     }
290     fclose(fp);
291   }
292
293   void remove_processed_file()
294   {
295     std::string processed = config_dir_ + "/" PROCESSED_FILENAME;
296     unlink(processed.c_str());
297   }
298
299   struct LoggingConfig : public Config {
300     void Sleep(size_t seconds) override {
301       // Log sleep calls but don't sleep.
302       LOG(INFO) << "sleep " << seconds << " seconds";
303     }
304
305     bool IsProfilingEnabled() const override {
306       //
307       // Check for existence of semaphore file in config directory
308       //
309       if (access(config_directory.c_str(), F_OK) == -1) {
310         PLOG(WARNING) << "unable to open config directory " << config_directory;
311         return false;
312       }
313
314       // Check for existence of semaphore file
315       std::string semaphore_filepath = config_directory
316           + "/" + SEMAPHORE_FILENAME;
317       if (access(semaphore_filepath.c_str(), F_OK) == -1) {
318         return false;
319       }
320
321       return true;
322     }
323   };
324
325   int invoke()
326   {
327     static const char *argv[3] = { "perfprofd", "-c", "" };
328     argv[2] = config_path_.c_str();
329
330     writeConfigFile(config_path_, config_text_);
331
332     // execute daemon main
333     LoggingConfig config;
334     return perfprofd_main(3, (char **) argv, &config);
335   }
336
337  private:
338   std::string config_dir_;
339   std::string config_path_;
340   std::string config_text_;
341
342   void writeConfigFile(const std::string &config_path,
343                        const std::string &config_text)
344   {
345     FILE *fp = fopen(config_path.c_str(), "w");
346     ASSERT_TRUE(fp != nullptr);
347     fprintf(fp, "%s\n", config_text.c_str());
348     fclose(fp);
349   }
350 };
351
352 //......................................................................
353
354 static std::string encoded_file_path(const std::string& dest_dir,
355                                      int seq) {
356   return android::base::StringPrintf("%s/perf.data.encoded.%d",
357                                      dest_dir.c_str(), seq);
358 }
359
360 static void readEncodedProfile(const std::string& dest_dir,
361                                const char *testpoint,
362                                android::perfprofd::PerfprofdRecord& encodedProfile)
363 {
364   struct stat statb;
365   int perf_data_stat_result = stat(encoded_file_path(dest_dir, 0).c_str(), &statb);
366   ASSERT_NE(-1, perf_data_stat_result);
367
368   // read
369   std::string encoded;
370   encoded.resize(statb.st_size);
371   FILE *ifp = fopen(encoded_file_path(dest_dir, 0).c_str(), "r");
372   ASSERT_NE(nullptr, ifp);
373   size_t items_read = fread((void*) encoded.data(), statb.st_size, 1, ifp);
374   ASSERT_EQ(1, items_read);
375   fclose(ifp);
376
377   // decode
378   encodedProfile.ParseFromString(encoded);
379 }
380
381 /*
382 static std::string encodedLoadModuleToString(const wireless_android_play_playlog::LoadModule &lm)
383 {
384   std::stringstream ss;
385   ss << "name: \"" << lm.name() << "\"\n";
386   if (lm.build_id() != "") {
387     ss << "build_id: \"" << lm.build_id() << "\"\n";
388   }
389   for (const auto& symbol : lm.symbol()) {
390     ss << "symbol: \"" << symbol << "\"\n";
391   }
392   return ss.str();
393 }
394 */
395
396 /*
397 static std::string encodedModuleSamplesToString(const wireless_android_play_playlog::LoadModuleSamples &mod)
398 {
399   std::stringstream ss;
400
401   ss << "load_module_id: " << mod.load_module_id() << "\n";
402   for (size_t k = 0; k < mod.address_samples_size(); k++) {
403     const auto &sample = mod.address_samples(k);
404     ss << "  address_samples {\n";
405     for (size_t l = 0; l < mod.address_samples(k).address_size();
406          l++) {
407       auto address = mod.address_samples(k).address(l);
408       ss << "    address: " << address << "\n";
409     }
410     ss << "    count: " << sample.count() << "\n";
411     ss << "  }\n";
412   }
413   return ss.str();
414 }
415 */
416
417 #define RAW_RESULT(x) #x
418
419 TEST_F(PerfProfdTest, TestUtil)
420 {
421   EXPECT_EQ("", replaceAll("", "", ""));
422   EXPECT_EQ("zzbc", replaceAll("abc", "a", "zz"));
423   EXPECT_EQ("azzc", replaceAll("abc", "b", "zz"));
424   EXPECT_EQ("abzz", replaceAll("abc", "c", "zz"));
425   EXPECT_EQ("xxyyzz", replaceAll("abc", "abc", "xxyyzz"));
426 }
427
428 TEST_F(PerfProfdTest, MissingGMS)
429 {
430   //
431   // AWP requires cooperation between the daemon and the GMS core
432   // piece. If we're running on a device that has an old or damaged
433   // version of GMS core, then the config directory we're interested in
434   // may not be there. This test insures that the daemon does the
435   // right thing in this case.
436   //
437   PerfProfdRunner runner(conf_dir);
438   runner.addToConfig("only_debug_build=0");
439   runner.addToConfig("trace_config_read=0");
440   runner.addToConfig("config_directory=/does/not/exist");
441   runner.addToConfig("main_loop_iterations=1");
442   runner.addToConfig("use_fixed_seed=1");
443   runner.addToConfig("collection_interval=100");
444
445   // Kick off daemon
446   int daemon_main_return_code = runner.invoke();
447
448   // Check return code from daemon
449   EXPECT_EQ(0, daemon_main_return_code);
450
451   // Verify log contents
452   const std::string expected = RAW_RESULT(
453       I: sleep 90 seconds
454       W: unable to open config directory /does/not/exist: No such file or directory
455       I: profile collection skipped (missing config directory)
456                                           );
457
458   // check to make sure entire log matches
459   CompareLogMessages(expected, "MissingGMS");
460 }
461
462
463 TEST_F(PerfProfdTest, MissingOptInSemaphoreFile)
464 {
465   //
466   // Android device owners must opt in to "collect and report usage
467   // data" in order for us to be able to collect profiles. The opt-in
468   // check is performed in the GMS core component; if the check
469   // passes, then it creates a semaphore file for the daemon to pick
470   // up on.
471   //
472   PerfProfdRunner runner(conf_dir);
473   runner.addToConfig("only_debug_build=0");
474   std::string cfparam("config_directory="); cfparam += conf_dir;
475   runner.addToConfig(cfparam);
476   std::string ddparam("destination_directory="); ddparam += dest_dir;
477   runner.addToConfig(ddparam);
478   runner.addToConfig("main_loop_iterations=1");
479   runner.addToConfig("use_fixed_seed=1");
480   runner.addToConfig("collection_interval=100");
481
482   runner.remove_semaphore_file();
483
484   // Kick off daemon
485   int daemon_main_return_code = runner.invoke();
486
487   // Check return code from daemon
488   EXPECT_EQ(0, daemon_main_return_code);
489
490   // Verify log contents
491   const std::string expected = RAW_RESULT(
492       I: profile collection skipped (missing config directory)
493                                           );
494   // check to make sure log excerpt matches
495   CompareLogMessages(expected, "MissingOptInSemaphoreFile");
496 }
497
498 TEST_F(PerfProfdTest, MissingPerfExecutable)
499 {
500   //
501   // Perfprofd uses the 'simpleperf' tool to collect profiles
502   // (although this may conceivably change in the future). This test
503   // checks to make sure that if 'simpleperf' is not present we bail out
504   // from collecting profiles.
505   //
506   PerfProfdRunner runner(conf_dir);
507   runner.addToConfig("only_debug_build=0");
508   runner.addToConfig("trace_config_read=1");
509   std::string cfparam("config_directory="); cfparam += conf_dir;
510   runner.addToConfig(cfparam);
511   std::string ddparam("destination_directory="); ddparam += dest_dir;
512   runner.addToConfig(ddparam);
513   runner.addToConfig("main_loop_iterations=1");
514   runner.addToConfig("use_fixed_seed=1");
515   runner.addToConfig("collection_interval=100");
516   runner.addToConfig("perf_path=/does/not/exist");
517
518   // Create semaphore file
519   runner.create_semaphore_file();
520
521   // Kick off daemon
522   int daemon_main_return_code = runner.invoke();
523
524   // Check return code from daemon
525   EXPECT_EQ(0, daemon_main_return_code);
526
527   // expected log contents
528   const std::string expected = RAW_RESULT(
529       I: profile collection skipped (missing 'perf' executable)
530                                           );
531   // check to make sure log excerpt matches
532   CompareLogMessages(expected, "MissingPerfExecutable");
533 }
534
535 TEST_F(PerfProfdTest, BadPerfRun)
536 {
537   //
538   // Perf tools tend to be tightly coupled with a specific kernel
539   // version -- if things are out of sync perf could fail or
540   // crash. This test makes sure that we detect such a case and log
541   // the error.
542   //
543   PerfProfdRunner runner(conf_dir);
544   runner.addToConfig("only_debug_build=0");
545   std::string cfparam("config_directory="); cfparam += conf_dir;
546   runner.addToConfig(cfparam);
547   std::string ddparam("destination_directory="); ddparam += dest_dir;
548   runner.addToConfig(ddparam);
549   runner.addToConfig("main_loop_iterations=1");
550   runner.addToConfig("use_fixed_seed=1");
551   runner.addToConfig("collection_interval=100");
552   runner.addToConfig("perf_path=/system/bin/false");
553
554   // Create semaphore file
555   runner.create_semaphore_file();
556
557   // Kick off daemon
558   int daemon_main_return_code = runner.invoke();
559
560   // Check return code from daemon
561   EXPECT_EQ(0, daemon_main_return_code);
562
563   // Verify log contents
564   const std::string expected = RAW_RESULT(
565       W: perf bad exit status 1
566       W: profile collection failed
567                                           );
568
569   // check to make sure log excerpt matches
570   CompareLogMessages(expected, "BadPerfRun");
571 }
572
573 TEST_F(PerfProfdTest, ConfigFileParsing)
574 {
575   //
576   // Gracefully handly malformed items in the config file
577   //
578   PerfProfdRunner runner(conf_dir);
579   runner.addToConfig("only_debug_build=0");
580   runner.addToConfig("main_loop_iterations=1");
581   runner.addToConfig("collection_interval=100");
582   runner.addToConfig("use_fixed_seed=1");
583   runner.addToConfig("destination_directory=/does/not/exist");
584
585   // assorted bad syntax
586   runner.addToConfig("collection_interval=0");
587   runner.addToConfig("collection_interval=-1");
588   runner.addToConfig("collection_interval=2");
589   runner.addToConfig("nonexistent_key=something");
590   runner.addToConfig("no_equals_stmt");
591
592   // Kick off daemon
593   int daemon_main_return_code = runner.invoke();
594
595   // Check return code from daemon
596   EXPECT_EQ(0, daemon_main_return_code);
597
598   // Verify log contents
599   const std::string expected = RAW_RESULT(
600       W: line 6: specified value 0 for 'collection_interval' outside permitted range [100 4294967295] (ignored)
601       W: line 7: malformed unsigned value (ignored)
602       W: line 8: specified value 2 for 'collection_interval' outside permitted range [100 4294967295] (ignored)
603       W: line 9: unknown option 'nonexistent_key' ignored
604       W: line 10: line malformed (no '=' found)
605                                           );
606
607   // check to make sure log excerpt matches
608   CompareLogMessages(expected, "ConfigFileParsing");
609 }
610
611 TEST_F(PerfProfdTest, ProfileCollectionAnnotations)
612 {
613   unsigned util1 = collect_cpu_utilization();
614   EXPECT_LE(util1, 100);
615   EXPECT_GE(util1, 0);
616
617   // NB: expectation is that when we run this test, the device will be
618   // completed booted, will be on charger, and will not have the camera
619   // active.
620   EXPECT_FALSE(get_booting());
621   EXPECT_TRUE(get_charging());
622   EXPECT_FALSE(get_camera_active());
623 }
624
625 namespace {
626
627 template<typename Iterator, typename Predicate>
628 class FilteredIterator {
629  public:
630   using value_type =      typename std::iterator_traits<Iterator>::value_type;
631   using difference_type = typename std::iterator_traits<Iterator>::difference_type;
632   using reference =       typename std::iterator_traits<Iterator>::reference;
633   using pointer =         typename std::iterator_traits<Iterator>::pointer;
634
635   FilteredIterator(const Iterator& begin, const Iterator& end, const Predicate& pred)
636       : iter_(begin), end_(end), pred_(pred) {
637     filter();
638   }
639
640   reference operator*() const {
641     return *iter_;
642   }
643   pointer operator->() const {
644     return std::addressof(*iter_);
645   }
646
647   FilteredIterator& operator++() {
648     ++iter_;
649     filter();
650     return *this;
651   }
652
653   FilteredIterator end() {
654     return FilteredIterator(end_, end_, pred_);
655   }
656
657   bool operator==(const FilteredIterator& rhs) const {
658     return iter_ == rhs.iter_;
659   }
660   bool operator!=(const FilteredIterator& rhs) const {
661     return !(operator==(rhs));
662   }
663
664 private:
665   void filter() {
666     while (iter_ != end_ && !pred_(*iter_)) {
667       ++iter_;
668     }
669   }
670
671   Iterator iter_;
672   Iterator end_;
673   Predicate pred_;
674 };
675
676 template <typename Predicate>
677 using EventFilteredIterator = FilteredIterator<
678     decltype(static_cast<quipper::PerfDataProto*>(nullptr)->events().begin()),
679     Predicate>;
680
681 struct CommEventPredicate {
682   bool operator()(const quipper::PerfDataProto_PerfEvent& evt) {
683     return evt.has_comm_event();
684   }
685 };
686 struct CommEventIterator : public EventFilteredIterator<CommEventPredicate> {
687   explicit CommEventIterator(const quipper::PerfDataProto& proto)
688       : EventFilteredIterator<CommEventPredicate>(proto.events().begin(),
689                                                   proto.events().end(),
690                                                   CommEventPredicate()) {
691   }
692 };
693
694 struct MmapEventPredicate {
695   bool operator()(const quipper::PerfDataProto_PerfEvent& evt) {
696     return evt.has_mmap_event();
697   }
698 };
699 struct MmapEventIterator : public EventFilteredIterator<MmapEventPredicate> {
700   explicit MmapEventIterator(const quipper::PerfDataProto& proto)
701       : EventFilteredIterator<MmapEventPredicate>(proto.events().begin(),
702                                                   proto.events().end(),
703                                                   MmapEventPredicate()) {
704   }
705 };
706
707 struct SampleEventPredicate {
708   bool operator()(const quipper::PerfDataProto_PerfEvent& evt) {
709     return evt.has_sample_event();
710   }
711 };
712 struct SampleEventIterator : public EventFilteredIterator<SampleEventPredicate> {
713   explicit SampleEventIterator(const quipper::PerfDataProto& proto)
714       : EventFilteredIterator<SampleEventPredicate>(proto.events().begin(),
715                                                     proto.events().end(),
716                                                     SampleEventPredicate()) {
717   }
718 };
719
720 struct ForkEventPredicate {
721   bool operator()(const quipper::PerfDataProto_PerfEvent& evt) {
722     return evt.has_fork_event();
723   }
724 };
725 struct ForkEventIterator : public EventFilteredIterator<ForkEventPredicate> {
726   explicit ForkEventIterator(const quipper::PerfDataProto& proto)
727       : EventFilteredIterator<ForkEventPredicate>(proto.events().begin(),
728                                                   proto.events().end(),
729                                                   ForkEventPredicate()) {
730   }
731 };
732
733 struct ExitEventPredicate {
734   bool operator()(const quipper::PerfDataProto_PerfEvent& evt) {
735     return evt.has_exit_event();
736   }
737 };
738 struct ExitEventIterator : public EventFilteredIterator<ExitEventPredicate> {
739   explicit ExitEventIterator(const quipper::PerfDataProto& proto)
740       : EventFilteredIterator<ExitEventPredicate>(proto.events().begin(),
741                                                   proto.events().end(),
742                                                   ExitEventPredicate()) {
743   }
744 };
745
746 template <typename Iterator>
747 size_t CountEvents(const quipper::PerfDataProto& proto) {
748   size_t count = 0;
749   for (Iterator it(proto); it != it.end(); ++it) {
750     count++;
751   }
752   return count;
753 }
754
755 size_t CountCommEvents(const quipper::PerfDataProto& proto) {
756   return CountEvents<CommEventIterator>(proto);
757 }
758 size_t CountMmapEvents(const quipper::PerfDataProto& proto) {
759   return CountEvents<MmapEventIterator>(proto);
760 }
761 size_t CountSampleEvents(const quipper::PerfDataProto& proto) {
762   return CountEvents<SampleEventIterator>(proto);
763 }
764 size_t CountForkEvents(const quipper::PerfDataProto& proto) {
765   return CountEvents<ForkEventIterator>(proto);
766 }
767 size_t CountExitEvents(const quipper::PerfDataProto& proto) {
768   return CountEvents<ExitEventIterator>(proto);
769 }
770
771 std::string CreateStats(const quipper::PerfDataProto& proto) {
772   std::ostringstream oss;
773   oss << "Mmap events: "   << CountMmapEvents(proto) << std::endl;
774   oss << "Sample events: " << CountSampleEvents(proto) << std::endl;
775   oss << "Comm events: "   << CountCommEvents(proto) << std::endl;
776   oss << "Fork events: "   << CountForkEvents(proto) << std::endl;
777   oss << "Exit events: "   << CountExitEvents(proto) << std::endl;
778   return oss.str();
779 }
780
781 std::string FormatSampleEvent(const quipper::PerfDataProto_SampleEvent& sample) {
782   std::ostringstream oss;
783   if (sample.has_pid()) {
784     oss << "pid=" << sample.pid();
785   }
786   if (sample.has_tid()) {
787     oss << " tid=" << sample.tid();
788   }
789   if (sample.has_ip()) {
790       oss << " ip=" << sample.ip();
791     }
792   if (sample.has_addr()) {
793     oss << " addr=" << sample.addr();
794   }
795   if (sample.callchain_size() > 0) {
796     oss << " callchain=";
797     for (uint64_t cc : sample.callchain()) {
798       oss << "->" << cc;
799     }
800   }
801   return oss.str();
802 }
803
804 }
805
806 TEST_F(PerfProfdTest, BasicRunWithCannedPerf)
807 {
808   //
809   // Verify the portion of the daemon that reads and encodes
810   // perf.data files. Here we run the encoder on a canned perf.data
811   // file and verify that the resulting protobuf contains what
812   // we think it should contain.
813   //
814   std::string input_perf_data(test_dir);
815   input_perf_data += "/canned.perf.data";
816
817   // Set up config to avoid these annotations (they are tested elsewhere)
818   ConfigReader config_reader;
819   config_reader.overrideUnsignedEntry("collect_cpu_utilization", 0);
820   config_reader.overrideUnsignedEntry("collect_charging_state", 0);
821   config_reader.overrideUnsignedEntry("collect_camera_active", 0);
822   PerfProfdRunner::LoggingConfig config;
823   config_reader.FillConfig(&config);
824
825   // Kick off encoder and check return code
826   PROFILE_RESULT result =
827       encode_to_proto(input_perf_data, encoded_file_path(dest_dir, 0).c_str(), config, 0, nullptr);
828   ASSERT_EQ(OK_PROFILE_COLLECTION, result) << test_logger.JoinTestLog(" ");
829
830   // Read and decode the resulting perf.data.encoded file
831   android::perfprofd::PerfprofdRecord encodedProfile;
832   readEncodedProfile(dest_dir,
833                      "BasicRunWithCannedPerf",
834                      encodedProfile);
835
836   ASSERT_TRUE(encodedProfile.has_perf_data());
837   const quipper::PerfDataProto& perf_data = encodedProfile.perf_data();
838
839   // Expect 21108 events.
840   EXPECT_EQ(21108, perf_data.events_size()) << CreateStats(perf_data);
841
842   EXPECT_EQ(48,    CountMmapEvents(perf_data)) << CreateStats(perf_data);
843   EXPECT_EQ(19986, CountSampleEvents(perf_data)) << CreateStats(perf_data);
844   EXPECT_EQ(1033,  CountCommEvents(perf_data)) << CreateStats(perf_data);
845   EXPECT_EQ(15,    CountForkEvents(perf_data)) << CreateStats(perf_data);
846   EXPECT_EQ(26,    CountExitEvents(perf_data)) << CreateStats(perf_data);
847
848   if (HasNonfatalFailure()) {
849     FAIL();
850   }
851
852   {
853     MmapEventIterator mmap(perf_data);
854     constexpr std::pair<const char*, uint64_t> kMmapEvents[] = {
855         std::make_pair("[kernel.kallsyms]_text", 0),
856         std::make_pair("/system/lib/libc.so", 3067412480u),
857         std::make_pair("/system/vendor/lib/libdsutils.so", 3069911040u),
858         std::make_pair("/system/lib/libc.so", 3067191296u),
859         std::make_pair("/system/lib/libc++.so", 3069210624u),
860         std::make_pair("/data/dalvik-cache/arm/system@framework@boot.oat", 1900048384u),
861         std::make_pair("/system/lib/libjavacore.so", 2957135872u),
862         std::make_pair("/system/vendor/lib/libqmi_encdec.so", 3006644224u),
863         std::make_pair("/data/dalvik-cache/arm/system@framework@wifi-service.jar@classes.dex",
864                        3010351104u),
865         std::make_pair("/system/lib/libart.so", 3024150528u),
866         std::make_pair("/system/lib/libz.so", 3056410624u),
867         std::make_pair("/system/lib/libicui18n.so", 3057610752u),
868     };
869     for (auto& pair : kMmapEvents) {
870       EXPECT_STREQ(pair.first, mmap->mmap_event().filename().c_str());
871       EXPECT_EQ(pair.second, mmap->mmap_event().start()) << pair.first;
872       ++mmap;
873     }
874   }
875
876   {
877     CommEventIterator comm(perf_data);
878     constexpr const char* kCommEvents[] = {
879         "init", "kthreadd", "ksoftirqd/0", "kworker/u:0H", "migration/0", "khelper",
880         "netns", "modem_notifier", "smd_channel_clo", "smsm_cb_wq", "rpm-smd", "kworker/u:1H",
881     };
882     for (auto str : kCommEvents) {
883       EXPECT_STREQ(str, comm->comm_event().comm().c_str());
884       ++comm;
885     }
886   }
887
888   {
889     SampleEventIterator samples(perf_data);
890     constexpr const char* kSampleEvents[] = {
891         "pid=0 tid=0 ip=3222720196",
892         "pid=0 tid=0 ip=3222910876",
893         "pid=0 tid=0 ip=3222910876",
894         "pid=0 tid=0 ip=3222910876",
895         "pid=0 tid=0 ip=3222910876",
896         "pid=0 tid=0 ip=3222910876",
897         "pid=0 tid=0 ip=3222910876",
898         "pid=3 tid=3 ip=3231975108",
899         "pid=5926 tid=5926 ip=3231964952",
900         "pid=5926 tid=5926 ip=3225342428",
901         "pid=5926 tid=5926 ip=3223841448",
902         "pid=5926 tid=5926 ip=3069807920",
903     };
904     for (auto str : kSampleEvents) {
905       EXPECT_STREQ(str, FormatSampleEvent(samples->sample_event()).c_str());
906       ++samples;
907     }
908
909     // Skip some samples.
910     for (size_t i = 0; i != 5000; ++i) {
911       ++samples;
912     }
913     constexpr const char* kSampleEvents2[] = {
914         "pid=5938 tid=5938 ip=3069630992",
915         "pid=5938 tid=5938 ip=3069626616",
916         "pid=5938 tid=5938 ip=3069626636",
917         "pid=5938 tid=5938 ip=3069637212",
918         "pid=5938 tid=5938 ip=3069637208",
919         "pid=5938 tid=5938 ip=3069637252",
920         "pid=5938 tid=5938 ip=3069346040",
921         "pid=5938 tid=5938 ip=3069637128",
922         "pid=5938 tid=5938 ip=3069626616",
923     };
924     for (auto str : kSampleEvents2) {
925       EXPECT_STREQ(str, FormatSampleEvent(samples->sample_event()).c_str());
926       ++samples;
927     }
928
929     // Skip some samples.
930     for (size_t i = 0; i != 5000; ++i) {
931       ++samples;
932     }
933     constexpr const char* kSampleEvents3[] = {
934         "pid=5938 tid=5938 ip=3069912036",
935         "pid=5938 tid=5938 ip=3069637260",
936         "pid=5938 tid=5938 ip=3069631024",
937         "pid=5938 tid=5938 ip=3069346064",
938         "pid=5938 tid=5938 ip=3069637356",
939         "pid=5938 tid=5938 ip=3069637144",
940         "pid=5938 tid=5938 ip=3069912036",
941         "pid=5938 tid=5938 ip=3069912036",
942         "pid=5938 tid=5938 ip=3069631244",
943     };
944     for (auto str : kSampleEvents3) {
945       EXPECT_STREQ(str, FormatSampleEvent(samples->sample_event()).c_str());
946       ++samples;
947     }
948   }
949 }
950
951 TEST_F(PerfProfdTest, DISABLED_BasicRunWithCannedPerfWithSymbolizer)
952 {
953   //
954   // Verify the portion of the daemon that reads and encodes
955   // perf.data files. Here we run the encoder on a canned perf.data
956   // file and verify that the resulting protobuf contains what
957   // we think it should contain.
958   //
959   std::string input_perf_data(test_dir);
960   input_perf_data += "/canned.perf.data";
961
962   // Set up config to avoid these annotations (they are tested elsewhere)
963   ConfigReader config_reader;
964   config_reader.overrideUnsignedEntry("collect_cpu_utilization", 0);
965   config_reader.overrideUnsignedEntry("collect_charging_state", 0);
966   config_reader.overrideUnsignedEntry("collect_camera_active", 0);
967   PerfProfdRunner::LoggingConfig config;
968   config_reader.FillConfig(&config);
969
970   // Kick off encoder and check return code
971   struct TestSymbolizer : public perfprofd::Symbolizer {
972     std::string Decode(const std::string& dso, uint64_t address) override {
973       return dso + "@" + std::to_string(address);
974     }
975   };
976   TestSymbolizer test_symbolizer;
977   PROFILE_RESULT result =
978       encode_to_proto(input_perf_data,
979                       encoded_file_path(dest_dir, 0).c_str(),
980                       config,
981                       0,
982                       &test_symbolizer);
983   ASSERT_EQ(OK_PROFILE_COLLECTION, result);
984
985   // Read and decode the resulting perf.data.encoded file
986   android::perfprofd::PerfprofdRecord encodedProfile;
987   readEncodedProfile(dest_dir,
988                      "BasicRunWithCannedPerf",
989                      encodedProfile);
990
991   ASSERT_TRUE(encodedProfile.has_perf_data());
992   const quipper::PerfDataProto& perf_data = encodedProfile.perf_data();
993
994   // Expect 21108 events.
995   EXPECT_EQ(21108, perf_data.events_size()) << CreateStats(perf_data);
996
997   // TODO: Re-add symbolization.
998 }
999
1000 TEST_F(PerfProfdTest, CallchainRunWithCannedPerf)
1001 {
1002   // This test makes sure that the perf.data converter
1003   // can handle call chains.
1004   //
1005   std::string input_perf_data(test_dir);
1006   input_perf_data += "/callchain.canned.perf.data";
1007
1008   // Set up config to avoid these annotations (they are tested elsewhere)
1009   ConfigReader config_reader;
1010   config_reader.overrideUnsignedEntry("collect_cpu_utilization", 0);
1011   config_reader.overrideUnsignedEntry("collect_charging_state", 0);
1012   config_reader.overrideUnsignedEntry("collect_camera_active", 0);
1013   PerfProfdRunner::LoggingConfig config;
1014   config_reader.FillConfig(&config);
1015
1016   // Kick off encoder and check return code
1017   PROFILE_RESULT result =
1018       encode_to_proto(input_perf_data, encoded_file_path(dest_dir, 0).c_str(), config, 0, nullptr);
1019   ASSERT_EQ(OK_PROFILE_COLLECTION, result);
1020
1021   // Read and decode the resulting perf.data.encoded file
1022   android::perfprofd::PerfprofdRecord encodedProfile;
1023   readEncodedProfile(dest_dir,
1024                      "BasicRunWithCannedPerf",
1025                      encodedProfile);
1026
1027
1028   ASSERT_TRUE(encodedProfile.has_perf_data());
1029   const quipper::PerfDataProto& perf_data = encodedProfile.perf_data();
1030
1031   // Expect 21108 events.
1032   EXPECT_EQ(2224, perf_data.events_size()) << CreateStats(perf_data);
1033
1034   {
1035       SampleEventIterator samples(perf_data);
1036       constexpr const char* kSampleEvents[] = {
1037           "0: pid=6225 tid=6225 ip=18446743798834668032 callchain=->18446744073709551488->"
1038               "18446743798834668032->18446743798834782596->18446743798834784624->"
1039               "18446743798835055136->18446743798834788016->18446743798834789192->"
1040               "18446743798834789512->18446743798834790216->18446743798833756776",
1041           "1: pid=6225 tid=6225 ip=18446743798835685700 callchain=->18446744073709551488->"
1042               "18446743798835685700->18446743798835688704->18446743798835650964->"
1043               "18446743798834612104->18446743798834612276->18446743798835055528->"
1044               "18446743798834788016->18446743798834789192->18446743798834789512->"
1045               "18446743798834790216->18446743798833756776",
1046           "2: pid=6225 tid=6225 ip=18446743798835055804 callchain=->18446744073709551488->"
1047               "18446743798835055804->18446743798834788016->18446743798834789192->"
1048               "18446743798834789512->18446743798834790216->18446743798833756776",
1049           "3: pid=6225 tid=6225 ip=18446743798835991212 callchain=->18446744073709551488->"
1050               "18446743798835991212->18446743798834491060->18446743798834675572->"
1051               "18446743798834676516->18446743798834612172->18446743798834612276->"
1052               "18446743798835056664->18446743798834788016->18446743798834789192->"
1053               "18446743798834789512->18446743798834790216->18446743798833756776",
1054           "4: pid=6225 tid=6225 ip=18446743798844881108 callchain=->18446744073709551488->"
1055               "18446743798844881108->18446743798834836140->18446743798834846384->"
1056               "18446743798834491100->18446743798834675572->18446743798834676516->"
1057               "18446743798834612172->18446743798834612276->18446743798835056784->"
1058               "18446743798834788016->18446743798834789192->18446743798834789512->"
1059               "18446743798834790216->18446743798833756776",
1060       };
1061       size_t cmp_index = 0;
1062       for (size_t index = 0; samples != samples.end(); ++samples, ++index) {
1063         if (samples->sample_event().callchain_size() > 0) {
1064           std::ostringstream oss;
1065           oss << index << ": " << FormatSampleEvent(samples->sample_event());
1066           EXPECT_STREQ(kSampleEvents[cmp_index], oss.str().c_str());
1067           cmp_index++;
1068           if (cmp_index == arraysize(kSampleEvents)) {
1069             break;
1070           }
1071         }
1072       }
1073   }
1074 }
1075
1076 TEST_F(PerfProfdTest, BasicRunWithLivePerf)
1077 {
1078   //
1079   // Basic test to exercise the main loop of the daemon. It includes
1080   // a live 'perf' run
1081   //
1082   PerfProfdRunner runner(conf_dir);
1083   runner.addToConfig("only_debug_build=0");
1084   std::string ddparam("destination_directory="); ddparam += dest_dir;
1085   runner.addToConfig(ddparam);
1086   std::string cfparam("config_directory="); cfparam += conf_dir;
1087   runner.addToConfig(cfparam);
1088   runner.addToConfig("main_loop_iterations=1");
1089   runner.addToConfig("use_fixed_seed=12345678");
1090   runner.addToConfig("max_unprocessed_profiles=100");
1091   runner.addToConfig("collection_interval=9999");
1092   runner.addToConfig("sample_duration=2");
1093   // Avoid the symbolizer for spurious messages.
1094   runner.addToConfig("use_elf_symbolizer=0");
1095
1096   // Create semaphore file
1097   runner.create_semaphore_file();
1098
1099   // Kick off daemon
1100   int daemon_main_return_code = runner.invoke();
1101
1102   // Check return code from daemon
1103   ASSERT_EQ(0, daemon_main_return_code);
1104
1105   // Read and decode the resulting perf.data.encoded file
1106   android::perfprofd::PerfprofdRecord encodedProfile;
1107   readEncodedProfile(dest_dir, "BasicRunWithLivePerf", encodedProfile);
1108
1109   // Examine what we get back. Since it's a live profile, we can't
1110   // really do much in terms of verifying the contents.
1111   EXPECT_LT(0, encodedProfile.perf_data().events_size());
1112
1113   // Verify log contents
1114   const std::string expected = std::string(
1115       "I: starting Android Wide Profiling daemon ") +
1116       "I: config file path set to " + conf_dir + "/perfprofd.conf " +
1117       RAW_RESULT(
1118       I: random seed set to 12345678
1119       I: sleep 674 seconds
1120       I: initiating profile collection
1121       I: sleep 2 seconds
1122       I: profile collection complete
1123       I: sleep 9325 seconds
1124       I: finishing Android Wide Profiling daemon
1125                                           );
1126   // check to make sure log excerpt matches
1127   CompareLogMessages(expandVars(expected), "BasicRunWithLivePerf", true);
1128 }
1129
1130 TEST_F(PerfProfdTest, MultipleRunWithLivePerf)
1131 {
1132   //
1133   // Basic test to exercise the main loop of the daemon. It includes
1134   // a live 'perf' run
1135   //
1136   PerfProfdRunner runner(conf_dir);
1137   runner.addToConfig("only_debug_build=0");
1138   std::string ddparam("destination_directory="); ddparam += dest_dir;
1139   runner.addToConfig(ddparam);
1140   std::string cfparam("config_directory="); cfparam += conf_dir;
1141   runner.addToConfig(cfparam);
1142   runner.addToConfig("main_loop_iterations=3");
1143   runner.addToConfig("use_fixed_seed=12345678");
1144   runner.addToConfig("collection_interval=9999");
1145   runner.addToConfig("sample_duration=2");
1146   // Avoid the symbolizer for spurious messages.
1147   runner.addToConfig("use_elf_symbolizer=0");
1148   runner.write_processed_file(1, 2);
1149
1150   // Create semaphore file
1151   runner.create_semaphore_file();
1152
1153   // Kick off daemon
1154   int daemon_main_return_code = runner.invoke();
1155
1156   // Check return code from daemon
1157   ASSERT_EQ(0, daemon_main_return_code);
1158
1159   // Read and decode the resulting perf.data.encoded file
1160   android::perfprofd::PerfprofdRecord encodedProfile;
1161   readEncodedProfile(dest_dir, "BasicRunWithLivePerf", encodedProfile);
1162
1163   // Examine what we get back. Since it's a live profile, we can't
1164   // really do much in terms of verifying the contents.
1165   EXPECT_LT(0, encodedProfile.perf_data().events_size());
1166
1167   // Examine that encoded.1 file is removed while encoded.{0|2} exists.
1168   EXPECT_EQ(0, access(encoded_file_path(dest_dir, 0).c_str(), F_OK));
1169   EXPECT_NE(0, access(encoded_file_path(dest_dir, 1).c_str(), F_OK));
1170   EXPECT_EQ(0, access(encoded_file_path(dest_dir, 2).c_str(), F_OK));
1171
1172   // Verify log contents
1173   const std::string expected = std::string(
1174       "I: starting Android Wide Profiling daemon ") +
1175       "I: config file path set to " + conf_dir + "/perfprofd.conf " +
1176       RAW_RESULT(
1177       I: random seed set to 12345678
1178       I: sleep 674 seconds
1179       I: initiating profile collection
1180       I: sleep 2 seconds
1181       I: profile collection complete
1182       I: sleep 9325 seconds
1183       I: sleep 4974 seconds
1184       I: initiating profile collection
1185       I: sleep 2 seconds
1186       I: profile collection complete
1187       I: sleep 5025 seconds
1188       I: sleep 501 seconds
1189       I: initiating profile collection
1190       I: sleep 2 seconds
1191       I: profile collection complete
1192       I: sleep 9498 seconds
1193       I: finishing Android Wide Profiling daemon
1194                                           );
1195   // check to make sure log excerpt matches
1196   CompareLogMessages(expandVars(expected), "BasicRunWithLivePerf", true);
1197 }
1198
1199 TEST_F(PerfProfdTest, CallChainRunWithLivePerf)
1200 {
1201   //
1202   // Collect a callchain profile, so as to exercise the code in
1203   // perf_data post-processing that digests callchains.
1204   //
1205   PerfProfdRunner runner(conf_dir);
1206   std::string ddparam("destination_directory="); ddparam += dest_dir;
1207   runner.addToConfig(ddparam);
1208   std::string cfparam("config_directory="); cfparam += conf_dir;
1209   runner.addToConfig(cfparam);
1210   runner.addToConfig("main_loop_iterations=1");
1211   runner.addToConfig("use_fixed_seed=12345678");
1212   runner.addToConfig("max_unprocessed_profiles=100");
1213   runner.addToConfig("collection_interval=9999");
1214   runner.addToConfig("stack_profile=1");
1215   runner.addToConfig("sample_duration=2");
1216   // Avoid the symbolizer for spurious messages.
1217   runner.addToConfig("use_elf_symbolizer=0");
1218
1219   // Create semaphore file
1220   runner.create_semaphore_file();
1221
1222   // Kick off daemon
1223   int daemon_main_return_code = runner.invoke();
1224
1225   // Check return code from daemon
1226   ASSERT_EQ(0, daemon_main_return_code);
1227
1228   // Read and decode the resulting perf.data.encoded file
1229   android::perfprofd::PerfprofdRecord encodedProfile;
1230   readEncodedProfile(dest_dir, "CallChainRunWithLivePerf", encodedProfile);
1231
1232   // Examine what we get back. Since it's a live profile, we can't
1233   // really do much in terms of verifying the contents.
1234   EXPECT_LT(0, encodedProfile.perf_data().events_size());
1235
1236   // Verify log contents
1237   const std::string expected = std::string(
1238       "I: starting Android Wide Profiling daemon ") +
1239       "I: config file path set to " + conf_dir + "/perfprofd.conf " +
1240       RAW_RESULT(
1241       I: random seed set to 12345678
1242       I: sleep 674 seconds
1243       I: initiating profile collection
1244       I: sleep 2 seconds
1245       I: profile collection complete
1246       I: sleep 9325 seconds
1247       I: finishing Android Wide Profiling daemon
1248                                           );
1249   // check to make sure log excerpt matches
1250   CompareLogMessages(expandVars(expected), "CallChainRunWithLivePerf", true);
1251
1252   // Check that we have at least one SampleEvent with a callchain.
1253   SampleEventIterator samples(encodedProfile.perf_data());
1254   bool found_callchain = false;
1255   while (!found_callchain && samples != samples.end()) {
1256     found_callchain = samples->sample_event().callchain_size() > 0;
1257   }
1258   EXPECT_TRUE(found_callchain) << CreateStats(encodedProfile.perf_data());
1259 }
1260
1261 int main(int argc, char **argv) {
1262   // Always log to cerr, so that device failures are visible.
1263   android::base::SetLogger(android::base::StderrLogger);
1264
1265   CHECK(android::base::Realpath(argv[0], &gExecutableRealpath));
1266
1267   // switch to / before starting testing (perfprofd
1268   // should be location-independent)
1269   chdir("/");
1270   testing::InitGoogleTest(&argc, argv);
1271   return RUN_ALL_TESTS();
1272 }