OSDN Git Service

Perfprofd: Remove perfprofdutils
authorAndreas Gampe <agampe@google.com>
Wed, 10 Jan 2018 19:37:20 +0000 (11:37 -0800)
committerAndreas Gampe <agampe@google.com>
Thu, 11 Jan 2018 04:46:37 +0000 (20:46 -0800)
The indirection is unnecessary. Implement test hijacking through
custom libbase logger.

Add "[vdso]" to the recognized kernel DSOs to avoid a warning
message for the symbolizer.

Test: m
Test: perfprofd_test
Change-Id: I66c13f3b45a772f121be1e083c6194e2c962a104

perfprofd/Android.bp
perfprofd/configreader.cc
perfprofd/cpuconfig.cc
perfprofd/perf_data_converter.cc
perfprofd/perfprofdcore.cc
perfprofd/perfprofdutils.cc [deleted file]
perfprofd/perfprofdutils.h [deleted file]
perfprofd/tests/Android.bp
perfprofd/tests/perfprofd_test.cc

index 0e14a02..0970906 100644 (file)
@@ -118,20 +118,6 @@ cc_library_static {
 }
 
 //
-// Static library with primary utilities layer (called by perfprofd core)
-//
-cc_library_static {
-    name: "libperfprofdutils",
-    defaults: [
-        "perfprofd_defaults",
-    ],
-
-    srcs: [
-        "perfprofdutils.cc",
-    ],
-}
-
-//
 // Main daemon
 //
 cc_binary {
@@ -146,7 +132,6 @@ cc_binary {
 
     static_libs: [
         "libperfprofdcore",
-        "libperfprofdutils",
         "libperfprofd_binder",
         "libperfprofd_elf_read",
     ],
index 8bdd081..4fcd5ce 100644 (file)
 #include <stdlib.h>
 
 #include <algorithm>
+#include <cstring>
 #include <sstream>
 
 #include <android-base/file.h>
+#include <android-base/logging.h>
 
 #include "configreader.h"
-#include "perfprofdutils.h"
 
 //
 // Config file path
@@ -51,7 +52,7 @@ const char *ConfigReader::getConfigFilePath()
 void ConfigReader::setConfigFilePath(const char *path)
 {
   config_file_path = strdup(path);
-  W_ALOGI("config file path set to %s", config_file_path);
+  LOG(INFO) << "config file path set to " << config_file_path;
 }
 
 //
@@ -131,11 +132,9 @@ void ConfigReader::addUnsignedEntry(const char *key,
                                     unsigned max_value)
 {
   std::string ks(key);
-  if (u_entries.find(ks) != u_entries.end() ||
-      s_entries.find(ks) != s_entries.end()) {
-    W_ALOGE("internal error -- duplicate entry for key %s", key);
-    exit(9);
-  }
+  CHECK(u_entries.find(ks) == u_entries.end() &&
+        s_entries.find(ks) == s_entries.end())
+      << "internal error -- duplicate entry for key " << key;
   values vals;
   vals.minv = min_value;
   vals.maxv = max_value;
@@ -146,15 +145,10 @@ void ConfigReader::addUnsignedEntry(const char *key,
 void ConfigReader::addStringEntry(const char *key, const char *default_value)
 {
   std::string ks(key);
-  if (u_entries.find(ks) != u_entries.end() ||
-      s_entries.find(ks) != s_entries.end()) {
-    W_ALOGE("internal error -- duplicate entry for key %s", key);
-    exit(9);
-  }
-  if (default_value == nullptr) {
-    W_ALOGE("internal error -- bad default value for key %s", key);
-    exit(9);
-  }
+  CHECK(u_entries.find(ks) == u_entries.end() &&
+        s_entries.find(ks) == s_entries.end())
+      << "internal error -- duplicate entry for key " << key;
+  CHECK(default_value != nullptr) << "internal error -- bad default value for key " << key;
   s_entries[ks] = std::string(default_value);
 }
 
@@ -162,7 +156,7 @@ unsigned ConfigReader::getUnsignedValue(const char *key) const
 {
   std::string ks(key);
   auto it = u_entries.find(ks);
-  assert(it != u_entries.end());
+  CHECK(it != u_entries.end());
   return it->second;
 }
 
@@ -170,7 +164,7 @@ bool ConfigReader::getBoolValue(const char *key) const
 {
   std::string ks(key);
   auto it = u_entries.find(ks);
-  assert(it != u_entries.end());
+  CHECK(it != u_entries.end());
   return it->second != 0;
 }
 
@@ -178,7 +172,7 @@ std::string ConfigReader::getStringValue(const char *key) const
 {
   std::string ks(key);
   auto it = s_entries.find(ks);
-  assert(it != s_entries.end());
+  CHECK(it != s_entries.end());
   return it->second;
 }
 
@@ -186,14 +180,14 @@ void ConfigReader::overrideUnsignedEntry(const char *key, unsigned new_value)
 {
   std::string ks(key);
   auto it = u_entries.find(ks);
-  assert(it != u_entries.end());
+  CHECK(it != u_entries.end());
   values vals;
   auto iit = u_info.find(key);
-  assert(iit != u_info.end());
+  CHECK(iit != u_info.end());
   vals = iit->second;
-  assert(new_value >= vals.minv && new_value <= vals.maxv);
+  CHECK(new_value >= vals.minv && new_value <= vals.maxv);
   it->second = new_value;
-  W_ALOGI("option %s overridden to %u", key, new_value);
+  LOG(INFO) << "option " << key << " overridden to " << new_value;
 }
 
 
@@ -213,19 +207,20 @@ void ConfigReader::parseLine(const char *key,
   if (uit != u_entries.end()) {
     unsigned uvalue = 0;
     if (isdigit(value[0]) == 0 || sscanf(value, "%u", &uvalue) != 1) {
-      W_ALOGW("line %d: malformed unsigned value (ignored)", linecount);
+      LOG(WARNING) << "line " << linecount << ": malformed unsigned value (ignored)";
     } else {
       values vals;
       auto iit = u_info.find(key);
       assert(iit != u_info.end());
       vals = iit->second;
       if (uvalue < vals.minv || uvalue > vals.maxv) {
-        W_ALOGW("line %d: specified value %u for '%s' "
-                "outside permitted range [%u %u] (ignored)",
-                linecount, uvalue, key, vals.minv, vals.maxv);
+        LOG(WARNING) << "line " << linecount << ": "
+                     << "specified value " << uvalue << " for '" << key << "' "
+                     << "outside permitted range [" << vals.minv << " " << vals.maxv
+                     << "] (ignored)";
       } else {
         if (trace_config_read) {
-          W_ALOGI("option %s set to %u", key, uvalue);
+          LOG(INFO) << "option " << key << " set to " << uvalue;
         }
         uit->second = uvalue;
       }
@@ -237,13 +232,13 @@ void ConfigReader::parseLine(const char *key,
   auto sit = s_entries.find(key);
   if (sit != s_entries.end()) {
     if (trace_config_read) {
-      W_ALOGI("option %s set to %s", key, value);
+      LOG(INFO) << "option " << key << " set to " << value;
     }
     sit->second = std::string(value);
     return;
   }
 
-  W_ALOGW("line %d: unknown option '%s' ignored", linecount, key);
+  LOG(WARNING) << "line " << linecount << ": unknown option '" << key << "' ignored";
 }
 
 static bool isblank(const std::string &line)
@@ -279,7 +274,7 @@ bool ConfigReader::readFile()
     // look for X=Y assignment
     auto efound = line.find('=');
     if (efound == std::string::npos) {
-      W_ALOGW("line %d: line malformed (no '=' found)", linecount);
+      LOG(WARNING) << "line " << linecount << ": line malformed (no '=' found)";
       continue;
     }
 
index 04e295b..337da56 100644 (file)
 #include <sys/types.h>
 #include <sys/wait.h>
 
+#include <android-base/logging.h>
 #include <android-base/properties.h>
 
 #include "cpuconfig.h"
-#include "perfprofdutils.h"
 
 #define SYSFSCPU "/sys/devices/system/cpu"
 
@@ -81,14 +81,14 @@ void HardwireCpuHelper::OnlineCore(int i, int onoff)
     fprintf(fp, onoff ? "1\n" : "0\n");
     fclose(fp);
   } else {
-    W_ALOGW("open failed for %s", ss.str().c_str());
+    PLOG(WARNING) << "open failed for " << ss.str();
   }
 }
 
 void HardwireCpuHelper::StopMpdecision()
 {
   if (!android::base::SetProperty("ctl.stop", "mpdecision")) {
-    W_ALOGE("setprop ctl.stop mpdecision failed");
+    LOG(ERROR) << "setprop ctl.stop mpdecision failed";
   }
 }
 
@@ -98,6 +98,6 @@ void HardwireCpuHelper::RestartMpdecision()
   // mpdecision figure out what to do
 
   if (!android::base::SetProperty("ctl.start", "mpdecision")) {
-    W_ALOGE("setprop ctl.start mpdecision failed");
+    LOG(ERROR) << "setprop ctl.start mpdecision failed";
   }
 }
index 4989dc9..244386b 100644 (file)
@@ -6,6 +6,8 @@
 #include <map>
 #include <unordered_map>
 
+#include <android-base/strings.h>
+
 #include "quipper/perf_parser.h"
 #include "symbolizer.h"
 
@@ -91,6 +93,20 @@ RawPerfDataToAndroidPerfProfile(const string &perf_file,
   uint64 total_samples = 0;
   bool seen_branch_stack = false;
   bool seen_callchain = false;
+
+  auto is_kernel_dso = [](const std::string& dso) {
+    constexpr const char* kKernelDsos[] = {
+        "[kernel.kallsyms]",
+        "[vdso]",
+    };
+    for (auto kernel_dso : kKernelDsos) {
+      if (dso == kernel_dso) {
+        return true;
+      }
+    }
+    return false;
+  };
+
   for (const auto &event : parser.parsed_events()) {
     if (!event.raw_event ||
         event.raw_event->header.type != PERF_RECORD_SAMPLE) {
@@ -99,13 +115,17 @@ RawPerfDataToAndroidPerfProfile(const string &perf_file,
     string dso_name = event.dso_and_offset.dso_name();
     string program_name = event.command();
     const string kernel_name = "[kernel.kallsyms]";
-    if (dso_name.substr(0, kernel_name.length()) == kernel_name) {
+    if (android::base::StartsWith(dso_name, kernel_name)) {
       dso_name = kernel_name;
       if (program_name == "") {
         program_name = "kernel";
       }
     } else if (program_name == "") {
-      program_name = "unknown_program";
+      if (is_kernel_dso(dso_name)) {
+        program_name = "kernel";
+      } else {
+        program_name = "unknown_program";
+      }
     }
     total_samples++;
     // We expect to see either all callchain events, all branch stack
@@ -179,7 +199,7 @@ RawPerfDataToAndroidPerfProfile(const string &perf_file,
         load_module->set_build_id(build_id);
       }
     }
-    if (kUseSymbolizer && symbolizer != nullptr && name_data.first != "[kernel.kallsyms]") {
+    if (kUseSymbolizer && symbolizer != nullptr && !is_kernel_dso(name_data.first)) {
       if (kUseSymbolizerForModulesWithBuildId || !has_build_id) {
         // Add the module to signal that we'd want to add symbols.
         name_data.second.module = load_module;
index 4cbf813..6de7a71 100644 (file)
 #include <string>
 
 #include <android-base/file.h>
+#include <android-base/logging.h>
 #include <android-base/macros.h>
 #include <android-base/properties.h>
 #include <android-base/stringprintf.h>
 
 #include "perfprofdcore.h"
-#include "perfprofdutils.h"
 #include "perf_data_converter.h"
 #include "cpuconfig.h"
 #include "configreader.h"
@@ -116,7 +116,7 @@ static unsigned short random_seed[3];
 //
 static void sig_hup(int /* signum */)
 {
-  W_ALOGW("SIGHUP received");
+  LOG(WARNING) << "SIGHUP received";
 }
 
 //
@@ -133,20 +133,20 @@ static void parse_args(int argc, char** argv)
   for (ac = 1; ac < argc; ++ac) {
     if (!strcmp(argv[ac], "-c")) {
       if (ac >= argc-1) {
-        W_ALOGE("malformed command line: -c option requires argument)");
+        LOG(ERROR) << "malformed command line: -c option requires argument)";
         continue;
       }
       ConfigReader::setConfigFilePath(argv[ac+1]);
       ++ac;
     } else if (!strcmp(argv[ac], "-x")) {
       if (ac >= argc-1) {
-        W_ALOGE("malformed command line: -x option requires argument)");
+        LOG(ERROR) << "malformed command line: -x option requires argument)";
         continue;
       }
       perf_file_to_convert = argv[ac+1];
       ++ac;
     } else {
-      W_ALOGE("malformed command line: unknown option or arg %s)", argv[ac]);
+      LOG(ERROR) << "malformed command line: unknown option or arg " <<  argv[ac] << ")";
       continue;
     }
   }
@@ -216,7 +216,7 @@ static CKPROFILE_RESULT check_profiling_enabled(const Config& config)
   // Check for existence of simpleperf/perf executable
   std::string pp = config.perf_path;
   if (access(pp.c_str(), R_OK|X_OK) == -1) {
-    W_ALOGW("unable to access/execute %s", pp.c_str());
+    LOG(WARNING) << "unable to access/execute " << pp;
     return DONT_PROFILE_MISSING_PERF_EXECUTABLE;
   }
 
@@ -274,7 +274,7 @@ pid_t AlarmHelper::child_;
 
 void AlarmHelper::handler(int, siginfo_t *, void *)
 {
-  W_ALOGW("SIGALRM timeout");
+  LOG(WARNING) << "SIGALRM timeout";
   kill(child_, SIGKILL);
 }
 
@@ -290,12 +290,12 @@ bool get_camera_active()
 {
   int pipefds[2];
   if (pipe2(pipefds, O_CLOEXEC) != 0) {
-    W_ALOGE("pipe2() failed (%s)", strerror(errno));
+    PLOG(ERROR) << "pipe2() failed";
     return false;
   }
   pid_t pid = fork();
   if (pid == -1) {
-    W_ALOGE("fork() failed (%s)", strerror(errno));
+    PLOG(ERROR) << "fork() failed";
     close(pipefds[0]);
     close(pipefds[1]);
     return false;
@@ -310,7 +310,7 @@ bool get_camera_active()
     argv[slot++] = "media.camera";
     argv[slot++] = nullptr;
     execvp(argv[0], (char * const *)argv);
-    W_ALOGE("execvp() failed (%s)", strerror(errno));
+    PLOG(ERROR) << "execvp() failed";
     return false;
   }
   // parent
@@ -351,7 +351,7 @@ bool get_charging()
   std::string psdir("/sys/class/power_supply");
   DIR* dir = opendir(psdir.c_str());
   if (dir == NULL) {
-    W_ALOGE("Failed to open dir %s (%s)", psdir.c_str(), strerror(errno));
+    PLOG(ERROR) << "Failed to open dir " << psdir;
     return false;
   }
   struct dirent* e;
@@ -434,7 +434,7 @@ static void annotate_encoded_perf_profile(wireless_android_play_playlog::Android
     int iload = static_cast<int>(fload * 100.0);
     profile->set_sys_load_average(iload);
   } else {
-    W_ALOGE("Failed to read or scan /proc/loadavg (%s)", strerror(errno));
+    PLOG(ERROR) << "Failed to read or scan /proc/loadavg";
   }
 
   //
@@ -461,7 +461,7 @@ static void annotate_encoded_perf_profile(wireless_android_play_playlog::Android
     bool ison = (strstr(disp.c_str(), "PowerManagerService.Display") == 0);
     profile->set_display_on(ison);
   } else {
-    W_ALOGE("Failed to read /sys/power/wake_unlock (%s)", strerror(errno));
+    PLOG(ERROR) << "Failed to read /sys/power/wake_unlock";
   }
 }
 
@@ -550,7 +550,7 @@ static PROFILE_RESULT invoke_perf(Config& config,
       dup2(fileno(efp), STDERR_FILENO);
       dup2(fileno(efp), STDOUT_FILENO);
     } else {
-      W_ALOGW("unable to open %s for writing", perf_stderr_path.c_str());
+      PLOG(WARNING) << "unable to open " << perf_stderr_path << " for writing";
     }
 
     // marshall arguments
@@ -625,15 +625,15 @@ static PROFILE_RESULT invoke_perf(Config& config,
     pid_t reaped = TEMP_FAILURE_RETRY(waitpid(pid, &st, 0));
 
     if (reaped == -1) {
-      W_ALOGW("waitpid failed: %s", strerror(errno));
+      PLOG(WARNING) << "waitpid failed";
     } else if (WIFSIGNALED(st)) {
       if (WTERMSIG(st) == SIGHUP && config.ShouldStopProfiling()) {
         // That was us...
         return OK_PROFILE_COLLECTION;
       }
-      W_ALOGW("perf killed by signal %d", WTERMSIG(st));
+      LOG(WARNING) << "perf killed by signal " << WTERMSIG(st);
     } else if (WEXITSTATUS(st) != 0) {
-      W_ALOGW("perf bad exit status %d", WEXITSTATUS(st));
+      LOG(WARNING) << "perf bad exit status " << WEXITSTATUS(st);
     } else {
       return OK_PROFILE_COLLECTION;
     }
@@ -658,8 +658,7 @@ static void cleanup_destination_dir(const std::string& dest_dir)
     }
     closedir(dir);
   } else {
-    W_ALOGW("unable to open destination dir %s for cleanup",
-            dest_dir.c_str());
+    PLOG(WARNING) << "unable to open destination dir " << dest_dir << " for cleanup";
   }
 }
 
@@ -712,7 +711,7 @@ static bool post_process(const Config& config, int current_seq)
   produced.insert(current_seq);
   fp = fopen(produced_file_path.c_str(), "w");
   if (fp == NULL) {
-    W_ALOGW("Cannot write %s", produced_file_path.c_str());
+    PLOG(WARNING) << "Cannot write " <<  produced_file_path;
     return false;
   }
   for (std::set<int>::const_iterator iter = produced.begin();
@@ -757,7 +756,7 @@ static PROFILE_RESULT collect_profile(Config& config, int seq)
   struct stat statb;
   if (stat(data_file_path.c_str(), &statb) == 0) { // if file exists...
     if (unlink(data_file_path.c_str())) {          // then try to remove
-      W_ALOGW("unable to unlink previous perf.data file");
+      PLOG(WARNING) << "unable to unlink previous perf.data file";
     }
   }
 
@@ -842,7 +841,7 @@ static void set_seed(uint32_t use_fixed_seed)
     //
     seed = arc4random();
   }
-  W_ALOGI("random seed set to %u", seed);
+  LOG(INFO) << "random seed set to " << seed;
   // Distribute the 32-bit seed into the three 16-bit array
   // elements. The specific values being written do not especially
   // matter as long as we are setting them to something based on the seed.
@@ -858,7 +857,7 @@ static void CommonInit(uint32_t use_fixed_seed, const char* dest_dir) {
   std::stringstream oomscore_path;
   oomscore_path << "/proc/" << getpid() << "/oom_score_adj";
   if (!android::base::WriteStringToFile("0", oomscore_path.str())) {
-    W_ALOGE("unable to write to %s", oomscore_path.str().c_str());
+    LOG(ERROR) << "unable to write to " << oomscore_path.str();
   }
 
   set_seed(use_fixed_seed);
@@ -882,8 +881,7 @@ static void init(const Config& config)
 static void init(ConfigReader &config)
 {
   if (!config.readFile()) {
-    W_ALOGE("unable to open configuration file %s",
-            config.getConfigFilePath());
+    LOG(ERROR) << "unable to open configuration file " << config.getConfigFilePath();
   }
 
   CommonInit(static_cast<uint32_t>(config.getUnsignedValue("use_fixed_seed")),
@@ -920,20 +918,18 @@ static void ProfilingLoopImpl(ConfigFn config, UpdateFn update) {
     // Check for profiling enabled...
     CKPROFILE_RESULT ckresult = check_profiling_enabled(*config());
     if (ckresult != DO_COLLECT_PROFILE) {
-      W_ALOGI("profile collection skipped (%s)",
-              ckprofile_result_to_string(ckresult));
+      LOG(INFO) << "profile collection skipped (" << ckprofile_result_to_string(ckresult) << ")";
     } else {
       // Kick off the profiling run...
-      W_ALOGI("initiating profile collection");
+      LOG(INFO) << "initiating profile collection";
       PROFILE_RESULT result = collect_profile(*config(), seq);
       if (result != OK_PROFILE_COLLECTION) {
-        W_ALOGI("profile collection failed (%s)",
-                profile_result_to_string(result));
+        LOG(INFO) << "profile collection failed (" << profile_result_to_string(result) << ")";
       } else {
         if (post_process(*config(), seq)) {
           seq++;
         }
-        W_ALOGI("profile collection complete");
+        LOG(INFO) << "profile collection complete";
       }
     }
 
@@ -970,7 +966,7 @@ int perfprofd_main(int argc, char** argv, Config* config)
 {
   ConfigReader config_reader;
 
-  W_ALOGI("starting Android Wide Profiling daemon");
+  LOG(INFO) << "starting Android Wide Profiling daemon";
 
   parse_args(argc, argv);
   init(config_reader);
@@ -984,7 +980,7 @@ int perfprofd_main(int argc, char** argv, Config* config)
 
   // Early exit if we're not supposed to run on this build flavor
   if (is_debug_build != 1 && config->only_debug_build) {
-    W_ALOGI("early exit due to inappropriate build type");
+    LOG(INFO) << "early exit due to inappropriate build type";
     return 0;
   }
 
@@ -999,6 +995,6 @@ int perfprofd_main(int argc, char** argv, Config* config)
   };
   ProfilingLoopImpl(config_fn, reread_config);
 
-  W_ALOGI("finishing Android Wide Profiling daemon");
+  LOG(INFO) << "finishing Android Wide Profiling daemon";
   return 0;
 }
diff --git a/perfprofd/perfprofdutils.cc b/perfprofd/perfprofdutils.cc
deleted file mode 100644 (file)
index 32d55c7..0000000
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
-**
-** Copyright 2015, The Android Open Source Project
-**
-** Licensed under the Apache License, Version 2.0 (the "License");
-** you may not use this file except in compliance with the License.
-** You may obtain a copy of the License at
-**
-**     http://www.apache.org/licenses/LICENSE-2.0
-**
-** Unless required by applicable law or agreed to in writing, software
-** distributed under the License is distributed on an "AS IS" BASIS,
-** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-** See the License for the specific language governing permissions and
-** limitations under the License.
-*/
-
-#define LOG_TAG "perfprofd"
-
-#include <stdarg.h>
-#include <unistd.h>
-
-#include <utils/Log.h>
-
-#include "perfprofdutils.h"
-
-void perfprofd_log_error(const char *fmt, ...)
-{
-    va_list ap;
-    va_start(ap, fmt);
-    LOG_PRI_VA(ANDROID_LOG_ERROR, LOG_TAG, fmt, ap);
-    va_end(ap);
-}
-
-void perfprofd_log_warning(const char *fmt, ...)
-{
-    va_list ap;
-    va_start(ap, fmt);
-    LOG_PRI_VA(ANDROID_LOG_WARN, LOG_TAG, fmt, ap);
-    va_end(ap);
-}
-
-void perfprofd_log_info(const char *fmt, ...)
-{
-    va_list ap;
-    va_start(ap, fmt);
-    LOG_PRI_VA(ANDROID_LOG_INFO, LOG_TAG, fmt, ap);
-    va_end(ap);
-}
-
-void perfprofd_sleep(int seconds)
-{
-  sleep(seconds);
-}
diff --git a/perfprofd/perfprofdutils.h b/perfprofd/perfprofdutils.h
deleted file mode 100644 (file)
index b59070f..0000000
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
-**
-** Copyright 2015, The Android Open Source Project
-**
-** Licensed under the Apache License, Version 2.0 (the "License");
-** you may not use this file except in compliance with the License.
-** You may obtain a copy of the License at
-**
-**     http://www.apache.org/licenses/LICENSE-2.0
-**
-** Unless required by applicable law or agreed to in writing, software
-** distributed under the License is distributed on an "AS IS" BASIS,
-** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-** See the License for the specific language governing permissions and
-** limitations under the License.
-*/
-
-#include <sys/cdefs.h>
-
-__BEGIN_DECLS
-
-//
-// These routines are separated out from the core perfprofd so
-// as to be used as part of the unit test (see the README.txt
-// alongside the unit test for more info).
-//
-extern void perfprofd_log_error(const char *fmt, ...);
-extern void perfprofd_log_warning(const char *fmt, ...);
-extern void perfprofd_log_info(const char *fmt, ...);
-
-#define W_ALOGE perfprofd_log_error
-#define W_ALOGW perfprofd_log_warning
-#define W_ALOGI perfprofd_log_info
-
-__END_DECLS
index c173805..23d9adb 100644 (file)
@@ -1,25 +1,22 @@
 // Build the unit tests.
 
-perfprofd_test_cflags = [
-    "-Wall",
-    "-Werror",
-]
+cc_defaults {
+    name: "perfprofd_test_defaults",
 
-perfprofd_test_cppflags = [
-    "-Wno-sign-compare",
-    "-Wno-unused-parameter",
-]
-
-//
-// Static library with mockup utilities layer (called by unit test).
-//
-cc_library_static {
-    name: "libperfprofdmockutils",
+    cflags: [
+        "-Wall",
+        "-Werror",
+        "-O0",
+        "-g",
+    ],
+    cppflags: [
+        "-Wno-sign-compare",
+        "-Wno-unused-parameter",
+    ],
 
-    include_dirs: ["system/extras/perfprofd"],
-    cflags: perfprofd_test_cflags,
-    cppflags: perfprofd_test_cppflags,
-    srcs: ["perfprofdmockutils.cc"],
+    strip: {
+        keep_symbols: true,
+    },
 }
 
 //
@@ -27,12 +24,14 @@ cc_library_static {
 //
 cc_test {
     name: "perfprofd_test",
+    defaults: [
+        "perfprofd_test_defaults",
+    ],
     test_suites: ["device-tests"],
 
     stl: "libc++",
     static_libs: [
         "libperfprofdcore",
-        "libperfprofdmockutils",
         "libperfprofd_elf_read",
         "libbase",
     ],
@@ -40,9 +39,9 @@ cc_test {
         "libprotobuf-cpp-lite",
         "liblog",
     ],
-    srcs: ["perfprofd_test.cc"],
-    cflags: perfprofd_test_cflags,
-    cppflags: perfprofd_test_cppflags,
+    srcs: [
+        "perfprofd_test.cc",
+    ],
     data: [
         "canned.perf.data",
         "callchain.canned.perf.data",
index 98df371..802f4d1 100644 (file)
 
 #include <android-base/file.h>
 #include <android-base/logging.h>
+#include <android-base/macros.h>
 #include <android-base/properties.h>
 #include <android-base/stringprintf.h>
+#include <android-base/strings.h>
 #include <android-base/test_utils.h>
 #include <gtest/gtest.h>
 
 #include "config.h"
 #include "configreader.h"
 #include "perfprofdcore.h"
-#include "perfprofdutils.h"
-#include "perfprofdmockutils.h"
 #include "symbolizer.h"
 
 #include "perf_profile.pb.h"
 //
 static std::string gExecutableRealpath;
 
+namespace {
+
+using android::base::LogId;
+using android::base::LogSeverity;
+
+static std::vector<std::string>* gTestLogMessages = nullptr;
+
+static void TestLogFunction(LogId log_id ATTRIBUTE_UNUSED,
+                            LogSeverity severity,
+                            const char* tag,
+                            const char* file ATTRIBUTE_UNUSED,
+                            unsigned int line ATTRIBUTE_UNUSED,
+                            const char* message) {
+  constexpr char log_characters[] = "VDIWEFF";
+  char severity_char = log_characters[severity];
+  gTestLogMessages->push_back(android::base::StringPrintf("%c: %s", severity_char, message));
+}
+
+static void InitTestLog() {
+  CHECK(gTestLogMessages == nullptr);
+  gTestLogMessages = new std::vector<std::string>();
+}
+static void ClearTestLog() {
+  CHECK(gTestLogMessages != nullptr);
+  delete gTestLogMessages;
+  gTestLogMessages = nullptr;
+}
+static std::string JoinTestLog(const char* delimiter) {
+  CHECK(gTestLogMessages != nullptr);
+  return android::base::Join(*gTestLogMessages, delimiter);
+}
+
+}  // namespace
+
 // Path to perf executable on device
 #define PERFPATH "/system/bin/perf"
 
@@ -57,12 +91,14 @@ static std::string gExecutableRealpath;
 class PerfProfdTest : public testing::Test {
  protected:
   virtual void SetUp() {
-    mock_perfprofdutils_init();
+    InitTestLog();
+    android::base::SetLogger(TestLogFunction);
     create_dirs();
   }
 
   virtual void TearDown() {
-    mock_perfprofdutils_finish();
+    android::base::SetLogger(android::base::StderrLogger);
+    ClearTestLog();
 
     // TODO: proper management of test files. For now, use old system() code.
     for (const auto dir : { &dest_dir, &conf_dir }) {
@@ -211,7 +247,7 @@ class PerfProfdRunner {
   struct LoggingConfig : public Config {
     void Sleep(size_t seconds) override {
       // Log sleep calls but don't sleep.
-      perfprofd_log_info("sleep %d seconds", seconds);
+      LOG(INFO) << "sleep " << seconds << " seconds";
     }
 
     bool IsProfilingEnabled() const override {
@@ -219,8 +255,7 @@ class PerfProfdRunner {
       // Check for existence of semaphore file in config directory
       //
       if (access(config_directory.c_str(), F_OK) == -1) {
-        W_ALOGW("unable to open config directory %s: (%s)",
-                config_directory.c_str(), strerror(errno));
+        PLOG(WARNING) << "unable to open config directory " << config_directory;
         return false;
       }
 
@@ -388,13 +423,12 @@ TEST_F(PerfProfdTest, MissingGMS)
   // Verify log contents
   const std::string expected = RAW_RESULT(
       I: sleep 90 seconds
-      W: unable to open config directory /does/not/exist: (No such file or directory)
+      W: unable to open config directory /does/not/exist: No such file or directory
       I: profile collection skipped (missing config directory)
                                           );
 
   // check to make sure entire log matches
-  compareLogMessages(mock_perfprofdutils_getlogged(),
-                     expected, "MissingGMS");
+  compareLogMessages(JoinTestLog(" "), expected, "MissingGMS");
 }
 
 
@@ -430,8 +464,7 @@ TEST_F(PerfProfdTest, MissingOptInSemaphoreFile)
       I: profile collection skipped (missing config directory)
                                           );
   // check to make sure log excerpt matches
-  compareLogMessages(mock_perfprofdutils_getlogged(),
-                     expected, "MissingOptInSemaphoreFile");
+  compareLogMessages(JoinTestLog(" "), expected, "MissingOptInSemaphoreFile");
 }
 
 TEST_F(PerfProfdTest, MissingPerfExecutable)
@@ -468,8 +501,7 @@ TEST_F(PerfProfdTest, MissingPerfExecutable)
       I: profile collection skipped (missing 'perf' executable)
                                           );
   // check to make sure log excerpt matches
-  compareLogMessages(mock_perfprofdutils_getlogged(),
-                     expected, "MissingPerfExecutable");
+  compareLogMessages(JoinTestLog(" "), expected, "MissingPerfExecutable");
 }
 
 TEST_F(PerfProfdTest, BadPerfRun)
@@ -506,8 +538,7 @@ TEST_F(PerfProfdTest, BadPerfRun)
                                           );
 
   // check to make sure log excerpt matches
-  compareLogMessages(mock_perfprofdutils_getlogged(),
-                     expected, "BadPerfRun");
+  compareLogMessages(JoinTestLog(" "), expected, "BadPerfRun");
 }
 
 TEST_F(PerfProfdTest, ConfigFileParsing)
@@ -545,8 +576,7 @@ TEST_F(PerfProfdTest, ConfigFileParsing)
                                           );
 
   // check to make sure log excerpt matches
-  compareLogMessages(mock_perfprofdutils_getlogged(),
-                     expected, "ConfigFileParsing");
+  compareLogMessages(JoinTestLog(" "), expected, "ConfigFileParsing");
 }
 
 TEST_F(PerfProfdTest, ProfileCollectionAnnotations)
@@ -858,8 +888,7 @@ TEST_F(PerfProfdTest, BasicRunWithLivePerf)
       I: finishing Android Wide Profiling daemon
                                           );
   // check to make sure log excerpt matches
-  compareLogMessages(mock_perfprofdutils_getlogged(),
-                     expandVars(expected), "BasicRunWithLivePerf", true);
+  compareLogMessages(JoinTestLog(" "), expandVars(expected), "BasicRunWithLivePerf", true);
 }
 
 TEST_F(PerfProfdTest, MultipleRunWithLivePerf)
@@ -926,8 +955,7 @@ TEST_F(PerfProfdTest, MultipleRunWithLivePerf)
       I: finishing Android Wide Profiling daemon
                                           );
   // check to make sure log excerpt matches
-  compareLogMessages(mock_perfprofdutils_getlogged(),
-                     expandVars(expected), "BasicRunWithLivePerf", true);
+  compareLogMessages(JoinTestLog(" "), expandVars(expected), "BasicRunWithLivePerf", true);
 }
 
 TEST_F(PerfProfdTest, CallChainRunWithLivePerf)
@@ -979,8 +1007,7 @@ TEST_F(PerfProfdTest, CallChainRunWithLivePerf)
       I: finishing Android Wide Profiling daemon
                                           );
   // check to make sure log excerpt matches
-  compareLogMessages(mock_perfprofdutils_getlogged(),
-                     expandVars(expected), "CallChainRunWithLivePerf", true);
+  compareLogMessages(JoinTestLog(" "), expandVars(expected), "CallChainRunWithLivePerf", true);
 }
 
 int main(int argc, char **argv) {