1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
|
/*
**
** 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 "perfprofd_perf.h"
#include <inttypes.h>
#include <signal.h>
#include <sys/wait.h>
#include <unistd.h>
#include <algorithm>
#include <cerrno>
#include <cstdio>
#include <cstring>
#include <memory>
#include <vector>
#include <android-base/file.h>
#include <android-base/logging.h>
#include <android-base/stringprintf.h>
#include <android-base/strings.h>
#include <android-base/unique_fd.h>
#include "config.h"
namespace android {
namespace perfprofd {
namespace {
std::unordered_set<std::string>& GetSupportedPerfCountersInternal() {
static std::unordered_set<std::string>& vec = *new std::unordered_set<std::string>();
return vec;
}
} // namespace
//
// Invoke "perf record". Return value is OK_PROFILE_COLLECTION for
// success, or some other error code if something went wrong.
//
PerfResult InvokePerf(Config& config,
const std::string &perf_path,
const char *stack_profile_opt,
unsigned duration,
const std::string &data_file_path,
const std::string &perf_stderr_path)
{
std::vector<std::string> argv_backing;
std::vector<const char*> argv_vector;
char paranoid_env[] = "PERFPROFD_DISABLE_PERF_EVENT_PARANOID_CHANGE=1";
char* envp[2] = {paranoid_env, nullptr};
{
auto add = [&argv_backing](auto arg) {
argv_backing.push_back(arg);
};
add(perf_path);
add("record");
// -o perf.data
add("-o");
add(data_file_path);
// -c/f N
std::string p_str;
if (config.sampling_frequency > 0) {
add("-f");
add(android::base::StringPrintf("%u", config.sampling_frequency));
} else if (config.sampling_period > 0) {
add("-c");
add(android::base::StringPrintf("%u", config.sampling_period));
}
if (!config.event_config.empty()) {
const std::unordered_set<std::string>& supported = GetSupportedPerfCountersInternal();
for (const auto& event_set : config.event_config) {
if (event_set.events.empty()) {
LOG(WARNING) << "Unexpected empty event set";
continue;
}
std::ostringstream event_str;
bool added = false;
for (const std::string& event : event_set.events) {
if (supported.find(event) == supported.end()) {
LOG(WARNING) << "Event " << event << " is unsupported.";
if (config.fail_on_unsupported_events) {
return PerfResult::kUnsupportedEvent;
}
continue;
}
if (added) {
event_str << ',';
}
event_str << event;
added = true;
}
if (!added) {
continue;
}
if (event_set.sampling_period > 0) {
add("-c");
add(std::to_string(event_set.sampling_period));
}
add(event_set.group ? "--group" : "-e");
add(event_str.str());
}
}
// -g if desired
if (stack_profile_opt != nullptr) {
add(stack_profile_opt);
add("-m");
add("8192");
}
if (config.process < 0) {
// system wide profiling
add("-a");
} else {
add("-p");
add(std::to_string(config.process));
}
// no need for kernel or other symbols
add("--no-dump-kernel-symbols");
add("--no-dump-symbols");
// sleep <duration>
add("--duration");
add(android::base::StringPrintf("%u", duration));
// Now create the char* buffer.
argv_vector.resize(argv_backing.size() + 1, nullptr);
std::transform(argv_backing.begin(),
argv_backing.end(),
argv_vector.begin(),
[](const std::string& in) { return in.c_str(); });
}
pid_t pid = fork();
if (pid == -1) {
PLOG(ERROR) << "Fork failed";
return PerfResult::kForkFailed;
}
if (pid == 0) {
// child
// Open file to receive stderr/stdout from perf
FILE *efp = fopen(perf_stderr_path.c_str(), "w");
if (efp) {
dup2(fileno(efp), STDERR_FILENO);
dup2(fileno(efp), STDOUT_FILENO);
} else {
PLOG(WARNING) << "unable to open " << perf_stderr_path << " for writing";
}
// record the final command line in the error output file for
// posterity/debugging purposes
fprintf(stderr, "perf invocation (pid=%d):\n", getpid());
for (unsigned i = 0; argv_vector[i] != nullptr; ++i) {
fprintf(stderr, "%s%s", i ? " " : "", argv_vector[i]);
}
fprintf(stderr, "\n");
// exec
execvpe(argv_vector[0], const_cast<char* const*>(argv_vector.data()), envp);
fprintf(stderr, "exec failed: %s\n", strerror(errno));
exit(1);
} else {
// parent
// Try to sleep.
config.Sleep(duration);
// We may have been woken up to stop profiling.
if (config.ShouldStopProfiling()) {
// Send SIGHUP to simpleperf to make it stop.
kill(pid, SIGHUP);
}
// Wait for the child, so it's reaped correctly.
int st = 0;
pid_t reaped = TEMP_FAILURE_RETRY(waitpid(pid, &st, 0));
auto print_perferr = [&perf_stderr_path]() {
std::string tmp;
if (android::base::ReadFileToString(perf_stderr_path, &tmp)) {
LOG(WARNING) << tmp;
} else {
PLOG(WARNING) << "Could not read " << perf_stderr_path;
}
};
if (reaped == -1) {
PLOG(WARNING) << "waitpid failed";
} else if (WIFSIGNALED(st)) {
if (WTERMSIG(st) == SIGHUP && config.ShouldStopProfiling()) {
// That was us...
return PerfResult::kOK;
}
LOG(WARNING) << "perf killed by signal " << WTERMSIG(st);
print_perferr();
} else if (WEXITSTATUS(st) != 0) {
LOG(WARNING) << "perf bad exit status " << WEXITSTATUS(st);
print_perferr();
} else {
return PerfResult::kOK;
}
}
return PerfResult::kRecordFailed;
}
bool FindSupportedPerfCounters(const std::string& perf_path) {
const char* argv[] = { perf_path.c_str(), "list", nullptr };
char paranoid_env[] = "PERFPROFD_DISABLE_PERF_EVENT_PARANOID_CHANGE=1";
char* envp[2] = {paranoid_env, nullptr};
base::unique_fd link[2];
{
int link_fd[2];
if (pipe(link_fd) == -1) {
PLOG(ERROR) << "Pipe failed";
return false;
}
link[0].reset(link_fd[0]);
link[1].reset(link_fd[1]);
}
pid_t pid = fork();
if (pid == -1) {
PLOG(ERROR) << "Fork failed";
return PerfResult::kForkFailed;
}
if (pid == 0) {
// Child
// Redirect stdout and stderr.
dup2(link[1].get(), STDOUT_FILENO);
dup2(link[1].get(), STDERR_FILENO);
link[0].reset();
link[1].reset();
// exec
execvpe(argv[0], const_cast<char* const*>(argv), envp);
PLOG(WARNING) << "exec failed";
exit(1);
__builtin_unreachable();
}
link[1].reset();
std::string result;
if (!android::base::ReadFdToString(link[0].get(), &result)) {
PLOG(WARNING) << perf_path << " list reading failed.";
}
link[0].reset();
int status_code;
if (waitpid(pid, &status_code, 0) == -1) {
LOG(WARNING) << "Failed to wait for " << perf_path << " list";
return false;
}
if (!WIFEXITED(status_code) || WEXITSTATUS(status_code) != 0) {
LOG(WARNING) << perf_path << " list did not exit normally.";
return false;
}
std::unordered_set<std::string>& supported = GetSupportedPerfCountersInternal();
supported.clear();
// Could implement something with less memory requirements. But for now this is good
// enough.
std::vector<std::string> lines = base::Split(result, "\n");
for (const std::string& line : lines) {
if (line.length() < 2 || line.compare(0, 2, " ") != 0) {
continue;
}
const size_t comment = line.find('#');
const size_t space = line.find(' ', 2);
size_t end = std::min(space, comment);
if (end != std::string::npos) {
// Scan backwards.
--end;
while (end > 2 && isspace(line[end])) {
end--;
}
}
if (end > 2) {
supported.insert(line.substr(2, end - 2));
}
}
return true;
}
const std::unordered_set<std::string>& GetSupportedPerfCounters() {
return GetSupportedPerfCountersInternal();
}
} // namespace perfprofd
} // namespace android
|