blob: 467bea4dfde3a605ef5999921a04c9c58ad977d1 [file] [log] [blame]
Than McIntosh7e2f4e92015-03-05 11:05:02 -05001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Than McIntosh7e2f4e92015-03-05 11:05:02 -050017#include <algorithm>
18#include <cctype>
Andreas Gampe54237f82018-01-18 21:20:36 -080019#include <functional>
Andreas Gampe0c09e0e2018-03-13 16:04:01 -070020#include <iterator>
Andreas Gampe32695342018-01-03 22:28:18 -080021#include <memory>
Andreas Gampe54237f82018-01-18 21:20:36 -080022#include <mutex>
Than McIntosh7e2f4e92015-03-05 11:05:02 -050023#include <regex>
Andreas Gampe32695342018-01-03 22:28:18 -080024#include <string>
25
26#include <fcntl.h>
Than McIntosh7e2f4e92015-03-05 11:05:02 -050027#include <stdio.h>
Andreas Gampe32695342018-01-03 22:28:18 -080028#include <libgen.h>
Than McIntosh7e2f4e92015-03-05 11:05:02 -050029#include <sys/types.h>
30#include <sys/stat.h>
Than McIntosh7e2f4e92015-03-05 11:05:02 -050031
Andreas Gampe32695342018-01-03 22:28:18 -080032#include <android-base/file.h>
33#include <android-base/logging.h>
Andreas Gamped9084f62018-01-10 11:37:20 -080034#include <android-base/macros.h>
Elliott Hughes66dd09e2015-12-04 14:00:57 -080035#include <android-base/stringprintf.h>
Andreas Gamped9084f62018-01-10 11:37:20 -080036#include <android-base/strings.h>
Andreas Gampe32695342018-01-03 22:28:18 -080037#include <android-base/test_utils.h>
Andreas Gampe54237f82018-01-18 21:20:36 -080038#include <android-base/thread_annotations.h>
Andreas Gampe32695342018-01-03 22:28:18 -080039#include <gtest/gtest.h>
Andreas Gampe894b3f92018-03-22 19:48:48 -070040#include <zlib.h>
Dehao Chenf4605012015-05-07 13:16:35 -070041
Andreas Gampee44ae142017-12-21 10:02:23 -080042#include "config.h"
Than McIntosh8c7c7db2015-09-03 15:16:04 -040043#include "configreader.h"
Andreas Gampecbc02bc2018-03-21 16:05:26 -070044#include "map_utils.h"
Andreas Gampee44ae142017-12-21 10:02:23 -080045#include "perfprofdcore.h"
Andreas Gampe04672dd2018-03-28 14:28:18 -070046#include "perfprofd_cmdline.h"
Andreas Gampeb019ddc2018-04-02 10:58:32 -070047#include "perfprofd_threaded_handler.h"
Andreas Gampe77ca78a2018-03-21 16:02:02 -070048#include "quipper_helper.h"
Andreas Gampef9a35612018-01-04 14:22:50 -080049#include "symbolizer.h"
Than McIntosh7e2f4e92015-03-05 11:05:02 -050050
Andreas Gampe0c09e0e2018-03-13 16:04:01 -070051#include "perfprofd_record.pb.h"
Than McIntosh7e2f4e92015-03-05 11:05:02 -050052
Andreas Gampe77ca78a2018-03-21 16:02:02 -070053using namespace android::perfprofd::quipper;
54
Andreas Gampeb5c37092018-03-22 20:25:33 -070055static_assert(android::base::kEnableDChecks, "Expected DCHECKs to be enabled");
56
Than McIntosh7e2f4e92015-03-05 11:05:02 -050057//
58// Set to argv[0] on startup
59//
Andreas Gampe32695342018-01-03 22:28:18 -080060static std::string gExecutableRealpath;
Than McIntosh7e2f4e92015-03-05 11:05:02 -050061
Andreas Gamped9084f62018-01-10 11:37:20 -080062namespace {
63
64using android::base::LogId;
65using android::base::LogSeverity;
66
Andreas Gampe54237f82018-01-18 21:20:36 -080067class TestLogHelper {
68 public:
69 void Install() {
70 using namespace std::placeholders;
71 android::base::SetLogger(
72 std::bind(&TestLogHelper::TestLogFunction, this, _1, _2, _3, _4, _5, _6));
73 }
Andreas Gamped9084f62018-01-10 11:37:20 -080074
Andreas Gampe54237f82018-01-18 21:20:36 -080075 std::string JoinTestLog(const char* delimiter) {
76 std::unique_lock<std::mutex> ul(lock_);
77 return android::base::Join(test_log_messages_, delimiter);
78 }
Andreas Gampe0c09e0e2018-03-13 16:04:01 -070079 template <typename Predicate>
80 std::string JoinTestLog(const char* delimiter, Predicate pred) {
81 std::unique_lock<std::mutex> ul(lock_);
82 std::vector<std::string> tmp;
83 std::copy_if(test_log_messages_.begin(),
84 test_log_messages_.end(),
85 std::back_inserter(tmp),
86 pred);
87 return android::base::Join(tmp, delimiter);
88 }
Andreas Gamped9084f62018-01-10 11:37:20 -080089
Andreas Gampe54237f82018-01-18 21:20:36 -080090 private:
Andreas Gampecbc02bc2018-03-21 16:05:26 -070091 void TestLogFunction(LogId log_id,
Andreas Gampe54237f82018-01-18 21:20:36 -080092 LogSeverity severity,
93 const char* tag,
Andreas Gampecbc02bc2018-03-21 16:05:26 -070094 const char* file,
95 unsigned int line,
Andreas Gampe54237f82018-01-18 21:20:36 -080096 const char* message) {
97 std::unique_lock<std::mutex> ul(lock_);
98 constexpr char log_characters[] = "VDIWEFF";
99 char severity_char = log_characters[severity];
100 test_log_messages_.push_back(android::base::StringPrintf("%c: %s", severity_char, message));
Andreas Gampecbc02bc2018-03-21 16:05:26 -0700101
102 if (severity >= LogSeverity::FATAL_WITHOUT_ABORT) {
103 android::base::StderrLogger(log_id, severity, tag, file, line, message);
104 }
Andreas Gampe54237f82018-01-18 21:20:36 -0800105 }
106
107 private:
108 std::mutex lock_;
109
110 std::vector<std::string> test_log_messages_;
111};
Andreas Gamped9084f62018-01-10 11:37:20 -0800112
113} // namespace
114
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500115// Path to perf executable on device
116#define PERFPATH "/system/bin/perf"
117
118// Temporary config file that we will emit for the daemon to read
119#define CONFIGFILE "perfprofd.conf"
120
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500121static bool bothWhiteSpace(char lhs, char rhs)
122{
123 return (std::isspace(lhs) && std::isspace(rhs));
124}
125
126//
127// Squeeze out repeated whitespace from expected/actual logs.
128//
129static std::string squeezeWhite(const std::string &str,
130 const char *tag,
131 bool dump=false)
132{
133 if (dump) { fprintf(stderr, "raw %s is %s\n", tag, str.c_str()); }
134 std::string result(str);
Alexey Alexandrova5cbb7a2016-09-24 17:05:28 -0700135 std::replace(result.begin(), result.end(), '\n', ' ');
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500136 auto new_end = std::unique(result.begin(), result.end(), bothWhiteSpace);
137 result.erase(new_end, result.end());
138 while (result.begin() != result.end() && std::isspace(*result.rbegin())) {
139 result.pop_back();
140 }
141 if (dump) { fprintf(stderr, "squeezed %s is %s\n", tag, result.c_str()); }
142 return result;
143}
144
Alexey Alexandrova5cbb7a2016-09-24 17:05:28 -0700145//
146// Replace all occurrences of a string with another string.
147//
148static std::string replaceAll(const std::string &str,
149 const std::string &from,
150 const std::string &to)
151{
152 std::string ret = "";
153 size_t pos = 0;
154 while (pos < str.size()) {
155 size_t found = str.find(from, pos);
156 if (found == std::string::npos) {
157 ret += str.substr(pos);
158 break;
159 }
160 ret += str.substr(pos, found - pos) + to;
161 pos = found + from.size();
162 }
163 return ret;
164}
165
166//
167// Replace occurrences of special variables in the string.
168//
Andreas Gampe51389ce2018-03-13 20:55:56 -0700169#ifdef __ANDROID__
Alexey Alexandrova5cbb7a2016-09-24 17:05:28 -0700170static std::string expandVars(const std::string &str) {
171#ifdef __LP64__
172 return replaceAll(str, "$NATIVE_TESTS", "/data/nativetest64");
173#else
174 return replaceAll(str, "$NATIVE_TESTS", "/data/nativetest");
175#endif
176}
Andreas Gampe51389ce2018-03-13 20:55:56 -0700177#endif
Alexey Alexandrova5cbb7a2016-09-24 17:05:28 -0700178
Andreas Gampe54237f82018-01-18 21:20:36 -0800179class PerfProfdTest : public testing::Test {
180 protected:
181 virtual void SetUp() {
182 test_logger.Install();
183 create_dirs();
184 }
185
186 virtual void TearDown() {
187 android::base::SetLogger(android::base::StderrLogger);
188
189 // TODO: proper management of test files. For now, use old system() code.
190 for (const auto dir : { &dest_dir, &conf_dir }) {
191 std::string cmd("rm -rf ");
192 cmd += *dir;
193 int ret = system(cmd.c_str());
194 CHECK_EQ(0, ret);
195 }
196 }
197
198 protected:
199 //
200 // Check to see if the log messages emitted by the daemon
201 // match the expected result. By default we use a partial
202 // match, e.g. if we see the expected excerpt anywhere in the
203 // result, it's a match (for exact match, set exact to true)
204 //
Andreas Gamped0525702018-06-12 09:56:11 -0700205 ::testing::AssertionResult CompareLogMessages(const std::string& expected,
206 bool exactMatch = false) {
Andreas Gampe54237f82018-01-18 21:20:36 -0800207 std::string sqexp = squeezeWhite(expected, "expected");
Andreas Gampe0c09e0e2018-03-13 16:04:01 -0700208
209 // Strip out JIT errors.
210 std::regex jit_regex("E: Failed to open ELF file: [^ ]*ashmem/dalvik-jit-code-cache.*");
211 auto strip_jit = [&](const std::string& str) {
212 std::smatch jit_match;
213 return !std::regex_match(str, jit_match, jit_regex);
214 };
215 std::string sqact = squeezeWhite(test_logger.JoinTestLog(" ", strip_jit), "actual");
216
Andreas Gampe54237f82018-01-18 21:20:36 -0800217 if (exactMatch) {
Andreas Gamped0525702018-06-12 09:56:11 -0700218 if (sqexp == sqact) {
219 return ::testing::AssertionSuccess() << sqexp << " is equal to " << sqact;
Andreas Gampe54237f82018-01-18 21:20:36 -0800220 }
Andreas Gamped0525702018-06-12 09:56:11 -0700221 return ::testing::AssertionFailure() << "Expected:" << std::endl << sqexp << std::endl
222 << "Received:" << std::endl << sqact;
223 } else {
224 if (sqact.find(sqexp) == std::string::npos) {
225 return ::testing::AssertionFailure()
226 << "Expected to find:" << std::endl << sqexp << std::endl
227 << "in:" << std::endl << sqact;
228 }
229 return ::testing::AssertionSuccess() << sqexp << " was found in " << sqact;
Andreas Gampe54237f82018-01-18 21:20:36 -0800230 }
231 }
232
233 // test_dir is the directory containing the test executable and
234 // any files associated with the test (will be created by the harness).
235 std::string test_dir;
236
237 // dest_dir is a temporary directory that we're using as the destination directory.
238 // It is backed by temp_dir1.
239 std::string dest_dir;
240
241 // conf_dir is a temporary directory that we're using as the configuration directory.
242 // It is backed by temp_dir2.
243 std::string conf_dir;
244
245 TestLogHelper test_logger;
246
247 private:
248 void create_dirs() {
249 temp_dir1.reset(new TemporaryDir());
250 temp_dir2.reset(new TemporaryDir());
251 dest_dir = temp_dir1->path;
252 conf_dir = temp_dir2->path;
253 test_dir = android::base::Dirname(gExecutableRealpath);
254 }
255
256 std::unique_ptr<TemporaryDir> temp_dir1;
257 std::unique_ptr<TemporaryDir> temp_dir2;
258};
259
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500260///
261/// Helper class to kick off a run of the perfprofd daemon with a specific
262/// config file.
263///
264class PerfProfdRunner {
265 public:
Andreas Gampe32695342018-01-03 22:28:18 -0800266 explicit PerfProfdRunner(const std::string& config_dir)
267 : config_dir_(config_dir)
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500268 {
Andreas Gampe32695342018-01-03 22:28:18 -0800269 config_path_ = config_dir + "/" CONFIGFILE;
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500270 }
271
272 ~PerfProfdRunner()
273 {
Dehao Chenf4605012015-05-07 13:16:35 -0700274 remove_processed_file();
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500275 }
276
277 void addToConfig(const std::string &line)
278 {
279 config_text_ += line;
280 config_text_ += "\n";
281 }
282
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500283 void remove_semaphore_file()
284 {
Andreas Gampe32695342018-01-03 22:28:18 -0800285 std::string semaphore(config_dir_);
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500286 semaphore += "/" SEMAPHORE_FILENAME;
287 unlink(semaphore.c_str());
288 }
289
290 void create_semaphore_file()
291 {
Andreas Gampe32695342018-01-03 22:28:18 -0800292 std::string semaphore(config_dir_);
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500293 semaphore += "/" SEMAPHORE_FILENAME;
George Burgess IV609b7652017-01-31 22:46:46 -0800294 close(open(semaphore.c_str(), O_WRONLY|O_CREAT, 0600));
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500295 }
296
Dehao Chenf4605012015-05-07 13:16:35 -0700297 void write_processed_file(int start_seq, int end_seq)
298 {
Andreas Gampe32695342018-01-03 22:28:18 -0800299 std::string processed = config_dir_ + "/" PROCESSED_FILENAME;
Dehao Chenf4605012015-05-07 13:16:35 -0700300 FILE *fp = fopen(processed.c_str(), "w");
301 for (int i = start_seq; i < end_seq; i++) {
302 fprintf(fp, "%d\n", i);
303 }
304 fclose(fp);
305 }
306
307 void remove_processed_file()
308 {
Andreas Gampe32695342018-01-03 22:28:18 -0800309 std::string processed = config_dir_ + "/" PROCESSED_FILENAME;
Dehao Chenf4605012015-05-07 13:16:35 -0700310 unlink(processed.c_str());
311 }
312
Andreas Gampe517f4e92017-12-21 10:26:36 -0800313 struct LoggingConfig : public Config {
314 void Sleep(size_t seconds) override {
315 // Log sleep calls but don't sleep.
Andreas Gamped9084f62018-01-10 11:37:20 -0800316 LOG(INFO) << "sleep " << seconds << " seconds";
Andreas Gampe517f4e92017-12-21 10:26:36 -0800317 }
Andreas Gampea3498502017-12-27 11:23:41 -0800318
319 bool IsProfilingEnabled() const override {
320 //
321 // Check for existence of semaphore file in config directory
322 //
323 if (access(config_directory.c_str(), F_OK) == -1) {
Andreas Gamped9084f62018-01-10 11:37:20 -0800324 PLOG(WARNING) << "unable to open config directory " << config_directory;
Andreas Gampea3498502017-12-27 11:23:41 -0800325 return false;
326 }
327
328 // Check for existence of semaphore file
329 std::string semaphore_filepath = config_directory
330 + "/" + SEMAPHORE_FILENAME;
331 if (access(semaphore_filepath.c_str(), F_OK) == -1) {
332 return false;
333 }
334
335 return true;
336 }
Andreas Gampe517f4e92017-12-21 10:26:36 -0800337 };
338
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500339 int invoke()
340 {
341 static const char *argv[3] = { "perfprofd", "-c", "" };
342 argv[2] = config_path_.c_str();
343
344 writeConfigFile(config_path_, config_text_);
Than McIntosh07f00fd2015-04-17 15:10:43 -0400345
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500346 // execute daemon main
Andreas Gampe517f4e92017-12-21 10:26:36 -0800347 LoggingConfig config;
Andreas Gampee44ae142017-12-21 10:02:23 -0800348 return perfprofd_main(3, (char **) argv, &config);
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500349 }
350
351 private:
Andreas Gampe32695342018-01-03 22:28:18 -0800352 std::string config_dir_;
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500353 std::string config_path_;
354 std::string config_text_;
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500355
356 void writeConfigFile(const std::string &config_path,
357 const std::string &config_text)
358 {
359 FILE *fp = fopen(config_path.c_str(), "w");
360 ASSERT_TRUE(fp != nullptr);
361 fprintf(fp, "%s\n", config_text.c_str());
362 fclose(fp);
363 }
364};
365
366//......................................................................
367
Andreas Gampe32695342018-01-03 22:28:18 -0800368static std::string encoded_file_path(const std::string& dest_dir,
369 int seq) {
370 return android::base::StringPrintf("%s/perf.data.encoded.%d",
371 dest_dir.c_str(), seq);
372}
373
374static void readEncodedProfile(const std::string& dest_dir,
Andreas Gampe894b3f92018-03-22 19:48:48 -0700375 bool compressed,
Andreas Gampe0c09e0e2018-03-13 16:04:01 -0700376 android::perfprofd::PerfprofdRecord& encodedProfile)
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500377{
378 struct stat statb;
Andreas Gampe32695342018-01-03 22:28:18 -0800379 int perf_data_stat_result = stat(encoded_file_path(dest_dir, 0).c_str(), &statb);
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500380 ASSERT_NE(-1, perf_data_stat_result);
381
382 // read
383 std::string encoded;
384 encoded.resize(statb.st_size);
Andreas Gampe32695342018-01-03 22:28:18 -0800385 FILE *ifp = fopen(encoded_file_path(dest_dir, 0).c_str(), "r");
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500386 ASSERT_NE(nullptr, ifp);
387 size_t items_read = fread((void*) encoded.data(), statb.st_size, 1, ifp);
388 ASSERT_EQ(1, items_read);
389 fclose(ifp);
390
Andreas Gampe894b3f92018-03-22 19:48:48 -0700391 // uncompress
392 if (compressed && !encoded.empty()) {
393 z_stream stream;
394 stream.zalloc = Z_NULL;
395 stream.zfree = Z_NULL;
396 stream.opaque = Z_NULL;
397
398 {
399 constexpr int kWindowBits = 15;
400 constexpr int kGzipEncoding = 16;
401 int init_result = inflateInit2(&stream, kWindowBits | kGzipEncoding);
402 if (init_result != Z_OK) {
403 LOG(ERROR) << "Could not initialize libz stream " << init_result;
404 return;
405 }
406 }
407
408 std::string buf;
409 buf.reserve(2 * encoded.size());
410 stream.avail_in = encoded.size();
411 stream.next_in = reinterpret_cast<Bytef*>(const_cast<char*>(encoded.data()));
412
413 int result;
414 do {
415 uint8_t chunk[1024];
416 stream.next_out = static_cast<Bytef*>(chunk);
417 stream.avail_out = arraysize(chunk);
418
419 result = inflate(&stream, 0);
420 const size_t amount = arraysize(chunk) - stream.avail_out;
421 if (amount > 0) {
422 if (buf.capacity() - buf.size() < amount) {
423 buf.reserve(buf.capacity() + 64u * 1024u);
424 CHECK_LE(amount, buf.capacity() - buf.size());
425 }
426 size_t index = buf.size();
427 buf.resize(buf.size() + amount);
428 memcpy(reinterpret_cast<uint8_t*>(const_cast<char*>(buf.data())) + index, chunk, amount);
429 }
430 } while (result == Z_OK);
431 inflateEnd(&stream);
432 if (result != Z_STREAM_END) {
433 LOG(ERROR) << "Finished with not-Z_STREAM_END " << result;
434 return;
435 }
436 encoded = buf;
437 }
438
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500439 // decode
440 encodedProfile.ParseFromString(encoded);
Than McIntosh124dd422015-04-29 14:48:32 -0400441}
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500442
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500443#define RAW_RESULT(x) #x
444
Alexey Alexandrova5cbb7a2016-09-24 17:05:28 -0700445TEST_F(PerfProfdTest, TestUtil)
446{
447 EXPECT_EQ("", replaceAll("", "", ""));
448 EXPECT_EQ("zzbc", replaceAll("abc", "a", "zz"));
449 EXPECT_EQ("azzc", replaceAll("abc", "b", "zz"));
450 EXPECT_EQ("abzz", replaceAll("abc", "c", "zz"));
451 EXPECT_EQ("xxyyzz", replaceAll("abc", "abc", "xxyyzz"));
452}
453
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500454TEST_F(PerfProfdTest, MissingGMS)
455{
456 //
457 // AWP requires cooperation between the daemon and the GMS core
458 // piece. If we're running on a device that has an old or damaged
Dehao Chen58bade32015-05-05 15:03:48 -0700459 // version of GMS core, then the config directory we're interested in
460 // may not be there. This test insures that the daemon does the
461 // right thing in this case.
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500462 //
Andreas Gampe32695342018-01-03 22:28:18 -0800463 PerfProfdRunner runner(conf_dir);
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500464 runner.addToConfig("only_debug_build=0");
Than McIntoshf353d8b2015-05-21 14:44:34 -0400465 runner.addToConfig("trace_config_read=0");
Dehao Chen58bade32015-05-05 15:03:48 -0700466 runner.addToConfig("config_directory=/does/not/exist");
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500467 runner.addToConfig("main_loop_iterations=1");
468 runner.addToConfig("use_fixed_seed=1");
469 runner.addToConfig("collection_interval=100");
470
471 // Kick off daemon
472 int daemon_main_return_code = runner.invoke();
473
474 // Check return code from daemon
475 EXPECT_EQ(0, daemon_main_return_code);
476
477 // Verify log contents
478 const std::string expected = RAW_RESULT(
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500479 I: sleep 90 seconds
Andreas Gamped9084f62018-01-10 11:37:20 -0800480 W: unable to open config directory /does/not/exist: No such file or directory
Dehao Chen58bade32015-05-05 15:03:48 -0700481 I: profile collection skipped (missing config directory)
482 );
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500483
484 // check to make sure entire log matches
Andreas Gamped0525702018-06-12 09:56:11 -0700485 EXPECT_TRUE(CompareLogMessages(expected));
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500486}
487
Dehao Chen58bade32015-05-05 15:03:48 -0700488
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500489TEST_F(PerfProfdTest, MissingOptInSemaphoreFile)
490{
491 //
492 // Android device owners must opt in to "collect and report usage
493 // data" in order for us to be able to collect profiles. The opt-in
494 // check is performed in the GMS core component; if the check
495 // passes, then it creates a semaphore file for the daemon to pick
496 // up on.
497 //
Andreas Gampe32695342018-01-03 22:28:18 -0800498 PerfProfdRunner runner(conf_dir);
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500499 runner.addToConfig("only_debug_build=0");
Andreas Gampe32695342018-01-03 22:28:18 -0800500 std::string cfparam("config_directory="); cfparam += conf_dir;
Dehao Chen58bade32015-05-05 15:03:48 -0700501 runner.addToConfig(cfparam);
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500502 std::string ddparam("destination_directory="); ddparam += dest_dir;
503 runner.addToConfig(ddparam);
504 runner.addToConfig("main_loop_iterations=1");
505 runner.addToConfig("use_fixed_seed=1");
506 runner.addToConfig("collection_interval=100");
507
508 runner.remove_semaphore_file();
509
510 // Kick off daemon
511 int daemon_main_return_code = runner.invoke();
512
513 // Check return code from daemon
514 EXPECT_EQ(0, daemon_main_return_code);
515
516 // Verify log contents
517 const std::string expected = RAW_RESULT(
Andreas Gampe44e63a72018-01-03 12:39:53 -0800518 I: profile collection skipped (missing config directory)
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500519 );
520 // check to make sure log excerpt matches
Andreas Gamped0525702018-06-12 09:56:11 -0700521 EXPECT_TRUE(CompareLogMessages(expected));
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500522}
523
524TEST_F(PerfProfdTest, MissingPerfExecutable)
525{
526 //
Than McIntosh07f00fd2015-04-17 15:10:43 -0400527 // Perfprofd uses the 'simpleperf' tool to collect profiles
528 // (although this may conceivably change in the future). This test
529 // checks to make sure that if 'simpleperf' is not present we bail out
530 // from collecting profiles.
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500531 //
Andreas Gampe32695342018-01-03 22:28:18 -0800532 PerfProfdRunner runner(conf_dir);
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500533 runner.addToConfig("only_debug_build=0");
534 runner.addToConfig("trace_config_read=1");
Andreas Gampe32695342018-01-03 22:28:18 -0800535 std::string cfparam("config_directory="); cfparam += conf_dir;
Dehao Chen58bade32015-05-05 15:03:48 -0700536 runner.addToConfig(cfparam);
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500537 std::string ddparam("destination_directory="); ddparam += dest_dir;
538 runner.addToConfig(ddparam);
539 runner.addToConfig("main_loop_iterations=1");
540 runner.addToConfig("use_fixed_seed=1");
541 runner.addToConfig("collection_interval=100");
542 runner.addToConfig("perf_path=/does/not/exist");
543
544 // Create semaphore file
545 runner.create_semaphore_file();
546
547 // Kick off daemon
548 int daemon_main_return_code = runner.invoke();
549
550 // Check return code from daemon
551 EXPECT_EQ(0, daemon_main_return_code);
552
553 // expected log contents
554 const std::string expected = RAW_RESULT(
555 I: profile collection skipped (missing 'perf' executable)
556 );
557 // check to make sure log excerpt matches
Andreas Gamped0525702018-06-12 09:56:11 -0700558 EXPECT_TRUE(CompareLogMessages(expected));
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500559}
560
561TEST_F(PerfProfdTest, BadPerfRun)
562{
563 //
Than McIntosh07f00fd2015-04-17 15:10:43 -0400564 // Perf tools tend to be tightly coupled with a specific kernel
565 // version -- if things are out of sync perf could fail or
566 // crash. This test makes sure that we detect such a case and log
567 // the error.
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500568 //
Andreas Gampe32695342018-01-03 22:28:18 -0800569 PerfProfdRunner runner(conf_dir);
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500570 runner.addToConfig("only_debug_build=0");
Andreas Gampe32695342018-01-03 22:28:18 -0800571 std::string cfparam("config_directory="); cfparam += conf_dir;
Dehao Chen58bade32015-05-05 15:03:48 -0700572 runner.addToConfig(cfparam);
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500573 std::string ddparam("destination_directory="); ddparam += dest_dir;
574 runner.addToConfig(ddparam);
575 runner.addToConfig("main_loop_iterations=1");
576 runner.addToConfig("use_fixed_seed=1");
577 runner.addToConfig("collection_interval=100");
Andreas Gampe51389ce2018-03-13 20:55:56 -0700578#ifdef __ANDROID__
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500579 runner.addToConfig("perf_path=/system/bin/false");
Andreas Gampe51389ce2018-03-13 20:55:56 -0700580#else
581 runner.addToConfig("perf_path=/bin/false");
582#endif
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500583
584 // Create semaphore file
585 runner.create_semaphore_file();
586
587 // Kick off daemon
588 int daemon_main_return_code = runner.invoke();
589
590 // Check return code from daemon
591 EXPECT_EQ(0, daemon_main_return_code);
592
Andreas Gampe36a0b892018-06-12 09:54:42 -0700593 // Verify log contents. Because of perferr logging containing pids and test paths,
594 // it is easier to have three expected parts.
595 const std::string expected1 = "W: perf bad exit status 1";
Andreas Gampe310b08a2018-06-19 10:43:17 -0700596 const std::string expected2 = "bin/false record";
Andreas Gampe36a0b892018-06-12 09:54:42 -0700597 const std::string expected3 = "W: profile collection failed";
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500598
599 // check to make sure log excerpt matches
Andreas Gampe36a0b892018-06-12 09:54:42 -0700600 EXPECT_TRUE(CompareLogMessages(expected1));
601 EXPECT_TRUE(CompareLogMessages(expected2));
602 EXPECT_TRUE(CompareLogMessages(expected3));
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500603}
604
605TEST_F(PerfProfdTest, ConfigFileParsing)
606{
607 //
608 // Gracefully handly malformed items in the config file
609 //
Andreas Gampe32695342018-01-03 22:28:18 -0800610 PerfProfdRunner runner(conf_dir);
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500611 runner.addToConfig("only_debug_build=0");
612 runner.addToConfig("main_loop_iterations=1");
613 runner.addToConfig("collection_interval=100");
614 runner.addToConfig("use_fixed_seed=1");
615 runner.addToConfig("destination_directory=/does/not/exist");
616
617 // assorted bad syntax
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500618 runner.addToConfig("collection_interval=-1");
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500619 runner.addToConfig("nonexistent_key=something");
620 runner.addToConfig("no_equals_stmt");
621
622 // Kick off daemon
623 int daemon_main_return_code = runner.invoke();
624
625 // Check return code from daemon
626 EXPECT_EQ(0, daemon_main_return_code);
627
628 // Verify log contents
629 const std::string expected = RAW_RESULT(
Andreas Gampeac743a32018-05-24 09:43:37 -0700630 W: line 6: specified value 18446744073709551615 for 'collection_interval' outside permitted range [0 4294967295]
631 W: line 7: unknown option 'nonexistent_key'
Andreas Gampe59a18212018-04-30 16:55:15 -0700632 W: line 8: line malformed (no '=' found)
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500633 );
634
635 // check to make sure log excerpt matches
Andreas Gamped0525702018-06-12 09:56:11 -0700636 EXPECT_TRUE(CompareLogMessages(expected));
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500637}
638
Andreas Gampee1eb3cd2018-06-26 10:00:07 -0700639TEST_F(PerfProfdTest, ConfigFileParsing_Events) {
640 auto check_event_config = [](const Config& config,
641 size_t index,
642 const std::vector<std::string>& names,
643 bool group,
644 uint32_t period) {
645 if (config.event_config.size() <= index) {
646 return ::testing::AssertionFailure() << "Not enough entries " << config.event_config.size()
647 << " " << index;
648 }
649 const auto& elem = config.event_config[index];
650
651 if (elem.group != group) {
652 return ::testing::AssertionFailure() << "Type wrong " << elem.group << " " << group;
653 }
654
655 if (elem.sampling_period != period) {
656 return ::testing::AssertionFailure() << "Period wrong " << elem.sampling_period << " "
657 << period;
658 }
659
660 auto strvec = [](const std::vector<std::string>& v) {
661 return "[" + android::base::Join(v, ',') + "]";
662 };
663 if (elem.events.size() != names.size()) {
664 return ::testing::AssertionFailure() << "Names wrong " << strvec(elem.events) << " "
665 << strvec(names);
666 }
667 for (size_t i = 0; i != elem.events.size(); ++i) {
668 if (elem.events[i] != names[i]) {
669 return ::testing::AssertionFailure() << "Names wrong at " << i << ": "
670 << strvec(elem.events) << " "
671 << strvec(names);
672 }
673 }
674 return ::testing::AssertionSuccess();
675 };
676
677 {
678 std::string data = "-e_hello,world=1\n"
679 "-g_foo,bar=2\n"
680 "-e_abc,xyz=3\n"
681 "-g_ftrace:test,ftrace:test2=4";
682
683 ConfigReader reader;
684 std::string error_msg;
685 ASSERT_TRUE(reader.Read(data, true, &error_msg)) << error_msg;
686
687 PerfProfdRunner::LoggingConfig config;
688 reader.FillConfig(&config);
689
690 EXPECT_TRUE(check_event_config(config, 0, { "hello", "world" }, false, 1));
691 EXPECT_TRUE(check_event_config(config, 1, { "foo", "bar" }, true, 2));
692 EXPECT_TRUE(check_event_config(config, 2, { "abc", "xyz" }, false, 3));
693 EXPECT_TRUE(check_event_config(config, 3, { "ftrace:test", "ftrace:test2" }, true, 4));
694 }
695
696 {
697 std::string data = "-e_hello,world=dummy";
698
699 ConfigReader reader;
700 std::string error_msg;
701 EXPECT_FALSE(reader.Read(data, true, &error_msg));
702 }
703
704 {
705 std::string data = "-g_hello,world=dummy";
706
707 ConfigReader reader;
708 std::string error_msg;
709 EXPECT_FALSE(reader.Read(data, true, &error_msg));
710 }
711}
712
Than McIntosh8c7c7db2015-09-03 15:16:04 -0400713TEST_F(PerfProfdTest, ProfileCollectionAnnotations)
714{
715 unsigned util1 = collect_cpu_utilization();
716 EXPECT_LE(util1, 100);
717 EXPECT_GE(util1, 0);
718
719 // NB: expectation is that when we run this test, the device will be
720 // completed booted, will be on charger, and will not have the camera
721 // active.
722 EXPECT_FALSE(get_booting());
Andreas Gampe51389ce2018-03-13 20:55:56 -0700723#ifdef __ANDROID__
Than McIntosh8c7c7db2015-09-03 15:16:04 -0400724 EXPECT_TRUE(get_charging());
Andreas Gampe51389ce2018-03-13 20:55:56 -0700725#endif
Than McIntosh8c7c7db2015-09-03 15:16:04 -0400726 EXPECT_FALSE(get_camera_active());
727}
728
Andreas Gampe0c09e0e2018-03-13 16:04:01 -0700729namespace {
730
Andreas Gampe0c09e0e2018-03-13 16:04:01 -0700731template <typename Iterator>
732size_t CountEvents(const quipper::PerfDataProto& proto) {
733 size_t count = 0;
734 for (Iterator it(proto); it != it.end(); ++it) {
735 count++;
736 }
737 return count;
738}
739
740size_t CountCommEvents(const quipper::PerfDataProto& proto) {
741 return CountEvents<CommEventIterator>(proto);
742}
743size_t CountMmapEvents(const quipper::PerfDataProto& proto) {
744 return CountEvents<MmapEventIterator>(proto);
745}
746size_t CountSampleEvents(const quipper::PerfDataProto& proto) {
747 return CountEvents<SampleEventIterator>(proto);
748}
749size_t CountForkEvents(const quipper::PerfDataProto& proto) {
750 return CountEvents<ForkEventIterator>(proto);
751}
752size_t CountExitEvents(const quipper::PerfDataProto& proto) {
753 return CountEvents<ExitEventIterator>(proto);
754}
755
756std::string CreateStats(const quipper::PerfDataProto& proto) {
757 std::ostringstream oss;
758 oss << "Mmap events: " << CountMmapEvents(proto) << std::endl;
759 oss << "Sample events: " << CountSampleEvents(proto) << std::endl;
760 oss << "Comm events: " << CountCommEvents(proto) << std::endl;
761 oss << "Fork events: " << CountForkEvents(proto) << std::endl;
762 oss << "Exit events: " << CountExitEvents(proto) << std::endl;
763 return oss.str();
764}
765
766std::string FormatSampleEvent(const quipper::PerfDataProto_SampleEvent& sample) {
767 std::ostringstream oss;
768 if (sample.has_pid()) {
769 oss << "pid=" << sample.pid();
770 }
771 if (sample.has_tid()) {
772 oss << " tid=" << sample.tid();
773 }
774 if (sample.has_ip()) {
775 oss << " ip=" << sample.ip();
776 }
777 if (sample.has_addr()) {
778 oss << " addr=" << sample.addr();
779 }
780 if (sample.callchain_size() > 0) {
781 oss << " callchain=";
782 for (uint64_t cc : sample.callchain()) {
783 oss << "->" << cc;
784 }
785 }
786 return oss.str();
787}
788
789}
790
Andreas Gampe894b3f92018-03-22 19:48:48 -0700791struct BasicRunWithCannedPerf : PerfProfdTest {
792 void VerifyBasicCannedProfile(const android::perfprofd::PerfprofdRecord& encodedProfile) {
Andreas Gampe15236cf2018-05-23 10:51:46 -0700793 const quipper::PerfDataProto& perf_data = encodedProfile;
Andreas Gampe894b3f92018-03-22 19:48:48 -0700794
795 // Expect 21108 events.
796 EXPECT_EQ(21108, perf_data.events_size()) << CreateStats(perf_data);
797
798 EXPECT_EQ(48, CountMmapEvents(perf_data)) << CreateStats(perf_data);
799 EXPECT_EQ(19986, CountSampleEvents(perf_data)) << CreateStats(perf_data);
800 EXPECT_EQ(1033, CountCommEvents(perf_data)) << CreateStats(perf_data);
801 EXPECT_EQ(15, CountForkEvents(perf_data)) << CreateStats(perf_data);
802 EXPECT_EQ(26, CountExitEvents(perf_data)) << CreateStats(perf_data);
803
804 if (HasNonfatalFailure()) {
805 FAIL();
806 }
807
808 {
809 MmapEventIterator mmap(perf_data);
810 constexpr std::pair<const char*, uint64_t> kMmapEvents[] = {
811 std::make_pair("[kernel.kallsyms]_text", 0),
812 std::make_pair("/system/lib/libc.so", 3067412480u),
813 std::make_pair("/system/vendor/lib/libdsutils.so", 3069911040u),
814 std::make_pair("/system/lib/libc.so", 3067191296u),
815 std::make_pair("/system/lib/libc++.so", 3069210624u),
816 std::make_pair("/data/dalvik-cache/arm/system@framework@boot.oat", 1900048384u),
817 std::make_pair("/system/lib/libjavacore.so", 2957135872u),
818 std::make_pair("/system/vendor/lib/libqmi_encdec.so", 3006644224u),
819 std::make_pair("/data/dalvik-cache/arm/system@framework@wifi-service.jar@classes.dex",
820 3010351104u),
821 std::make_pair("/system/lib/libart.so", 3024150528u),
822 std::make_pair("/system/lib/libz.so", 3056410624u),
823 std::make_pair("/system/lib/libicui18n.so", 3057610752u),
824 };
825 for (auto& pair : kMmapEvents) {
826 EXPECT_STREQ(pair.first, mmap->mmap_event().filename().c_str());
827 EXPECT_EQ(pair.second, mmap->mmap_event().start()) << pair.first;
828 ++mmap;
829 }
830 }
831
832 {
833 CommEventIterator comm(perf_data);
834 constexpr const char* kCommEvents[] = {
835 "init", "kthreadd", "ksoftirqd/0", "kworker/u:0H", "migration/0", "khelper",
836 "netns", "modem_notifier", "smd_channel_clo", "smsm_cb_wq", "rpm-smd", "kworker/u:1H",
837 };
838 for (auto str : kCommEvents) {
839 EXPECT_STREQ(str, comm->comm_event().comm().c_str());
840 ++comm;
841 }
842 }
843
844 {
845 SampleEventIterator samples(perf_data);
846 constexpr const char* kSampleEvents[] = {
847 "pid=0 tid=0 ip=3222720196",
848 "pid=0 tid=0 ip=3222910876",
849 "pid=0 tid=0 ip=3222910876",
850 "pid=0 tid=0 ip=3222910876",
851 "pid=0 tid=0 ip=3222910876",
852 "pid=0 tid=0 ip=3222910876",
853 "pid=0 tid=0 ip=3222910876",
854 "pid=3 tid=3 ip=3231975108",
855 "pid=5926 tid=5926 ip=3231964952",
856 "pid=5926 tid=5926 ip=3225342428",
857 "pid=5926 tid=5926 ip=3223841448",
858 "pid=5926 tid=5926 ip=3069807920",
859 };
860 for (auto str : kSampleEvents) {
861 EXPECT_STREQ(str, FormatSampleEvent(samples->sample_event()).c_str());
862 ++samples;
863 }
864
865 // Skip some samples.
866 for (size_t i = 0; i != 5000; ++i) {
867 ++samples;
868 }
869 constexpr const char* kSampleEvents2[] = {
870 "pid=5938 tid=5938 ip=3069630992",
871 "pid=5938 tid=5938 ip=3069626616",
872 "pid=5938 tid=5938 ip=3069626636",
873 "pid=5938 tid=5938 ip=3069637212",
874 "pid=5938 tid=5938 ip=3069637208",
875 "pid=5938 tid=5938 ip=3069637252",
876 "pid=5938 tid=5938 ip=3069346040",
877 "pid=5938 tid=5938 ip=3069637128",
878 "pid=5938 tid=5938 ip=3069626616",
879 };
880 for (auto str : kSampleEvents2) {
881 EXPECT_STREQ(str, FormatSampleEvent(samples->sample_event()).c_str());
882 ++samples;
883 }
884
885 // Skip some samples.
886 for (size_t i = 0; i != 5000; ++i) {
887 ++samples;
888 }
889 constexpr const char* kSampleEvents3[] = {
890 "pid=5938 tid=5938 ip=3069912036",
891 "pid=5938 tid=5938 ip=3069637260",
892 "pid=5938 tid=5938 ip=3069631024",
893 "pid=5938 tid=5938 ip=3069346064",
894 "pid=5938 tid=5938 ip=3069637356",
895 "pid=5938 tid=5938 ip=3069637144",
896 "pid=5938 tid=5938 ip=3069912036",
897 "pid=5938 tid=5938 ip=3069912036",
898 "pid=5938 tid=5938 ip=3069631244",
899 };
900 for (auto str : kSampleEvents3) {
901 EXPECT_STREQ(str, FormatSampleEvent(samples->sample_event()).c_str());
902 ++samples;
903 }
904 }
905 }
906};
907
908TEST_F(BasicRunWithCannedPerf, Basic)
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500909{
910 //
911 // Verify the portion of the daemon that reads and encodes
912 // perf.data files. Here we run the encoder on a canned perf.data
913 // file and verify that the resulting protobuf contains what
914 // we think it should contain.
915 //
916 std::string input_perf_data(test_dir);
917 input_perf_data += "/canned.perf.data";
918
Than McIntosh8c7c7db2015-09-03 15:16:04 -0400919 // Set up config to avoid these annotations (they are tested elsewhere)
Andreas Gampee44ae142017-12-21 10:02:23 -0800920 ConfigReader config_reader;
921 config_reader.overrideUnsignedEntry("collect_cpu_utilization", 0);
922 config_reader.overrideUnsignedEntry("collect_charging_state", 0);
923 config_reader.overrideUnsignedEntry("collect_camera_active", 0);
Andreas Gampe894b3f92018-03-22 19:48:48 -0700924
925 // Disable compression.
926 config_reader.overrideUnsignedEntry("compress", 0);
927
Andreas Gampe517f4e92017-12-21 10:26:36 -0800928 PerfProfdRunner::LoggingConfig config;
Andreas Gampee44ae142017-12-21 10:02:23 -0800929 config_reader.FillConfig(&config);
Than McIntosh8c7c7db2015-09-03 15:16:04 -0400930
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500931 // Kick off encoder and check return code
932 PROFILE_RESULT result =
Andreas Gampef9a35612018-01-04 14:22:50 -0800933 encode_to_proto(input_perf_data, encoded_file_path(dest_dir, 0).c_str(), config, 0, nullptr);
Andreas Gampe54237f82018-01-18 21:20:36 -0800934 ASSERT_EQ(OK_PROFILE_COLLECTION, result) << test_logger.JoinTestLog(" ");
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500935
936 // Read and decode the resulting perf.data.encoded file
Andreas Gampe0c09e0e2018-03-13 16:04:01 -0700937 android::perfprofd::PerfprofdRecord encodedProfile;
Andreas Gampe894b3f92018-03-22 19:48:48 -0700938 readEncodedProfile(dest_dir, false, encodedProfile);
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500939
Andreas Gampe894b3f92018-03-22 19:48:48 -0700940 VerifyBasicCannedProfile(encodedProfile);
Than McIntosh7e2f4e92015-03-05 11:05:02 -0500941}
942
Andreas Gampe894b3f92018-03-22 19:48:48 -0700943TEST_F(BasicRunWithCannedPerf, Compressed)
Andreas Gampef9a35612018-01-04 14:22:50 -0800944{
945 //
946 // Verify the portion of the daemon that reads and encodes
947 // perf.data files. Here we run the encoder on a canned perf.data
948 // file and verify that the resulting protobuf contains what
949 // we think it should contain.
950 //
951 std::string input_perf_data(test_dir);
952 input_perf_data += "/canned.perf.data";
953
954 // Set up config to avoid these annotations (they are tested elsewhere)
955 ConfigReader config_reader;
956 config_reader.overrideUnsignedEntry("collect_cpu_utilization", 0);
957 config_reader.overrideUnsignedEntry("collect_charging_state", 0);
958 config_reader.overrideUnsignedEntry("collect_camera_active", 0);
Andreas Gampe894b3f92018-03-22 19:48:48 -0700959
960 // Enable compression.
961 config_reader.overrideUnsignedEntry("compress", 1);
962
963 PerfProfdRunner::LoggingConfig config;
964 config_reader.FillConfig(&config);
965
966 // Kick off encoder and check return code
967 PROFILE_RESULT result =
968 encode_to_proto(input_perf_data, encoded_file_path(dest_dir, 0).c_str(), config, 0, nullptr);
969 ASSERT_EQ(OK_PROFILE_COLLECTION, result) << test_logger.JoinTestLog(" ");
970
971 // Read and decode the resulting perf.data.encoded file
972 android::perfprofd::PerfprofdRecord encodedProfile;
973 readEncodedProfile(dest_dir, true, encodedProfile);
974
975 VerifyBasicCannedProfile(encodedProfile);
976}
977
Andreas Gampecbc02bc2018-03-21 16:05:26 -0700978TEST_F(BasicRunWithCannedPerf, WithSymbolizer)
Andreas Gampe894b3f92018-03-22 19:48:48 -0700979{
980 //
981 // Verify the portion of the daemon that reads and encodes
982 // perf.data files. Here we run the encoder on a canned perf.data
983 // file and verify that the resulting protobuf contains what
984 // we think it should contain.
985 //
986 std::string input_perf_data(test_dir);
987 input_perf_data += "/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
Andreas Gampef9a35612018-01-04 14:22:50 -0800998 PerfProfdRunner::LoggingConfig config;
999 config_reader.FillConfig(&config);
1000
1001 // Kick off encoder and check return code
1002 struct TestSymbolizer : public perfprofd::Symbolizer {
1003 std::string Decode(const std::string& dso, uint64_t address) override {
1004 return dso + "@" + std::to_string(address);
1005 }
Andreas Gampecbc02bc2018-03-21 16:05:26 -07001006 bool GetMinExecutableVAddr(const std::string& dso, uint64_t* addr) override {
1007 *addr = 4096;
1008 return true;
1009 }
Andreas Gampef9a35612018-01-04 14:22:50 -08001010 };
1011 TestSymbolizer test_symbolizer;
1012 PROFILE_RESULT result =
1013 encode_to_proto(input_perf_data,
1014 encoded_file_path(dest_dir, 0).c_str(),
1015 config,
1016 0,
1017 &test_symbolizer);
Andreas Gampe577e6462018-01-10 20:02:20 -08001018 ASSERT_EQ(OK_PROFILE_COLLECTION, result);
Andreas Gampef9a35612018-01-04 14:22:50 -08001019
1020 // Read and decode the resulting perf.data.encoded file
Andreas Gampe0c09e0e2018-03-13 16:04:01 -07001021 android::perfprofd::PerfprofdRecord encodedProfile;
Andreas Gampe894b3f92018-03-22 19:48:48 -07001022 readEncodedProfile(dest_dir, false, encodedProfile);
Andreas Gampef9a35612018-01-04 14:22:50 -08001023
Andreas Gampe894b3f92018-03-22 19:48:48 -07001024 VerifyBasicCannedProfile(encodedProfile);
Andreas Gampef9a35612018-01-04 14:22:50 -08001025
Andreas Gampe15236cf2018-05-23 10:51:46 -07001026 auto find_symbol = [&](const std::string& filename) -> const quipper::SymbolInfo* {
1027 const size_t size = encodedProfile.ExtensionSize(quipper::symbol_info);
1028 for (size_t i = 0; i != size; ++i) {
1029 auto& symbol_info = encodedProfile.GetExtension(quipper::symbol_info, i);
Andreas Gampecbc02bc2018-03-21 16:05:26 -07001030 if (symbol_info.filename() == filename) {
1031 return &symbol_info;
1032 }
1033 }
1034 return nullptr;
1035 };
1036 auto all_filenames = [&]() {
1037 std::ostringstream oss;
Andreas Gampe15236cf2018-05-23 10:51:46 -07001038 const size_t size = encodedProfile.ExtensionSize(quipper::symbol_info);
1039 for (size_t i = 0; i != size; ++i) {
1040 auto& symbol_info = encodedProfile.GetExtension(quipper::symbol_info, i);
Andreas Gampecbc02bc2018-03-21 16:05:26 -07001041 oss << " " << symbol_info.filename();
1042 }
1043 return oss.str();
1044 };
1045
1046 EXPECT_TRUE(find_symbol("/data/app/com.google.android.apps.plus-1/lib/arm/libcronet.so")
1047 != nullptr) << all_filenames() << test_logger.JoinTestLog("\n");
1048 EXPECT_TRUE(find_symbol("/data/dalvik-cache/arm/system@framework@wifi-service.jar@classes.dex")
1049 != nullptr) << all_filenames();
1050 EXPECT_TRUE(find_symbol("/data/dalvik-cache/arm/data@app@com.google.android.gms-2@base.apk@"
1051 "classes.dex")
1052 != nullptr) << all_filenames();
1053 EXPECT_TRUE(find_symbol("/data/dalvik-cache/arm/system@framework@boot.oat") != nullptr)
1054 << all_filenames();
Andreas Gampef9a35612018-01-04 14:22:50 -08001055}
1056
Than McIntoshe42c1f12016-06-01 12:21:42 -04001057TEST_F(PerfProfdTest, CallchainRunWithCannedPerf)
1058{
1059 // This test makes sure that the perf.data converter
1060 // can handle call chains.
1061 //
1062 std::string input_perf_data(test_dir);
1063 input_perf_data += "/callchain.canned.perf.data";
1064
1065 // Set up config to avoid these annotations (they are tested elsewhere)
Andreas Gampee44ae142017-12-21 10:02:23 -08001066 ConfigReader config_reader;
1067 config_reader.overrideUnsignedEntry("collect_cpu_utilization", 0);
1068 config_reader.overrideUnsignedEntry("collect_charging_state", 0);
1069 config_reader.overrideUnsignedEntry("collect_camera_active", 0);
Andreas Gampe894b3f92018-03-22 19:48:48 -07001070
1071 // Disable compression.
1072 config_reader.overrideUnsignedEntry("compress", 0);
1073
Andreas Gampe517f4e92017-12-21 10:26:36 -08001074 PerfProfdRunner::LoggingConfig config;
Andreas Gampee44ae142017-12-21 10:02:23 -08001075 config_reader.FillConfig(&config);
Than McIntoshe42c1f12016-06-01 12:21:42 -04001076
1077 // Kick off encoder and check return code
1078 PROFILE_RESULT result =
Andreas Gampef9a35612018-01-04 14:22:50 -08001079 encode_to_proto(input_perf_data, encoded_file_path(dest_dir, 0).c_str(), config, 0, nullptr);
Andreas Gampe577e6462018-01-10 20:02:20 -08001080 ASSERT_EQ(OK_PROFILE_COLLECTION, result);
Than McIntoshe42c1f12016-06-01 12:21:42 -04001081
1082 // Read and decode the resulting perf.data.encoded file
Andreas Gampe0c09e0e2018-03-13 16:04:01 -07001083 android::perfprofd::PerfprofdRecord encodedProfile;
Andreas Gampe894b3f92018-03-22 19:48:48 -07001084 readEncodedProfile(dest_dir, false, encodedProfile);
Than McIntoshe42c1f12016-06-01 12:21:42 -04001085
Andreas Gampe15236cf2018-05-23 10:51:46 -07001086 const quipper::PerfDataProto& perf_data = encodedProfile;
Than McIntoshe42c1f12016-06-01 12:21:42 -04001087
Andreas Gampe0c09e0e2018-03-13 16:04:01 -07001088 // Expect 21108 events.
1089 EXPECT_EQ(2224, perf_data.events_size()) << CreateStats(perf_data);
Than McIntoshe42c1f12016-06-01 12:21:42 -04001090
Andreas Gampe0c09e0e2018-03-13 16:04:01 -07001091 {
1092 SampleEventIterator samples(perf_data);
1093 constexpr const char* kSampleEvents[] = {
1094 "0: pid=6225 tid=6225 ip=18446743798834668032 callchain=->18446744073709551488->"
1095 "18446743798834668032->18446743798834782596->18446743798834784624->"
1096 "18446743798835055136->18446743798834788016->18446743798834789192->"
1097 "18446743798834789512->18446743798834790216->18446743798833756776",
1098 "1: pid=6225 tid=6225 ip=18446743798835685700 callchain=->18446744073709551488->"
1099 "18446743798835685700->18446743798835688704->18446743798835650964->"
1100 "18446743798834612104->18446743798834612276->18446743798835055528->"
1101 "18446743798834788016->18446743798834789192->18446743798834789512->"
1102 "18446743798834790216->18446743798833756776",
1103 "2: pid=6225 tid=6225 ip=18446743798835055804 callchain=->18446744073709551488->"
1104 "18446743798835055804->18446743798834788016->18446743798834789192->"
1105 "18446743798834789512->18446743798834790216->18446743798833756776",
1106 "3: pid=6225 tid=6225 ip=18446743798835991212 callchain=->18446744073709551488->"
1107 "18446743798835991212->18446743798834491060->18446743798834675572->"
1108 "18446743798834676516->18446743798834612172->18446743798834612276->"
1109 "18446743798835056664->18446743798834788016->18446743798834789192->"
1110 "18446743798834789512->18446743798834790216->18446743798833756776",
1111 "4: pid=6225 tid=6225 ip=18446743798844881108 callchain=->18446744073709551488->"
1112 "18446743798844881108->18446743798834836140->18446743798834846384->"
1113 "18446743798834491100->18446743798834675572->18446743798834676516->"
1114 "18446743798834612172->18446743798834612276->18446743798835056784->"
1115 "18446743798834788016->18446743798834789192->18446743798834789512->"
1116 "18446743798834790216->18446743798833756776",
1117 };
1118 size_t cmp_index = 0;
1119 for (size_t index = 0; samples != samples.end(); ++samples, ++index) {
1120 if (samples->sample_event().callchain_size() > 0) {
1121 std::ostringstream oss;
1122 oss << index << ": " << FormatSampleEvent(samples->sample_event());
1123 EXPECT_STREQ(kSampleEvents[cmp_index], oss.str().c_str());
1124 cmp_index++;
1125 if (cmp_index == arraysize(kSampleEvents)) {
1126 break;
1127 }
1128 }
1129 }
Than McIntoshe42c1f12016-06-01 12:21:42 -04001130 }
1131}
1132
Andreas Gampe51389ce2018-03-13 20:55:56 -07001133#ifdef __ANDROID__
1134
Than McIntosh7e2f4e92015-03-05 11:05:02 -05001135TEST_F(PerfProfdTest, BasicRunWithLivePerf)
1136{
1137 //
1138 // Basic test to exercise the main loop of the daemon. It includes
1139 // a live 'perf' run
1140 //
Andreas Gampe32695342018-01-03 22:28:18 -08001141 PerfProfdRunner runner(conf_dir);
Than McIntosh7e2f4e92015-03-05 11:05:02 -05001142 runner.addToConfig("only_debug_build=0");
1143 std::string ddparam("destination_directory="); ddparam += dest_dir;
1144 runner.addToConfig(ddparam);
Andreas Gampe32695342018-01-03 22:28:18 -08001145 std::string cfparam("config_directory="); cfparam += conf_dir;
Dehao Chen58bade32015-05-05 15:03:48 -07001146 runner.addToConfig(cfparam);
Than McIntosh7e2f4e92015-03-05 11:05:02 -05001147 runner.addToConfig("main_loop_iterations=1");
1148 runner.addToConfig("use_fixed_seed=12345678");
Than McIntoshf353d8b2015-05-21 14:44:34 -04001149 runner.addToConfig("max_unprocessed_profiles=100");
Than McIntosh7e2f4e92015-03-05 11:05:02 -05001150 runner.addToConfig("collection_interval=9999");
Dehao Chenf4605012015-05-07 13:16:35 -07001151 runner.addToConfig("sample_duration=2");
Andreas Gampee3033742018-01-18 21:19:06 -08001152 // Avoid the symbolizer for spurious messages.
1153 runner.addToConfig("use_elf_symbolizer=0");
Than McIntosh7e2f4e92015-03-05 11:05:02 -05001154
Andreas Gampe894b3f92018-03-22 19:48:48 -07001155 // Disable compression.
1156 runner.addToConfig("compress=0");
1157
Than McIntosh7e2f4e92015-03-05 11:05:02 -05001158 // Create semaphore file
1159 runner.create_semaphore_file();
1160
1161 // Kick off daemon
1162 int daemon_main_return_code = runner.invoke();
1163
1164 // Check return code from daemon
Andreas Gampe577e6462018-01-10 20:02:20 -08001165 ASSERT_EQ(0, daemon_main_return_code);
Than McIntosh7e2f4e92015-03-05 11:05:02 -05001166
1167 // Read and decode the resulting perf.data.encoded file
Andreas Gampe0c09e0e2018-03-13 16:04:01 -07001168 android::perfprofd::PerfprofdRecord encodedProfile;
Andreas Gampe894b3f92018-03-22 19:48:48 -07001169 readEncodedProfile(dest_dir, false, encodedProfile);
Than McIntosh7e2f4e92015-03-05 11:05:02 -05001170
1171 // Examine what we get back. Since it's a live profile, we can't
1172 // really do much in terms of verifying the contents.
Andreas Gampe15236cf2018-05-23 10:51:46 -07001173 EXPECT_LT(0, encodedProfile.events_size());
Than McIntosh7e2f4e92015-03-05 11:05:02 -05001174
1175 // Verify log contents
Andreas Gampe32695342018-01-03 22:28:18 -08001176 const std::string expected = std::string(
1177 "I: starting Android Wide Profiling daemon ") +
1178 "I: config file path set to " + conf_dir + "/perfprofd.conf " +
1179 RAW_RESULT(
Than McIntosh7e2f4e92015-03-05 11:05:02 -05001180 I: random seed set to 12345678
1181 I: sleep 674 seconds
1182 I: initiating profile collection
Andreas Gampe44e63a72018-01-03 12:39:53 -08001183 I: sleep 2 seconds
Than McIntosh7e2f4e92015-03-05 11:05:02 -05001184 I: profile collection complete
1185 I: sleep 9325 seconds
1186 I: finishing Android Wide Profiling daemon
1187 );
1188 // check to make sure log excerpt matches
Andreas Gamped0525702018-06-12 09:56:11 -07001189 EXPECT_TRUE(CompareLogMessages(expandVars(expected), true));
Than McIntosh7e2f4e92015-03-05 11:05:02 -05001190}
1191
Andreas Gampe725faa22018-06-21 16:07:48 -07001192TEST_F(PerfProfdTest, BasicRunWithLivePerf_Events)
1193{
1194 //
1195 // Basic test to check that the event set functionality works.
1196 //
1197 // Note: this is brittle, as we do not really know which events the hardware
1198 // supports. Use "cpu-cycles" and "page-faults" as something likely.
1199 //
1200 PerfProfdRunner runner(conf_dir);
1201 runner.addToConfig("only_debug_build=0");
1202 std::string ddparam("destination_directory="); ddparam += dest_dir;
1203 runner.addToConfig(ddparam);
1204 std::string cfparam("config_directory="); cfparam += conf_dir;
1205 runner.addToConfig(cfparam);
1206 runner.addToConfig("main_loop_iterations=1");
1207 runner.addToConfig("use_fixed_seed=12345678");
1208 runner.addToConfig("max_unprocessed_profiles=100");
1209 runner.addToConfig("collection_interval=9999");
1210 runner.addToConfig("sample_duration=2");
1211 // Avoid the symbolizer for spurious messages.
1212 runner.addToConfig("use_elf_symbolizer=0");
1213
1214 // Disable compression.
1215 runner.addToConfig("compress=0");
1216
1217 // Set event set.
1218 runner.addToConfig("-e_cpu-cycles,page-faults@100000=dummy");
1219
1220 // Create semaphore file
1221 runner.create_semaphore_file();
1222
1223 // Kick off daemon
1224 int daemon_main_return_code = runner.invoke();
1225
1226 // Check return code from daemon
1227 ASSERT_EQ(0, daemon_main_return_code);
1228
1229 // Read and decode the resulting perf.data.encoded file
1230 android::perfprofd::PerfprofdRecord encodedProfile;
1231 readEncodedProfile(dest_dir, false, encodedProfile);
1232
1233 // Examine what we get back. Since it's a live profile, we can't
1234 // really do much in terms of verifying the contents.
1235 EXPECT_LT(0, encodedProfile.events_size());
1236
1237 // Verify log contents
1238 const std::string expected = std::string(
1239 "I: starting Android Wide Profiling daemon ") +
1240 "I: config file path set to " + conf_dir + "/perfprofd.conf " +
1241 RAW_RESULT(
1242 I: random seed set to 12345678
1243 I: sleep 674 seconds
1244 I: initiating profile collection
1245 I: sleep 2 seconds
1246 I: profile collection complete
1247 I: sleep 9325 seconds
1248 I: finishing Android Wide Profiling daemon
1249 );
1250 // check to make sure log excerpt matches
1251 EXPECT_TRUE(CompareLogMessages(expandVars(expected), true));
1252}
1253
1254TEST_F(PerfProfdTest, BasicRunWithLivePerf_EventsGroup)
1255{
1256 //
1257 // Basic test to check that the event set functionality works.
1258 //
1259 // Note: this is brittle, as we do not really know which events the hardware
1260 // supports. Use "cpu-cycles" and "page-faults" as something likely.
1261 //
1262 PerfProfdRunner runner(conf_dir);
1263 runner.addToConfig("only_debug_build=0");
1264 std::string ddparam("destination_directory="); ddparam += dest_dir;
1265 runner.addToConfig(ddparam);
1266 std::string cfparam("config_directory="); cfparam += conf_dir;
1267 runner.addToConfig(cfparam);
1268 runner.addToConfig("main_loop_iterations=1");
1269 runner.addToConfig("use_fixed_seed=12345678");
1270 runner.addToConfig("max_unprocessed_profiles=100");
1271 runner.addToConfig("collection_interval=9999");
1272 runner.addToConfig("sample_duration=2");
1273 // Avoid the symbolizer for spurious messages.
1274 runner.addToConfig("use_elf_symbolizer=0");
1275
1276 // Disable compression.
1277 runner.addToConfig("compress=0");
1278
1279 // Set event set.
1280 runner.addToConfig("-g_cpu-cycles,page-faults@100000=dummy");
1281
1282 // Create semaphore file
1283 runner.create_semaphore_file();
1284
1285 // Kick off daemon
1286 int daemon_main_return_code = runner.invoke();
1287
1288 // Check return code from daemon
1289 ASSERT_EQ(0, daemon_main_return_code);
1290
1291 // Read and decode the resulting perf.data.encoded file
1292 android::perfprofd::PerfprofdRecord encodedProfile;
1293 readEncodedProfile(dest_dir, false, encodedProfile);
1294
1295 // Examine what we get back. Since it's a live profile, we can't
1296 // really do much in terms of verifying the contents.
1297 EXPECT_LT(0, encodedProfile.events_size());
1298
1299 // Verify log contents
1300 const std::string expected = std::string(
1301 "I: starting Android Wide Profiling daemon ") +
1302 "I: config file path set to " + conf_dir + "/perfprofd.conf " +
1303 RAW_RESULT(
1304 I: random seed set to 12345678
1305 I: sleep 674 seconds
1306 I: initiating profile collection
1307 I: sleep 2 seconds
1308 I: profile collection complete
1309 I: sleep 9325 seconds
1310 I: finishing Android Wide Profiling daemon
1311 );
1312 // check to make sure log excerpt matches
1313 EXPECT_TRUE(CompareLogMessages(expandVars(expected), true));
1314}
1315
Dehao Chenf4605012015-05-07 13:16:35 -07001316TEST_F(PerfProfdTest, MultipleRunWithLivePerf)
1317{
1318 //
1319 // Basic test to exercise the main loop of the daemon. It includes
1320 // a live 'perf' run
1321 //
Andreas Gampe32695342018-01-03 22:28:18 -08001322 PerfProfdRunner runner(conf_dir);
Dehao Chenf4605012015-05-07 13:16:35 -07001323 runner.addToConfig("only_debug_build=0");
1324 std::string ddparam("destination_directory="); ddparam += dest_dir;
1325 runner.addToConfig(ddparam);
Andreas Gampe32695342018-01-03 22:28:18 -08001326 std::string cfparam("config_directory="); cfparam += conf_dir;
Dehao Chenf4605012015-05-07 13:16:35 -07001327 runner.addToConfig(cfparam);
1328 runner.addToConfig("main_loop_iterations=3");
1329 runner.addToConfig("use_fixed_seed=12345678");
1330 runner.addToConfig("collection_interval=9999");
1331 runner.addToConfig("sample_duration=2");
Andreas Gampee3033742018-01-18 21:19:06 -08001332 // Avoid the symbolizer for spurious messages.
1333 runner.addToConfig("use_elf_symbolizer=0");
Andreas Gampe894b3f92018-03-22 19:48:48 -07001334
1335 // Disable compression.
1336 runner.addToConfig("compress=0");
1337
Dehao Chenf4605012015-05-07 13:16:35 -07001338 runner.write_processed_file(1, 2);
1339
1340 // Create semaphore file
1341 runner.create_semaphore_file();
1342
1343 // Kick off daemon
1344 int daemon_main_return_code = runner.invoke();
1345
1346 // Check return code from daemon
Andreas Gampe577e6462018-01-10 20:02:20 -08001347 ASSERT_EQ(0, daemon_main_return_code);
Dehao Chenf4605012015-05-07 13:16:35 -07001348
1349 // Read and decode the resulting perf.data.encoded file
Andreas Gampe0c09e0e2018-03-13 16:04:01 -07001350 android::perfprofd::PerfprofdRecord encodedProfile;
Andreas Gampe894b3f92018-03-22 19:48:48 -07001351 readEncodedProfile(dest_dir, false, encodedProfile);
Dehao Chenf4605012015-05-07 13:16:35 -07001352
1353 // Examine what we get back. Since it's a live profile, we can't
1354 // really do much in terms of verifying the contents.
Andreas Gampe15236cf2018-05-23 10:51:46 -07001355 EXPECT_LT(0, encodedProfile.events_size());
Dehao Chenf4605012015-05-07 13:16:35 -07001356
1357 // Examine that encoded.1 file is removed while encoded.{0|2} exists.
Andreas Gampe32695342018-01-03 22:28:18 -08001358 EXPECT_EQ(0, access(encoded_file_path(dest_dir, 0).c_str(), F_OK));
1359 EXPECT_NE(0, access(encoded_file_path(dest_dir, 1).c_str(), F_OK));
1360 EXPECT_EQ(0, access(encoded_file_path(dest_dir, 2).c_str(), F_OK));
Dehao Chenf4605012015-05-07 13:16:35 -07001361
1362 // Verify log contents
Andreas Gampe32695342018-01-03 22:28:18 -08001363 const std::string expected = std::string(
1364 "I: starting Android Wide Profiling daemon ") +
1365 "I: config file path set to " + conf_dir + "/perfprofd.conf " +
1366 RAW_RESULT(
Dehao Chenf4605012015-05-07 13:16:35 -07001367 I: random seed set to 12345678
1368 I: sleep 674 seconds
1369 I: initiating profile collection
Andreas Gampe44e63a72018-01-03 12:39:53 -08001370 I: sleep 2 seconds
Dehao Chenf4605012015-05-07 13:16:35 -07001371 I: profile collection complete
1372 I: sleep 9325 seconds
1373 I: sleep 4974 seconds
1374 I: initiating profile collection
Andreas Gampe44e63a72018-01-03 12:39:53 -08001375 I: sleep 2 seconds
Dehao Chenf4605012015-05-07 13:16:35 -07001376 I: profile collection complete
1377 I: sleep 5025 seconds
1378 I: sleep 501 seconds
1379 I: initiating profile collection
Andreas Gampe44e63a72018-01-03 12:39:53 -08001380 I: sleep 2 seconds
Dehao Chenf4605012015-05-07 13:16:35 -07001381 I: profile collection complete
1382 I: sleep 9498 seconds
1383 I: finishing Android Wide Profiling daemon
1384 );
1385 // check to make sure log excerpt matches
Andreas Gamped0525702018-06-12 09:56:11 -07001386 EXPECT_TRUE(CompareLogMessages(expandVars(expected), true));
Dehao Chenf4605012015-05-07 13:16:35 -07001387}
1388
Than McIntoshbe1b1772016-05-23 11:07:08 -04001389TEST_F(PerfProfdTest, CallChainRunWithLivePerf)
1390{
1391 //
Than McIntoshbe1b1772016-05-23 11:07:08 -04001392 // Collect a callchain profile, so as to exercise the code in
1393 // perf_data post-processing that digests callchains.
1394 //
Andreas Gampe32695342018-01-03 22:28:18 -08001395 PerfProfdRunner runner(conf_dir);
Than McIntoshbe1b1772016-05-23 11:07:08 -04001396 std::string ddparam("destination_directory="); ddparam += dest_dir;
1397 runner.addToConfig(ddparam);
Andreas Gampe32695342018-01-03 22:28:18 -08001398 std::string cfparam("config_directory="); cfparam += conf_dir;
Than McIntoshbe1b1772016-05-23 11:07:08 -04001399 runner.addToConfig(cfparam);
1400 runner.addToConfig("main_loop_iterations=1");
1401 runner.addToConfig("use_fixed_seed=12345678");
1402 runner.addToConfig("max_unprocessed_profiles=100");
1403 runner.addToConfig("collection_interval=9999");
1404 runner.addToConfig("stack_profile=1");
1405 runner.addToConfig("sample_duration=2");
Andreas Gampee3033742018-01-18 21:19:06 -08001406 // Avoid the symbolizer for spurious messages.
1407 runner.addToConfig("use_elf_symbolizer=0");
Than McIntoshbe1b1772016-05-23 11:07:08 -04001408
Andreas Gampe894b3f92018-03-22 19:48:48 -07001409 // Disable compression.
1410 runner.addToConfig("compress=0");
1411
Than McIntoshbe1b1772016-05-23 11:07:08 -04001412 // Create semaphore file
1413 runner.create_semaphore_file();
1414
1415 // Kick off daemon
1416 int daemon_main_return_code = runner.invoke();
1417
1418 // Check return code from daemon
Andreas Gampe577e6462018-01-10 20:02:20 -08001419 ASSERT_EQ(0, daemon_main_return_code);
Than McIntoshbe1b1772016-05-23 11:07:08 -04001420
1421 // Read and decode the resulting perf.data.encoded file
Andreas Gampe0c09e0e2018-03-13 16:04:01 -07001422 android::perfprofd::PerfprofdRecord encodedProfile;
Andreas Gampe894b3f92018-03-22 19:48:48 -07001423 readEncodedProfile(dest_dir, false, encodedProfile);
Than McIntoshbe1b1772016-05-23 11:07:08 -04001424
1425 // Examine what we get back. Since it's a live profile, we can't
1426 // really do much in terms of verifying the contents.
Andreas Gampe15236cf2018-05-23 10:51:46 -07001427 EXPECT_LT(0, encodedProfile.events_size());
Than McIntoshbe1b1772016-05-23 11:07:08 -04001428
1429 // Verify log contents
Andreas Gampe32695342018-01-03 22:28:18 -08001430 const std::string expected = std::string(
1431 "I: starting Android Wide Profiling daemon ") +
1432 "I: config file path set to " + conf_dir + "/perfprofd.conf " +
1433 RAW_RESULT(
Than McIntoshbe1b1772016-05-23 11:07:08 -04001434 I: random seed set to 12345678
1435 I: sleep 674 seconds
1436 I: initiating profile collection
Andreas Gampe44e63a72018-01-03 12:39:53 -08001437 I: sleep 2 seconds
Than McIntoshbe1b1772016-05-23 11:07:08 -04001438 I: profile collection complete
1439 I: sleep 9325 seconds
1440 I: finishing Android Wide Profiling daemon
1441 );
1442 // check to make sure log excerpt matches
Andreas Gamped0525702018-06-12 09:56:11 -07001443 EXPECT_TRUE(CompareLogMessages(expandVars(expected), true));
Andreas Gampe0c09e0e2018-03-13 16:04:01 -07001444
1445 // Check that we have at least one SampleEvent with a callchain.
Andreas Gampe15236cf2018-05-23 10:51:46 -07001446 SampleEventIterator samples(encodedProfile);
Andreas Gampe0c09e0e2018-03-13 16:04:01 -07001447 bool found_callchain = false;
1448 while (!found_callchain && samples != samples.end()) {
1449 found_callchain = samples->sample_event().callchain_size() > 0;
1450 }
Andreas Gampe15236cf2018-05-23 10:51:46 -07001451 EXPECT_TRUE(found_callchain) << CreateStats(encodedProfile);
Than McIntoshbe1b1772016-05-23 11:07:08 -04001452}
1453
Andreas Gampe51389ce2018-03-13 20:55:56 -07001454#endif
1455
Andreas Gampecbc02bc2018-03-21 16:05:26 -07001456class RangeMapTest : public testing::Test {
1457};
1458
1459TEST_F(RangeMapTest, TestRangeMap) {
1460 using namespace android::perfprofd;
1461
1462 RangeMap<std::string, uint64_t> map;
1463 auto print = [&]() {
1464 std::ostringstream oss;
1465 for (auto& aggr_sym : map) {
1466 oss << aggr_sym.first << "#" << aggr_sym.second.symbol;
1467 oss << "[";
1468 for (auto& x : aggr_sym.second.offsets) {
1469 oss << x << ",";
1470 }
1471 oss << "]";
1472 }
1473 return oss.str();
1474 };
1475
1476 EXPECT_STREQ("", print().c_str());
1477
1478 map.Insert("a", 10);
1479 EXPECT_STREQ("10#a[10,]", print().c_str());
1480 map.Insert("a", 100);
1481 EXPECT_STREQ("10#a[10,100,]", print().c_str());
1482 map.Insert("a", 1);
1483 EXPECT_STREQ("1#a[1,10,100,]", print().c_str());
1484 map.Insert("a", 1);
1485 EXPECT_STREQ("1#a[1,10,100,]", print().c_str());
1486 map.Insert("a", 2);
1487 EXPECT_STREQ("1#a[1,2,10,100,]", print().c_str());
1488
1489 map.Insert("b", 200);
1490 EXPECT_STREQ("1#a[1,2,10,100,]200#b[200,]", print().c_str());
1491 map.Insert("b", 199);
1492 EXPECT_STREQ("1#a[1,2,10,100,]199#b[199,200,]", print().c_str());
1493
1494 map.Insert("c", 50);
1495 EXPECT_STREQ("1#a[1,2,10,]50#c[50,]100#a[100,]199#b[199,200,]", print().c_str());
1496}
1497
Andreas Gampeb019ddc2018-04-02 10:58:32 -07001498class ThreadedHandlerTest : public PerfProfdTest {
1499 public:
1500 void SetUp() override {
1501 PerfProfdTest::SetUp();
1502 threaded_handler_.reset(new android::perfprofd::ThreadedHandler());
1503 }
1504
1505 void TearDown() override {
1506 threaded_handler_.reset();
1507 PerfProfdTest::TearDown();
1508 }
1509
1510 protected:
1511 std::unique_ptr<android::perfprofd::ThreadedHandler> threaded_handler_;
1512};
1513
1514TEST_F(ThreadedHandlerTest, Basic) {
1515 std::string error_msg;
1516 EXPECT_FALSE(threaded_handler_->StopProfiling(&error_msg));
1517}
1518
1519#ifdef __ANDROID__
1520#define ThreadedHandlerTestName(x) x
1521#else
1522#define ThreadedHandlerTestName(x) DISABLED_ ## x
1523#endif
1524
1525TEST_F(ThreadedHandlerTest, ThreadedHandlerTestName(Live)) {
1526 auto config_fn = [](android::perfprofd::ThreadedConfig& config) {
1527 // Use some values that make it likely that things don't fail quickly.
1528 config.main_loop_iterations = 0;
1529 config.collection_interval_in_s = 1000000;
1530 };
1531 std::string error_msg;
1532 ASSERT_TRUE(threaded_handler_->StartProfiling(config_fn, &error_msg)) << error_msg;
1533 EXPECT_TRUE(threaded_handler_->StopProfiling(&error_msg)) << error_msg;
1534}
1535
Than McIntosh7e2f4e92015-03-05 11:05:02 -05001536int main(int argc, char **argv) {
Andreas Gampe32695342018-01-03 22:28:18 -08001537 // Always log to cerr, so that device failures are visible.
1538 android::base::SetLogger(android::base::StderrLogger);
1539
1540 CHECK(android::base::Realpath(argv[0], &gExecutableRealpath));
1541
Than McIntosh7e2f4e92015-03-05 11:05:02 -05001542 // switch to / before starting testing (perfprofd
1543 // should be location-independent)
1544 chdir("/");
1545 testing::InitGoogleTest(&argc, argv);
1546 return RUN_ALL_TESTS();
1547}