OSDN Git Service

Merge changes Ic5340e95,I94f54ffe,I3bc947a2 am: 07091dc905
[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 <gtest/gtest.h>
18 #include <algorithm>
19 #include <cctype>
20 #include <string>
21 #include <regex>
22 #include <stdio.h>
23 #include <sys/types.h>
24 #include <sys/stat.h>
25 #include <fcntl.h>
26
27 #include <android-base/properties.h>
28 #include <android-base/stringprintf.h>
29
30 #include "config.h"
31 #include "configreader.h"
32 #include "perfprofdcore.h"
33 #include "perfprofdutils.h"
34 #include "perfprofdmockutils.h"
35
36 #include "perf_profile.pb.h"
37 #include "google/protobuf/text_format.h"
38
39 //
40 // Set to argv[0] on startup
41 //
42 static const char *executable_path;
43
44 //
45 // test_dir is the directory containing the test executable and
46 // any files associated with the test (will be created by the harness).
47 //
48 // dest_dir is a subdirectory of test_dir that we'll create on the fly
49 // at the start of each testpoint (into which new files can be written),
50 // then delete at end of testpoint.
51 //
52 static std::string test_dir;
53 static std::string dest_dir;
54
55 // Path to perf executable on device
56 #define PERFPATH "/system/bin/perf"
57
58 // Temporary config file that we will emit for the daemon to read
59 #define CONFIGFILE "perfprofd.conf"
60
61 static std::string encoded_file_path(int seq)
62 {
63   return android::base::StringPrintf("%s/perf.data.encoded.%d",
64                                      dest_dir.c_str(), seq);
65 }
66
67 class PerfProfdTest : public testing::Test {
68  protected:
69   virtual void SetUp() {
70     mock_perfprofdutils_init();
71     create_dest_dir();
72     yesclean();
73   }
74
75   virtual void TearDown() {
76     mock_perfprofdutils_finish();
77   }
78
79   void noclean() {
80     clean_ = false;
81   }
82   void yesclean() {
83     clean_ = true;
84   }
85
86  private:
87   bool clean_;
88
89   void create_dest_dir() {
90     setup_dirs();
91     ASSERT_FALSE(dest_dir == "");
92     if (clean_) {
93       std::string cmd("rm -rf ");
94       cmd += dest_dir;
95       system(cmd.c_str());
96     }
97     std::string cmd("mkdir -p ");
98     cmd += dest_dir;
99     system(cmd.c_str());
100   }
101
102   void setup_dirs()
103   {
104     if (test_dir == "") {
105       ASSERT_TRUE(executable_path != nullptr);
106       std::string s(executable_path);
107       auto found = s.find_last_of('/');
108       test_dir = s.substr(0,found);
109       dest_dir = test_dir;
110       dest_dir += "/tmp";
111     }
112   }
113
114 };
115
116 static bool bothWhiteSpace(char lhs, char rhs)
117 {
118   return (std::isspace(lhs) && std::isspace(rhs));
119 }
120
121 //
122 // Squeeze out repeated whitespace from expected/actual logs.
123 //
124 static std::string squeezeWhite(const std::string &str,
125                                 const char *tag,
126                                 bool dump=false)
127 {
128   if (dump) { fprintf(stderr, "raw %s is %s\n", tag, str.c_str()); }
129   std::string result(str);
130   std::replace(result.begin(), result.end(), '\n', ' ');
131   auto new_end = std::unique(result.begin(), result.end(), bothWhiteSpace);
132   result.erase(new_end, result.end());
133   while (result.begin() != result.end() && std::isspace(*result.rbegin())) {
134     result.pop_back();
135   }
136   if (dump) { fprintf(stderr, "squeezed %s is %s\n", tag, result.c_str()); }
137   return result;
138 }
139
140 //
141 // Replace all occurrences of a string with another string.
142 //
143 static std::string replaceAll(const std::string &str,
144                               const std::string &from,
145                               const std::string &to)
146 {
147   std::string ret = "";
148   size_t pos = 0;
149   while (pos < str.size()) {
150     size_t found = str.find(from, pos);
151     if (found == std::string::npos) {
152       ret += str.substr(pos);
153       break;
154     }
155     ret += str.substr(pos, found - pos) + to;
156     pos = found + from.size();
157   }
158   return ret;
159 }
160
161 //
162 // Replace occurrences of special variables in the string.
163 //
164 static std::string expandVars(const std::string &str) {
165 #ifdef __LP64__
166   return replaceAll(str, "$NATIVE_TESTS", "/data/nativetest64");
167 #else
168   return replaceAll(str, "$NATIVE_TESTS", "/data/nativetest");
169 #endif
170 }
171
172 ///
173 /// Helper class to kick off a run of the perfprofd daemon with a specific
174 /// config file.
175 ///
176 class PerfProfdRunner {
177  public:
178   PerfProfdRunner()
179       : config_path_(test_dir)
180   {
181     config_path_ += "/" CONFIGFILE;
182   }
183
184   ~PerfProfdRunner()
185   {
186     remove_processed_file();
187   }
188
189   void addToConfig(const std::string &line)
190   {
191     config_text_ += line;
192     config_text_ += "\n";
193   }
194
195   void remove_semaphore_file()
196   {
197     std::string semaphore(test_dir);
198     semaphore += "/" SEMAPHORE_FILENAME;
199     unlink(semaphore.c_str());
200   }
201
202   void create_semaphore_file()
203   {
204     std::string semaphore(test_dir);
205     semaphore += "/" SEMAPHORE_FILENAME;
206     close(open(semaphore.c_str(), O_WRONLY|O_CREAT, 0600));
207   }
208
209   void write_processed_file(int start_seq, int end_seq)
210   {
211     std::string processed = test_dir + "/" PROCESSED_FILENAME;
212     FILE *fp = fopen(processed.c_str(), "w");
213     for (int i = start_seq; i < end_seq; i++) {
214       fprintf(fp, "%d\n", i);
215     }
216     fclose(fp);
217   }
218
219   void remove_processed_file()
220   {
221     std::string processed = test_dir + "/" PROCESSED_FILENAME;
222     unlink(processed.c_str());
223   }
224
225   struct LoggingConfig : public Config {
226     void Sleep(size_t seconds) override {
227       // Log sleep calls but don't sleep.
228       perfprofd_log_info("sleep %d seconds", seconds);
229     }
230   };
231
232   int invoke()
233   {
234     static const char *argv[3] = { "perfprofd", "-c", "" };
235     argv[2] = config_path_.c_str();
236
237     writeConfigFile(config_path_, config_text_);
238
239     // execute daemon main
240     LoggingConfig config;
241     return perfprofd_main(3, (char **) argv, &config);
242   }
243
244  private:
245   std::string config_path_;
246   std::string config_text_;
247
248   void writeConfigFile(const std::string &config_path,
249                        const std::string &config_text)
250   {
251     FILE *fp = fopen(config_path.c_str(), "w");
252     ASSERT_TRUE(fp != nullptr);
253     fprintf(fp, "%s\n", config_text.c_str());
254     fclose(fp);
255   }
256 };
257
258 //......................................................................
259
260 static void readEncodedProfile(const char *testpoint,
261                                wireless_android_play_playlog::AndroidPerfProfile &encodedProfile)
262 {
263   struct stat statb;
264   int perf_data_stat_result = stat(encoded_file_path(0).c_str(), &statb);
265   ASSERT_NE(-1, perf_data_stat_result);
266
267   // read
268   std::string encoded;
269   encoded.resize(statb.st_size);
270   FILE *ifp = fopen(encoded_file_path(0).c_str(), "r");
271   ASSERT_NE(nullptr, ifp);
272   size_t items_read = fread((void*) encoded.data(), statb.st_size, 1, ifp);
273   ASSERT_EQ(1, items_read);
274   fclose(ifp);
275
276   // decode
277   encodedProfile.ParseFromString(encoded);
278 }
279
280 static std::string encodedLoadModuleToString(const wireless_android_play_playlog::LoadModule &lm)
281 {
282   std::stringstream ss;
283   ss << "name: \"" << lm.name() << "\"\n";
284   if (lm.build_id() != "") {
285     ss << "build_id: \"" << lm.build_id() << "\"\n";
286   }
287   return ss.str();
288 }
289
290 static std::string encodedModuleSamplesToString(const wireless_android_play_playlog::LoadModuleSamples &mod)
291 {
292   std::stringstream ss;
293
294   ss << "load_module_id: " << mod.load_module_id() << "\n";
295   for (size_t k = 0; k < mod.address_samples_size(); k++) {
296     const auto &sample = mod.address_samples(k);
297     ss << "  address_samples {\n";
298     for (size_t l = 0; l < mod.address_samples(k).address_size();
299          l++) {
300       auto address = mod.address_samples(k).address(l);
301       ss << "    address: " << address << "\n";
302     }
303     ss << "    count: " << sample.count() << "\n";
304     ss << "  }\n";
305   }
306   return ss.str();
307 }
308
309 #define RAW_RESULT(x) #x
310
311 //
312 // Check to see if the log messages emitted by the daemon
313 // match the expected result. By default we use a partial
314 // match, e.g. if we see the expected excerpt anywhere in the
315 // result, it's a match (for exact match, set exact to true)
316 //
317 static void compareLogMessages(const std::string &actual,
318                                const std::string &expected,
319                                const char *testpoint,
320                                bool exactMatch=false)
321 {
322    std::string sqexp = squeezeWhite(expected, "expected");
323    std::string sqact = squeezeWhite(actual, "actual");
324    if (exactMatch) {
325      EXPECT_STREQ(sqexp.c_str(), sqact.c_str());
326    } else {
327      std::size_t foundpos = sqact.find(sqexp);
328      bool wasFound = true;
329      if (foundpos == std::string::npos) {
330        std::cerr << testpoint << ": expected result not found\n";
331        std::cerr << " Actual: \"" << sqact << "\"\n";
332        std::cerr << " Expected: \"" << sqexp << "\"\n";
333        wasFound = false;
334      }
335      EXPECT_TRUE(wasFound);
336    }
337 }
338
339 TEST_F(PerfProfdTest, TestUtil)
340 {
341   EXPECT_EQ("", replaceAll("", "", ""));
342   EXPECT_EQ("zzbc", replaceAll("abc", "a", "zz"));
343   EXPECT_EQ("azzc", replaceAll("abc", "b", "zz"));
344   EXPECT_EQ("abzz", replaceAll("abc", "c", "zz"));
345   EXPECT_EQ("xxyyzz", replaceAll("abc", "abc", "xxyyzz"));
346 }
347
348 TEST_F(PerfProfdTest, MissingGMS)
349 {
350   //
351   // AWP requires cooperation between the daemon and the GMS core
352   // piece. If we're running on a device that has an old or damaged
353   // version of GMS core, then the config directory we're interested in
354   // may not be there. This test insures that the daemon does the
355   // right thing in this case.
356   //
357   PerfProfdRunner runner;
358   runner.addToConfig("only_debug_build=0");
359   runner.addToConfig("trace_config_read=0");
360   runner.addToConfig("config_directory=/does/not/exist");
361   runner.addToConfig("main_loop_iterations=1");
362   runner.addToConfig("use_fixed_seed=1");
363   runner.addToConfig("collection_interval=100");
364
365   // Kick off daemon
366   int daemon_main_return_code = runner.invoke();
367
368   // Check return code from daemon
369   EXPECT_EQ(0, daemon_main_return_code);
370
371   // Verify log contents
372   const std::string expected = RAW_RESULT(
373       I: sleep 90 seconds
374       W: unable to open config directory /does/not/exist: (No such file or directory)
375       I: profile collection skipped (missing config directory)
376                                           );
377
378   // check to make sure entire log matches
379   compareLogMessages(mock_perfprofdutils_getlogged(),
380                      expected, "MissingGMS");
381 }
382
383
384 TEST_F(PerfProfdTest, MissingOptInSemaphoreFile)
385 {
386   //
387   // Android device owners must opt in to "collect and report usage
388   // data" in order for us to be able to collect profiles. The opt-in
389   // check is performed in the GMS core component; if the check
390   // passes, then it creates a semaphore file for the daemon to pick
391   // up on.
392   //
393   PerfProfdRunner runner;
394   runner.addToConfig("only_debug_build=0");
395   std::string cfparam("config_directory="); cfparam += test_dir;
396   runner.addToConfig(cfparam);
397   std::string ddparam("destination_directory="); ddparam += dest_dir;
398   runner.addToConfig(ddparam);
399   runner.addToConfig("main_loop_iterations=1");
400   runner.addToConfig("use_fixed_seed=1");
401   runner.addToConfig("collection_interval=100");
402
403   runner.remove_semaphore_file();
404
405   // Kick off daemon
406   int daemon_main_return_code = runner.invoke();
407
408   // Check return code from daemon
409   EXPECT_EQ(0, daemon_main_return_code);
410
411   // Verify log contents
412   const std::string expected = RAW_RESULT(
413       I: profile collection skipped (missing semaphore file)
414                                           );
415   // check to make sure log excerpt matches
416   compareLogMessages(mock_perfprofdutils_getlogged(),
417                      expected, "MissingOptInSemaphoreFile");
418 }
419
420 TEST_F(PerfProfdTest, MissingPerfExecutable)
421 {
422   //
423   // Perfprofd uses the 'simpleperf' tool to collect profiles
424   // (although this may conceivably change in the future). This test
425   // checks to make sure that if 'simpleperf' is not present we bail out
426   // from collecting profiles.
427   //
428   PerfProfdRunner runner;
429   runner.addToConfig("only_debug_build=0");
430   runner.addToConfig("trace_config_read=1");
431   std::string cfparam("config_directory="); cfparam += test_dir;
432   runner.addToConfig(cfparam);
433   std::string ddparam("destination_directory="); ddparam += dest_dir;
434   runner.addToConfig(ddparam);
435   runner.addToConfig("main_loop_iterations=1");
436   runner.addToConfig("use_fixed_seed=1");
437   runner.addToConfig("collection_interval=100");
438   runner.addToConfig("perf_path=/does/not/exist");
439
440   // Create semaphore file
441   runner.create_semaphore_file();
442
443   // Kick off daemon
444   int daemon_main_return_code = runner.invoke();
445
446   // Check return code from daemon
447   EXPECT_EQ(0, daemon_main_return_code);
448
449   // expected log contents
450   const std::string expected = RAW_RESULT(
451       I: profile collection skipped (missing 'perf' executable)
452                                           );
453   // check to make sure log excerpt matches
454   compareLogMessages(mock_perfprofdutils_getlogged(),
455                      expected, "MissingPerfExecutable");
456 }
457
458 TEST_F(PerfProfdTest, BadPerfRun)
459 {
460   //
461   // Perf tools tend to be tightly coupled with a specific kernel
462   // version -- if things are out of sync perf could fail or
463   // crash. This test makes sure that we detect such a case and log
464   // the error.
465   //
466   PerfProfdRunner runner;
467   runner.addToConfig("only_debug_build=0");
468   std::string cfparam("config_directory="); cfparam += test_dir;
469   runner.addToConfig(cfparam);
470   std::string ddparam("destination_directory="); ddparam += dest_dir;
471   runner.addToConfig(ddparam);
472   runner.addToConfig("main_loop_iterations=1");
473   runner.addToConfig("use_fixed_seed=1");
474   runner.addToConfig("collection_interval=100");
475   runner.addToConfig("perf_path=/system/bin/false");
476
477   // Create semaphore file
478   runner.create_semaphore_file();
479
480   // Kick off daemon
481   int daemon_main_return_code = runner.invoke();
482
483   // Check return code from daemon
484   EXPECT_EQ(0, daemon_main_return_code);
485
486   // Verify log contents
487   const std::string expected = RAW_RESULT(
488       I: profile collection failed (perf record returned bad exit status)
489                                           );
490
491   // check to make sure log excerpt matches
492   compareLogMessages(mock_perfprofdutils_getlogged(),
493                      expected, "BadPerfRun");
494 }
495
496 TEST_F(PerfProfdTest, ConfigFileParsing)
497 {
498   //
499   // Gracefully handly malformed items in the config file
500   //
501   PerfProfdRunner runner;
502   runner.addToConfig("only_debug_build=0");
503   runner.addToConfig("main_loop_iterations=1");
504   runner.addToConfig("collection_interval=100");
505   runner.addToConfig("use_fixed_seed=1");
506   runner.addToConfig("destination_directory=/does/not/exist");
507
508   // assorted bad syntax
509   runner.addToConfig("collection_interval=0");
510   runner.addToConfig("collection_interval=-1");
511   runner.addToConfig("collection_interval=2");
512   runner.addToConfig("nonexistent_key=something");
513   runner.addToConfig("no_equals_stmt");
514
515   // Kick off daemon
516   int daemon_main_return_code = runner.invoke();
517
518   // Check return code from daemon
519   EXPECT_EQ(0, daemon_main_return_code);
520
521   // Verify log contents
522   const std::string expected = RAW_RESULT(
523       W: line 6: specified value 0 for 'collection_interval' outside permitted range [100 4294967295] (ignored)
524       W: line 7: malformed unsigned value (ignored)
525       W: line 8: specified value 2 for 'collection_interval' outside permitted range [100 4294967295] (ignored)
526       W: line 9: unknown option 'nonexistent_key' ignored
527       W: line 10: line malformed (no '=' found)
528                                           );
529
530   // check to make sure log excerpt matches
531   compareLogMessages(mock_perfprofdutils_getlogged(),
532                      expected, "ConfigFileParsing");
533 }
534
535 TEST_F(PerfProfdTest, ProfileCollectionAnnotations)
536 {
537   unsigned util1 = collect_cpu_utilization();
538   EXPECT_LE(util1, 100);
539   EXPECT_GE(util1, 0);
540
541   // NB: expectation is that when we run this test, the device will be
542   // completed booted, will be on charger, and will not have the camera
543   // active.
544   EXPECT_FALSE(get_booting());
545   EXPECT_TRUE(get_charging());
546   EXPECT_FALSE(get_camera_active());
547 }
548
549 TEST_F(PerfProfdTest, BasicRunWithCannedPerf)
550 {
551   //
552   // Verify the portion of the daemon that reads and encodes
553   // perf.data files. Here we run the encoder on a canned perf.data
554   // file and verify that the resulting protobuf contains what
555   // we think it should contain.
556   //
557   std::string input_perf_data(test_dir);
558   input_perf_data += "/canned.perf.data";
559
560   // Set up config to avoid these annotations (they are tested elsewhere)
561   ConfigReader config_reader;
562   config_reader.overrideUnsignedEntry("collect_cpu_utilization", 0);
563   config_reader.overrideUnsignedEntry("collect_charging_state", 0);
564   config_reader.overrideUnsignedEntry("collect_camera_active", 0);
565   PerfProfdRunner::LoggingConfig config;
566   config_reader.FillConfig(&config);
567
568   // Kick off encoder and check return code
569   PROFILE_RESULT result =
570       encode_to_proto(input_perf_data, encoded_file_path(0).c_str(), config, 0);
571   EXPECT_EQ(OK_PROFILE_COLLECTION, result);
572
573   // Read and decode the resulting perf.data.encoded file
574   wireless_android_play_playlog::AndroidPerfProfile encodedProfile;
575   readEncodedProfile("BasicRunWithCannedPerf",
576                      encodedProfile);
577
578   // Expect 45 programs
579   EXPECT_EQ(45, encodedProfile.programs_size());
580
581   // Check a couple of load modules
582   { const auto &lm0 = encodedProfile.load_modules(0);
583     std::string act_lm0 = encodedLoadModuleToString(lm0);
584     std::string sqact0 = squeezeWhite(act_lm0, "actual for lm 0");
585     const std::string expected_lm0 = RAW_RESULT(
586         name: "/data/app/com.google.android.apps.plus-1/lib/arm/libcronet.so"
587                                                 );
588     std::string sqexp0 = squeezeWhite(expected_lm0, "expected_lm0");
589     EXPECT_STREQ(sqexp0.c_str(), sqact0.c_str());
590   }
591   { const auto &lm9 = encodedProfile.load_modules(9);
592     std::string act_lm9 = encodedLoadModuleToString(lm9);
593     std::string sqact9 = squeezeWhite(act_lm9, "actual for lm 9");
594     const std::string expected_lm9 = RAW_RESULT(
595         name: "/system/lib/libandroid_runtime.so" build_id: "8164ed7b3a8b8f5a220d027788922510"
596                                                 );
597     std::string sqexp9 = squeezeWhite(expected_lm9, "expected_lm9");
598     EXPECT_STREQ(sqexp9.c_str(), sqact9.c_str());
599   }
600
601   // Examine some of the samples now
602   { const auto &p1 = encodedProfile.programs(0);
603     const auto &lm1 = p1.modules(0);
604     std::string act_lm1 = encodedModuleSamplesToString(lm1);
605     std::string sqact1 = squeezeWhite(act_lm1, "actual for lm1");
606     const std::string expected_lm1 = RAW_RESULT(
607         load_module_id: 9 address_samples { address: 296100 count: 1 }
608                                                 );
609     std::string sqexp1 = squeezeWhite(expected_lm1, "expected_lm1");
610     EXPECT_STREQ(sqexp1.c_str(), sqact1.c_str());
611   }
612   { const auto &p1 = encodedProfile.programs(2);
613     const auto &lm2 = p1.modules(0);
614     std::string act_lm2 = encodedModuleSamplesToString(lm2);
615     std::string sqact2 = squeezeWhite(act_lm2, "actual for lm2");
616     const std::string expected_lm2 = RAW_RESULT(
617         load_module_id: 2
618         address_samples { address: 28030244 count: 1 }
619         address_samples { address: 29657840 count: 1 }
620                                                 );
621     std::string sqexp2 = squeezeWhite(expected_lm2, "expected_lm2");
622     EXPECT_STREQ(sqexp2.c_str(), sqact2.c_str());
623   }
624 }
625
626 TEST_F(PerfProfdTest, CallchainRunWithCannedPerf)
627 {
628   // This test makes sure that the perf.data converter
629   // can handle call chains.
630   //
631   std::string input_perf_data(test_dir);
632   input_perf_data += "/callchain.canned.perf.data";
633
634   // Set up config to avoid these annotations (they are tested elsewhere)
635   ConfigReader config_reader;
636   config_reader.overrideUnsignedEntry("collect_cpu_utilization", 0);
637   config_reader.overrideUnsignedEntry("collect_charging_state", 0);
638   config_reader.overrideUnsignedEntry("collect_camera_active", 0);
639   PerfProfdRunner::LoggingConfig config;
640   config_reader.FillConfig(&config);
641
642   // Kick off encoder and check return code
643   PROFILE_RESULT result =
644       encode_to_proto(input_perf_data, encoded_file_path(0).c_str(), config, 0);
645   EXPECT_EQ(OK_PROFILE_COLLECTION, result);
646
647   // Read and decode the resulting perf.data.encoded file
648   wireless_android_play_playlog::AndroidPerfProfile encodedProfile;
649   readEncodedProfile("BasicRunWithCannedPerf",
650                      encodedProfile);
651
652
653   // Expect 3 programs 8 load modules
654   EXPECT_EQ(3, encodedProfile.programs_size());
655   EXPECT_EQ(8, encodedProfile.load_modules_size());
656
657   // Check a couple of load modules
658   { const auto &lm0 = encodedProfile.load_modules(0);
659     std::string act_lm0 = encodedLoadModuleToString(lm0);
660     std::string sqact0 = squeezeWhite(act_lm0, "actual for lm 0");
661     const std::string expected_lm0 = RAW_RESULT(
662         name: "/system/bin/dex2oat"
663         build_id: "ee12bd1a1de39422d848f249add0afc4"
664                                                 );
665     std::string sqexp0 = squeezeWhite(expected_lm0, "expected_lm0");
666     EXPECT_STREQ(sqexp0.c_str(), sqact0.c_str());
667   }
668   { const auto &lm1 = encodedProfile.load_modules(1);
669     std::string act_lm1 = encodedLoadModuleToString(lm1);
670     std::string sqact1 = squeezeWhite(act_lm1, "actual for lm 1");
671     const std::string expected_lm1 = RAW_RESULT(
672         name: "/system/bin/linker"
673         build_id: "a36715f673a4a0aa76ef290124c516cc"
674                                                 );
675     std::string sqexp1 = squeezeWhite(expected_lm1, "expected_lm1");
676     EXPECT_STREQ(sqexp1.c_str(), sqact1.c_str());
677   }
678
679   // Examine some of the samples now
680   { const auto &p0 = encodedProfile.programs(0);
681     const auto &lm1 = p0.modules(0);
682     std::string act_lm1 = encodedModuleSamplesToString(lm1);
683     std::string sqact1 = squeezeWhite(act_lm1, "actual for lm1");
684     const std::string expected_lm1 = RAW_RESULT(
685         load_module_id: 0
686         address_samples { address: 108552 count: 2 }
687                                                 );
688     std::string sqexp1 = squeezeWhite(expected_lm1, "expected_lm1");
689     EXPECT_STREQ(sqexp1.c_str(), sqact1.c_str());
690   }
691   { const auto &p4 = encodedProfile.programs(2);
692     const auto &lm2 = p4.modules(1);
693     std::string act_lm2 = encodedModuleSamplesToString(lm2);
694     std::string sqact2 = squeezeWhite(act_lm2, "actual for lm2");
695     const std::string expected_lm2 = RAW_RESULT(
696         load_module_id: 2 address_samples { address: 403913 count: 1 } address_samples { address: 840761 count: 1 } address_samples { address: 846481 count: 1 } address_samples { address: 999053 count: 1 } address_samples { address: 1012959 count: 1 } address_samples { address: 1524309 count: 1 } address_samples { address: 1580779 count: 1 } address_samples { address: 4287986288 count: 1 }
697                                                 );
698     std::string sqexp2 = squeezeWhite(expected_lm2, "expected_lm2");
699     EXPECT_STREQ(sqexp2.c_str(), sqact2.c_str());
700   }
701 }
702
703 TEST_F(PerfProfdTest, BasicRunWithLivePerf)
704 {
705   //
706   // Basic test to exercise the main loop of the daemon. It includes
707   // a live 'perf' run
708   //
709   PerfProfdRunner runner;
710   runner.addToConfig("only_debug_build=0");
711   std::string ddparam("destination_directory="); ddparam += dest_dir;
712   runner.addToConfig(ddparam);
713   std::string cfparam("config_directory="); cfparam += test_dir;
714   runner.addToConfig(cfparam);
715   runner.addToConfig("main_loop_iterations=1");
716   runner.addToConfig("use_fixed_seed=12345678");
717   runner.addToConfig("max_unprocessed_profiles=100");
718   runner.addToConfig("collection_interval=9999");
719   runner.addToConfig("sample_duration=2");
720
721   // Create semaphore file
722   runner.create_semaphore_file();
723
724   // Kick off daemon
725   int daemon_main_return_code = runner.invoke();
726
727   // Check return code from daemon
728   EXPECT_EQ(0, daemon_main_return_code);
729
730   // Read and decode the resulting perf.data.encoded file
731   wireless_android_play_playlog::AndroidPerfProfile encodedProfile;
732   readEncodedProfile("BasicRunWithLivePerf", encodedProfile);
733
734   // Examine what we get back. Since it's a live profile, we can't
735   // really do much in terms of verifying the contents.
736   EXPECT_LT(0, encodedProfile.programs_size());
737
738   // Verify log contents
739   const std::string expected = RAW_RESULT(
740       I: starting Android Wide Profiling daemon
741       I: config file path set to $NATIVE_TESTS/perfprofd_test/perfprofd.conf
742       I: random seed set to 12345678
743       I: sleep 674 seconds
744       I: initiating profile collection
745       I: profile collection complete
746       I: sleep 9325 seconds
747       I: finishing Android Wide Profiling daemon
748                                           );
749   // check to make sure log excerpt matches
750   compareLogMessages(mock_perfprofdutils_getlogged(),
751                      expandVars(expected), "BasicRunWithLivePerf", true);
752 }
753
754 TEST_F(PerfProfdTest, MultipleRunWithLivePerf)
755 {
756   //
757   // Basic test to exercise the main loop of the daemon. It includes
758   // a live 'perf' run
759   //
760   PerfProfdRunner runner;
761   runner.addToConfig("only_debug_build=0");
762   std::string ddparam("destination_directory="); ddparam += dest_dir;
763   runner.addToConfig(ddparam);
764   std::string cfparam("config_directory="); cfparam += test_dir;
765   runner.addToConfig(cfparam);
766   runner.addToConfig("main_loop_iterations=3");
767   runner.addToConfig("use_fixed_seed=12345678");
768   runner.addToConfig("collection_interval=9999");
769   runner.addToConfig("sample_duration=2");
770   runner.write_processed_file(1, 2);
771
772   // Create semaphore file
773   runner.create_semaphore_file();
774
775   // Kick off daemon
776   int daemon_main_return_code = runner.invoke();
777
778   // Check return code from daemon
779   EXPECT_EQ(0, daemon_main_return_code);
780
781   // Read and decode the resulting perf.data.encoded file
782   wireless_android_play_playlog::AndroidPerfProfile encodedProfile;
783   readEncodedProfile("BasicRunWithLivePerf", encodedProfile);
784
785   // Examine what we get back. Since it's a live profile, we can't
786   // really do much in terms of verifying the contents.
787   EXPECT_LT(0, encodedProfile.programs_size());
788
789   // Examine that encoded.1 file is removed while encoded.{0|2} exists.
790   EXPECT_EQ(0, access(encoded_file_path(0).c_str(), F_OK));
791   EXPECT_NE(0, access(encoded_file_path(1).c_str(), F_OK));
792   EXPECT_EQ(0, access(encoded_file_path(2).c_str(), F_OK));
793
794   // Verify log contents
795   const std::string expected = RAW_RESULT(
796       I: starting Android Wide Profiling daemon
797       I: config file path set to $NATIVE_TESTS/perfprofd_test/perfprofd.conf
798       I: random seed set to 12345678
799       I: sleep 674 seconds
800       I: initiating profile collection
801       I: profile collection complete
802       I: sleep 9325 seconds
803       I: sleep 4974 seconds
804       I: initiating profile collection
805       I: profile collection complete
806       I: sleep 5025 seconds
807       I: sleep 501 seconds
808       I: initiating profile collection
809       I: profile collection complete
810       I: sleep 9498 seconds
811       I: finishing Android Wide Profiling daemon
812                                           );
813   // check to make sure log excerpt matches
814   compareLogMessages(mock_perfprofdutils_getlogged(),
815                      expandVars(expected), "BasicRunWithLivePerf", true);
816 }
817
818 TEST_F(PerfProfdTest, CallChainRunWithLivePerf)
819 {
820   //
821   // Collect a callchain profile, so as to exercise the code in
822   // perf_data post-processing that digests callchains.
823   //
824   PerfProfdRunner runner;
825   std::string ddparam("destination_directory="); ddparam += dest_dir;
826   runner.addToConfig(ddparam);
827   std::string cfparam("config_directory="); cfparam += test_dir;
828   runner.addToConfig(cfparam);
829   runner.addToConfig("main_loop_iterations=1");
830   runner.addToConfig("use_fixed_seed=12345678");
831   runner.addToConfig("max_unprocessed_profiles=100");
832   runner.addToConfig("collection_interval=9999");
833   runner.addToConfig("stack_profile=1");
834   runner.addToConfig("sample_duration=2");
835
836   // Create semaphore file
837   runner.create_semaphore_file();
838
839   // Kick off daemon
840   int daemon_main_return_code = runner.invoke();
841
842   // Check return code from daemon
843   EXPECT_EQ(0, daemon_main_return_code);
844
845   // Read and decode the resulting perf.data.encoded file
846   wireless_android_play_playlog::AndroidPerfProfile encodedProfile;
847   readEncodedProfile("CallChainRunWithLivePerf", encodedProfile);
848
849   // Examine what we get back. Since it's a live profile, we can't
850   // really do much in terms of verifying the contents.
851   EXPECT_LT(0, encodedProfile.programs_size());
852
853   // Verify log contents
854   const std::string expected = RAW_RESULT(
855       I: starting Android Wide Profiling daemon
856       I: config file path set to $NATIVE_TESTS/perfprofd_test/perfprofd.conf
857       I: random seed set to 12345678
858       I: sleep 674 seconds
859       I: initiating profile collection
860       I: profile collection complete
861       I: sleep 9325 seconds
862       I: finishing Android Wide Profiling daemon
863                                           );
864   // check to make sure log excerpt matches
865   compareLogMessages(mock_perfprofdutils_getlogged(),
866                      expandVars(expected), "CallChainRunWithLivePerf", true);
867 }
868
869 int main(int argc, char **argv) {
870   executable_path = argv[0];
871   // switch to / before starting testing (perfprofd
872   // should be location-independent)
873   chdir("/");
874   testing::InitGoogleTest(&argc, argv);
875   return RUN_ALL_TESTS();
876 }