OSDN Git Service

Perfprofd: Implement symbolization over quipper data
[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/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>
40 #include <zlib.h>
41
42 #include "config.h"
43 #include "configreader.h"
44 #include "map_utils.h"
45 #include "perfprofdcore.h"
46 #include "quipper_helper.h"
47 #include "symbolizer.h"
48
49 #include "perfprofd_record.pb.h"
50
51 using namespace android::perfprofd::quipper;
52
53 static_assert(android::base::kEnableDChecks, "Expected DCHECKs to be enabled");
54
55 //
56 // Set to argv[0] on startup
57 //
58 static std::string gExecutableRealpath;
59
60 namespace {
61
62 using android::base::LogId;
63 using android::base::LogSeverity;
64
65 class TestLogHelper {
66  public:
67   void Install() {
68     using namespace std::placeholders;
69     android::base::SetLogger(
70         std::bind(&TestLogHelper::TestLogFunction, this, _1, _2, _3, _4, _5, _6));
71   }
72
73   std::string JoinTestLog(const char* delimiter) {
74     std::unique_lock<std::mutex> ul(lock_);
75     return android::base::Join(test_log_messages_, delimiter);
76   }
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),
84                  pred);
85     return android::base::Join(tmp, delimiter);
86   }
87
88  private:
89   void TestLogFunction(LogId log_id,
90                        LogSeverity severity,
91                        const char* tag,
92                        const char* file,
93                        unsigned int line,
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));
99
100     if (severity >= LogSeverity::FATAL_WITHOUT_ABORT) {
101       android::base::StderrLogger(log_id, severity, tag, file, line, message);
102     }
103   }
104
105  private:
106   std::mutex lock_;
107
108   std::vector<std::string> test_log_messages_;
109 };
110
111 }  // namespace
112
113 // Path to perf executable on device
114 #define PERFPATH "/system/bin/perf"
115
116 // Temporary config file that we will emit for the daemon to read
117 #define CONFIGFILE "perfprofd.conf"
118
119 static bool bothWhiteSpace(char lhs, char rhs)
120 {
121   return (std::isspace(lhs) && std::isspace(rhs));
122 }
123
124 //
125 // Squeeze out repeated whitespace from expected/actual logs.
126 //
127 static std::string squeezeWhite(const std::string &str,
128                                 const char *tag,
129                                 bool dump=false)
130 {
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())) {
137     result.pop_back();
138   }
139   if (dump) { fprintf(stderr, "squeezed %s is %s\n", tag, result.c_str()); }
140   return result;
141 }
142
143 //
144 // Replace all occurrences of a string with another string.
145 //
146 static std::string replaceAll(const std::string &str,
147                               const std::string &from,
148                               const std::string &to)
149 {
150   std::string ret = "";
151   size_t pos = 0;
152   while (pos < str.size()) {
153     size_t found = str.find(from, pos);
154     if (found == std::string::npos) {
155       ret += str.substr(pos);
156       break;
157     }
158     ret += str.substr(pos, found - pos) + to;
159     pos = found + from.size();
160   }
161   return ret;
162 }
163
164 //
165 // Replace occurrences of special variables in the string.
166 //
167 #ifdef __ANDROID__
168 static std::string expandVars(const std::string &str) {
169 #ifdef __LP64__
170   return replaceAll(str, "$NATIVE_TESTS", "/data/nativetest64");
171 #else
172   return replaceAll(str, "$NATIVE_TESTS", "/data/nativetest");
173 #endif
174 }
175 #endif
176
177 class PerfProfdTest : public testing::Test {
178  protected:
179   virtual void SetUp() {
180     test_logger.Install();
181     create_dirs();
182   }
183
184   virtual void TearDown() {
185     android::base::SetLogger(android::base::StderrLogger);
186
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 ");
190       cmd += *dir;
191       int ret = system(cmd.c_str());
192       CHECK_EQ(0, ret);
193     }
194   }
195
196  protected:
197   //
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)
202   //
203   void CompareLogMessages(const std::string& expected,
204                           const char* testpoint,
205                           bool exactMatch = false) {
206      std::string sqexp = squeezeWhite(expected, "expected");
207
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);
213      };
214      std::string sqact = squeezeWhite(test_logger.JoinTestLog(" ", strip_jit), "actual");
215
216      if (exactMatch) {
217        EXPECT_STREQ(sqexp.c_str(), sqact.c_str());
218      } else {
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";
225          wasFound = false;
226        }
227        EXPECT_TRUE(wasFound);
228      }
229   }
230
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;
234
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;
238
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;
242
243   TestLogHelper test_logger;
244
245  private:
246   void create_dirs() {
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);
252   }
253
254   std::unique_ptr<TemporaryDir> temp_dir1;
255   std::unique_ptr<TemporaryDir> temp_dir2;
256 };
257
258 ///
259 /// Helper class to kick off a run of the perfprofd daemon with a specific
260 /// config file.
261 ///
262 class PerfProfdRunner {
263  public:
264   explicit PerfProfdRunner(const std::string& config_dir)
265       : config_dir_(config_dir)
266   {
267     config_path_ = config_dir + "/" CONFIGFILE;
268   }
269
270   ~PerfProfdRunner()
271   {
272     remove_processed_file();
273   }
274
275   void addToConfig(const std::string &line)
276   {
277     config_text_ += line;
278     config_text_ += "\n";
279   }
280
281   void remove_semaphore_file()
282   {
283     std::string semaphore(config_dir_);
284     semaphore += "/" SEMAPHORE_FILENAME;
285     unlink(semaphore.c_str());
286   }
287
288   void create_semaphore_file()
289   {
290     std::string semaphore(config_dir_);
291     semaphore += "/" SEMAPHORE_FILENAME;
292     close(open(semaphore.c_str(), O_WRONLY|O_CREAT, 0600));
293   }
294
295   void write_processed_file(int start_seq, int end_seq)
296   {
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);
301     }
302     fclose(fp);
303   }
304
305   void remove_processed_file()
306   {
307     std::string processed = config_dir_ + "/" PROCESSED_FILENAME;
308     unlink(processed.c_str());
309   }
310
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";
315     }
316
317     bool IsProfilingEnabled() const override {
318       //
319       // Check for existence of semaphore file in config directory
320       //
321       if (access(config_directory.c_str(), F_OK) == -1) {
322         PLOG(WARNING) << "unable to open config directory " << config_directory;
323         return false;
324       }
325
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) {
330         return false;
331       }
332
333       return true;
334     }
335   };
336
337   int invoke()
338   {
339     static const char *argv[3] = { "perfprofd", "-c", "" };
340     argv[2] = config_path_.c_str();
341
342     writeConfigFile(config_path_, config_text_);
343
344     // execute daemon main
345     LoggingConfig config;
346     return perfprofd_main(3, (char **) argv, &config);
347   }
348
349  private:
350   std::string config_dir_;
351   std::string config_path_;
352   std::string config_text_;
353
354   void writeConfigFile(const std::string &config_path,
355                        const std::string &config_text)
356   {
357     FILE *fp = fopen(config_path.c_str(), "w");
358     ASSERT_TRUE(fp != nullptr);
359     fprintf(fp, "%s\n", config_text.c_str());
360     fclose(fp);
361   }
362 };
363
364 //......................................................................
365
366 static std::string encoded_file_path(const std::string& dest_dir,
367                                      int seq) {
368   return android::base::StringPrintf("%s/perf.data.encoded.%d",
369                                      dest_dir.c_str(), seq);
370 }
371
372 static void readEncodedProfile(const std::string& dest_dir,
373                                bool compressed,
374                                android::perfprofd::PerfprofdRecord& encodedProfile)
375 {
376   struct stat statb;
377   int perf_data_stat_result = stat(encoded_file_path(dest_dir, 0).c_str(), &statb);
378   ASSERT_NE(-1, perf_data_stat_result);
379
380   // read
381   std::string encoded;
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);
387   fclose(ifp);
388
389   // uncompress
390   if (compressed && !encoded.empty()) {
391     z_stream stream;
392     stream.zalloc = Z_NULL;
393     stream.zfree = Z_NULL;
394     stream.opaque = Z_NULL;
395
396     {
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;
402         return;
403       }
404     }
405
406     std::string buf;
407     buf.reserve(2 * encoded.size());
408     stream.avail_in = encoded.size();
409     stream.next_in = reinterpret_cast<Bytef*>(const_cast<char*>(encoded.data()));
410
411     int result;
412     do {
413       uint8_t chunk[1024];
414       stream.next_out = static_cast<Bytef*>(chunk);
415       stream.avail_out = arraysize(chunk);
416
417       result = inflate(&stream, 0);
418       const size_t amount = arraysize(chunk) - stream.avail_out;
419       if (amount > 0) {
420         if (buf.capacity() - buf.size() < amount) {
421           buf.reserve(buf.capacity() + 64u * 1024u);
422           CHECK_LE(amount, buf.capacity() - buf.size());
423         }
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);
427       }
428     } while (result == Z_OK);
429     inflateEnd(&stream);
430     if (result != Z_STREAM_END) {
431       LOG(ERROR) << "Finished with not-Z_STREAM_END " << result;
432       return;
433     }
434     encoded = buf;
435   }
436
437   // decode
438   encodedProfile.ParseFromString(encoded);
439 }
440
441 #define RAW_RESULT(x) #x
442
443 TEST_F(PerfProfdTest, TestUtil)
444 {
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"));
450 }
451
452 TEST_F(PerfProfdTest, MissingGMS)
453 {
454   //
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.
460   //
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");
468
469   // Kick off daemon
470   int daemon_main_return_code = runner.invoke();
471
472   // Check return code from daemon
473   EXPECT_EQ(0, daemon_main_return_code);
474
475   // Verify log contents
476   const std::string expected = RAW_RESULT(
477       I: sleep 90 seconds
478       W: unable to open config directory /does/not/exist: No such file or directory
479       I: profile collection skipped (missing config directory)
480                                           );
481
482   // check to make sure entire log matches
483   CompareLogMessages(expected, "MissingGMS");
484 }
485
486
487 TEST_F(PerfProfdTest, MissingOptInSemaphoreFile)
488 {
489   //
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
494   // up on.
495   //
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");
505
506   runner.remove_semaphore_file();
507
508   // Kick off daemon
509   int daemon_main_return_code = runner.invoke();
510
511   // Check return code from daemon
512   EXPECT_EQ(0, daemon_main_return_code);
513
514   // Verify log contents
515   const std::string expected = RAW_RESULT(
516       I: profile collection skipped (missing config directory)
517                                           );
518   // check to make sure log excerpt matches
519   CompareLogMessages(expected, "MissingOptInSemaphoreFile");
520 }
521
522 TEST_F(PerfProfdTest, MissingPerfExecutable)
523 {
524   //
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.
529   //
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");
541
542   // Create semaphore file
543   runner.create_semaphore_file();
544
545   // Kick off daemon
546   int daemon_main_return_code = runner.invoke();
547
548   // Check return code from daemon
549   EXPECT_EQ(0, daemon_main_return_code);
550
551   // expected log contents
552   const std::string expected = RAW_RESULT(
553       I: profile collection skipped (missing 'perf' executable)
554                                           );
555   // check to make sure log excerpt matches
556   CompareLogMessages(expected, "MissingPerfExecutable");
557 }
558
559 TEST_F(PerfProfdTest, BadPerfRun)
560 {
561   //
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
565   // the error.
566   //
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");
576 #ifdef __ANDROID__
577   runner.addToConfig("perf_path=/system/bin/false");
578 #else
579   runner.addToConfig("perf_path=/bin/false");
580 #endif
581
582   // Create semaphore file
583   runner.create_semaphore_file();
584
585   // Kick off daemon
586   int daemon_main_return_code = runner.invoke();
587
588   // Check return code from daemon
589   EXPECT_EQ(0, daemon_main_return_code);
590
591   // Verify log contents
592   const std::string expected = RAW_RESULT(
593       W: perf bad exit status 1
594       W: profile collection failed
595                                           );
596
597   // check to make sure log excerpt matches
598   CompareLogMessages(expected, "BadPerfRun");
599 }
600
601 TEST_F(PerfProfdTest, ConfigFileParsing)
602 {
603   //
604   // Gracefully handly malformed items in the config file
605   //
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");
612
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");
619
620   // Kick off daemon
621   int daemon_main_return_code = runner.invoke();
622
623   // Check return code from daemon
624   EXPECT_EQ(0, daemon_main_return_code);
625
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)
633                                           );
634
635   // check to make sure log excerpt matches
636   CompareLogMessages(expected, "ConfigFileParsing");
637 }
638
639 TEST_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());
649 #ifdef __ANDROID__
650   EXPECT_TRUE(get_charging());
651 #endif
652   EXPECT_FALSE(get_camera_active());
653 }
654
655 namespace {
656
657 template <typename Iterator>
658 size_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
666 size_t CountCommEvents(const quipper::PerfDataProto& proto) {
667   return CountEvents<CommEventIterator>(proto);
668 }
669 size_t CountMmapEvents(const quipper::PerfDataProto& proto) {
670   return CountEvents<MmapEventIterator>(proto);
671 }
672 size_t CountSampleEvents(const quipper::PerfDataProto& proto) {
673   return CountEvents<SampleEventIterator>(proto);
674 }
675 size_t CountForkEvents(const quipper::PerfDataProto& proto) {
676   return CountEvents<ForkEventIterator>(proto);
677 }
678 size_t CountExitEvents(const quipper::PerfDataProto& proto) {
679   return CountEvents<ExitEventIterator>(proto);
680 }
681
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;
689   return oss.str();
690 }
691
692 std::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
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();
721
722     // Expect 21108 events.
723     EXPECT_EQ(21108, perf_data.events_size()) << CreateStats(perf_data);
724
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);
730
731     if (HasNonfatalFailure()) {
732       FAIL();
733     }
734
735     {
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",
747                          3010351104u),
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),
751       };
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;
755         ++mmap;
756       }
757     }
758
759     {
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",
764       };
765       for (auto str : kCommEvents) {
766         EXPECT_STREQ(str, comm->comm_event().comm().c_str());
767         ++comm;
768       }
769     }
770
771     {
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",
786       };
787       for (auto str : kSampleEvents) {
788         EXPECT_STREQ(str, FormatSampleEvent(samples->sample_event()).c_str());
789         ++samples;
790       }
791
792       // Skip some samples.
793       for (size_t i = 0; i != 5000; ++i) {
794         ++samples;
795       }
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",
806       };
807       for (auto str : kSampleEvents2) {
808         EXPECT_STREQ(str, FormatSampleEvent(samples->sample_event()).c_str());
809         ++samples;
810       }
811
812       // Skip some samples.
813       for (size_t i = 0; i != 5000; ++i) {
814         ++samples;
815       }
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",
826       };
827       for (auto str : kSampleEvents3) {
828         EXPECT_STREQ(str, FormatSampleEvent(samples->sample_event()).c_str());
829         ++samples;
830       }
831     }
832   }
833 };
834
835 TEST_F(BasicRunWithCannedPerf, Basic)
836 {
837   //
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.
842   //
843   std::string input_perf_data(test_dir);
844   input_perf_data += "/canned.perf.data";
845
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);
851
852   // Disable compression.
853   config_reader.overrideUnsignedEntry("compress", 0);
854
855   PerfProfdRunner::LoggingConfig config;
856   config_reader.FillConfig(&config);
857
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(" ");
862
863   // Read and decode the resulting perf.data.encoded file
864   android::perfprofd::PerfprofdRecord encodedProfile;
865   readEncodedProfile(dest_dir, false, encodedProfile);
866
867   VerifyBasicCannedProfile(encodedProfile);
868 }
869
870 TEST_F(BasicRunWithCannedPerf, Compressed)
871 {
872   //
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.
877   //
878   std::string input_perf_data(test_dir);
879   input_perf_data += "/canned.perf.data";
880
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);
886
887   // Enable compression.
888   config_reader.overrideUnsignedEntry("compress", 1);
889
890   PerfProfdRunner::LoggingConfig config;
891   config_reader.FillConfig(&config);
892
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(" ");
897
898   // Read and decode the resulting perf.data.encoded file
899   android::perfprofd::PerfprofdRecord encodedProfile;
900   readEncodedProfile(dest_dir, true, encodedProfile);
901
902   VerifyBasicCannedProfile(encodedProfile);
903 }
904
905 TEST_F(BasicRunWithCannedPerf, WithSymbolizer)
906 {
907   //
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.
912   //
913   std::string input_perf_data(test_dir);
914   input_perf_data += "/canned.perf.data";
915
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);
921
922   // Disable compression.
923   config_reader.overrideUnsignedEntry("compress", 0);
924
925   PerfProfdRunner::LoggingConfig config;
926   config_reader.FillConfig(&config);
927
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);
932     }
933     bool GetMinExecutableVAddr(const std::string& dso, uint64_t* addr) override {
934       *addr = 4096;
935       return true;
936     }
937   };
938   TestSymbolizer test_symbolizer;
939   PROFILE_RESULT result =
940       encode_to_proto(input_perf_data,
941                       encoded_file_path(dest_dir, 0).c_str(),
942                       config,
943                       0,
944                       &test_symbolizer);
945   ASSERT_EQ(OK_PROFILE_COLLECTION, result);
946
947   // Read and decode the resulting perf.data.encoded file
948   android::perfprofd::PerfprofdRecord encodedProfile;
949   readEncodedProfile(dest_dir, false, encodedProfile);
950
951   VerifyBasicCannedProfile(encodedProfile);
952
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) {
957         return &symbol_info;
958       }
959     }
960     return nullptr;
961   };
962   auto all_filenames = [&]() {
963     std::ostringstream oss;
964     for (auto& symbol_info : encodedProfile.symbol_info()) {
965       oss << " " << symbol_info.filename();
966     }
967     return oss.str();
968   };
969
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@"
975                           "classes.dex")
976                   != nullptr) << all_filenames();
977   EXPECT_TRUE(find_symbol("/data/dalvik-cache/arm/system@framework@boot.oat") != nullptr)
978       << all_filenames();
979 }
980
981 TEST_F(PerfProfdTest, CallchainRunWithCannedPerf)
982 {
983   // This test makes sure that the perf.data converter
984   // can handle call chains.
985   //
986   std::string input_perf_data(test_dir);
987   input_perf_data += "/callchain.canned.perf.data";
988
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);
994
995   // Disable compression.
996   config_reader.overrideUnsignedEntry("compress", 0);
997
998   PerfProfdRunner::LoggingConfig config;
999   config_reader.FillConfig(&config);
1000
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);
1005
1006   // Read and decode the resulting perf.data.encoded file
1007   android::perfprofd::PerfprofdRecord encodedProfile;
1008   readEncodedProfile(dest_dir, false, encodedProfile);
1009
1010
1011   ASSERT_TRUE(encodedProfile.has_perf_data());
1012   const quipper::PerfDataProto& perf_data = encodedProfile.perf_data();
1013
1014   // Expect 21108 events.
1015   EXPECT_EQ(2224, perf_data.events_size()) << CreateStats(perf_data);
1016
1017   {
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       }
1056   }
1057 }
1058
1059 #ifdef __ANDROID__
1060
1061 TEST_F(PerfProfdTest, BasicRunWithLivePerf)
1062 {
1063   //
1064   // Basic test to exercise the main loop of the daemon. It includes
1065   // a live 'perf' run
1066   //
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");
1080
1081   // Disable compression.
1082   runner.addToConfig("compress=0");
1083
1084   // 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
1091   ASSERT_EQ(0, daemon_main_return_code);
1092
1093   // Read and decode the resulting perf.data.encoded file
1094   android::perfprofd::PerfprofdRecord encodedProfile;
1095   readEncodedProfile(dest_dir, false, encodedProfile);
1096
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());
1100
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 " +
1105       RAW_RESULT(
1106       I: random seed set to 12345678
1107       I: sleep 674 seconds
1108       I: initiating profile collection
1109       I: sleep 2 seconds
1110       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
1115   CompareLogMessages(expandVars(expected), "BasicRunWithLivePerf", true);
1116 }
1117
1118 TEST_F(PerfProfdTest, MultipleRunWithLivePerf)
1119 {
1120   //
1121   // Basic test to exercise the main loop of the daemon. It includes
1122   // a live 'perf' run
1123   //
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");
1136
1137   // Disable compression.
1138   runner.addToConfig("compress=0");
1139
1140   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
1149   ASSERT_EQ(0, daemon_main_return_code);
1150
1151   // Read and decode the resulting perf.data.encoded file
1152   android::perfprofd::PerfprofdRecord encodedProfile;
1153   readEncodedProfile(dest_dir, false, encodedProfile);
1154
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());
1158
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));
1163
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 " +
1168       RAW_RESULT(
1169       I: random seed set to 12345678
1170       I: sleep 674 seconds
1171       I: initiating profile collection
1172       I: sleep 2 seconds
1173       I: profile collection complete
1174       I: sleep 9325 seconds
1175       I: sleep 4974 seconds
1176       I: initiating profile collection
1177       I: sleep 2 seconds
1178       I: profile collection complete
1179       I: sleep 5025 seconds
1180       I: sleep 501 seconds
1181       I: initiating profile collection
1182       I: sleep 2 seconds
1183       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
1188   CompareLogMessages(expandVars(expected), "BasicRunWithLivePerf", true);
1189 }
1190
1191 TEST_F(PerfProfdTest, CallChainRunWithLivePerf)
1192 {
1193   //
1194   // Collect a callchain profile, so as to exercise the code in
1195   // perf_data post-processing that digests callchains.
1196   //
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");
1210
1211   // Disable compression.
1212   runner.addToConfig("compress=0");
1213
1214   // 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
1221   ASSERT_EQ(0, daemon_main_return_code);
1222
1223   // Read and decode the resulting perf.data.encoded file
1224   android::perfprofd::PerfprofdRecord encodedProfile;
1225   readEncodedProfile(dest_dir, false, encodedProfile);
1226
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());
1230
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 " +
1235       RAW_RESULT(
1236       I: random seed set to 12345678
1237       I: sleep 674 seconds
1238       I: initiating profile collection
1239       I: sleep 2 seconds
1240       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
1245   CompareLogMessages(expandVars(expected), "CallChainRunWithLivePerf", true);
1246
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;
1252   }
1253   EXPECT_TRUE(found_callchain) << CreateStats(encodedProfile.perf_data());
1254 }
1255
1256 #endif
1257
1258 class RangeMapTest : public testing::Test {
1259 };
1260
1261 TEST_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
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);
1303
1304   CHECK(android::base::Realpath(argv[0], &gExecutableRealpath));
1305
1306   // switch to / before starting testing (perfprofd
1307   // should be location-independent)
1308   chdir("/");
1309   testing::InitGoogleTest(&argc, argv);
1310   return RUN_ALL_TESTS();
1311 }