blob: 2fa43ede12d4de2f50bbf037b439f94b7ef7910b [file] [log] [blame]
Colin Crossf45fa6b2012-03-26 12:38:26 -07001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <dirent.h>
18#include <errno.h>
19#include <fcntl.h>
Felipe Lemee184f662016-10-27 10:04:47 -070020#include <libgen.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070021#include <limits.h>
Felipe Leme7447d7c2016-11-03 18:12:22 -070022#include <math.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070023#include <poll.h>
24#include <signal.h>
25#include <stdarg.h>
26#include <stdio.h>
27#include <stdlib.h>
28#include <string.h>
Felipe Lemecf6a8b42016-03-11 10:38:19 -080029#include <sys/capability.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070030#include <sys/inotify.h>
Felipe Lemee184f662016-10-27 10:04:47 -070031#include <sys/klog.h>
32#include <sys/prctl.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070033#include <sys/stat.h>
34#include <sys/time.h>
35#include <sys/wait.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070036#include <time.h>
37#include <unistd.h>
Felipe Lemee184f662016-10-27 10:04:47 -070038#include <string>
Felipe Leme36b3f6f2015-11-19 15:41:04 -080039#include <vector>
Colin Crossf45fa6b2012-03-26 12:38:26 -070040
Felipe Leme71bbfc52015-11-23 14:14:51 -080041#define LOG_TAG "dumpstate"
Mark Salyzyn261a7332016-05-24 12:38:40 -070042
Mark Salyzyn290f4b92016-05-16 08:33:59 -070043#include <android-base/file.h>
Felipe Leme96c2bbb2016-09-26 09:21:21 -070044#include <android-base/properties.h>
Felipe Leme2b9b06c2016-10-14 09:13:06 -070045#include <android-base/stringprintf.h>
Felipe Leme7447d7c2016-11-03 18:12:22 -070046#include <android-base/strings.h>
Jeff Brownbf7f4922012-06-07 16:40:01 -070047#include <cutils/debugger.h>
Felipe Leme71bbfc52015-11-23 14:14:51 -080048#include <cutils/log.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070049#include <cutils/properties.h>
50#include <cutils/sockets.h>
51#include <private/android_filesystem_config.h>
52
Robert Craig95798372013-04-04 06:33:10 -040053#include <selinux/android.h>
54
Colin Crossf45fa6b2012-03-26 12:38:26 -070055#include "dumpstate.h"
56
Felipe Lemefd8affa2016-09-30 17:38:57 -070057#define SU_PATH "/system/xbin/su"
58
Jeff Brown1dc94e32014-09-11 14:15:27 -070059static const int64_t NANOS_PER_SEC = 1000000000;
60
Felipe Leme61884122016-06-13 09:23:30 -070061static const int TRACE_DUMP_TIMEOUT_MS = 10000; // 10 seconds
62
Felipe Lemee844a9d2016-09-21 15:01:39 -070063// TODO: temporary variables and functions used during C++ refactoring
64static Dumpstate& ds = Dumpstate::GetInstance();
Felipe Leme9a523ae2016-10-20 15:10:33 -070065static int RunCommand(const std::string& title, const std::vector<std::string>& full_command,
Felipe Leme678727a2016-09-21 17:22:11 -070066 const CommandOptions& options = CommandOptions::DEFAULT) {
Felipe Leme9a523ae2016-10-20 15:10:33 -070067 return ds.RunCommand(title, full_command, options);
Felipe Leme678727a2016-09-21 17:22:11 -070068}
Felipe Leme4c2d6632016-09-28 14:32:00 -070069static bool IsDryRun() {
70 return Dumpstate::GetInstance().IsDryRun();
71}
Felipe Lemee844a9d2016-09-21 15:01:39 -070072
Jeff Brownbf7f4922012-06-07 16:40:01 -070073/* list of native processes to include in the native dumps */
Andy Hung5c04e742016-04-13 19:35:34 -070074// This matches the /proc/pid/exe link instead of /proc/pid/cmdline.
Jeff Brownbf7f4922012-06-07 16:40:01 -070075static const char* native_processes_to_dump[] = {
Andy Hung9609bbd2015-12-15 12:42:50 -080076 "/system/bin/audioserver",
Chien-Yu Chenf5248da2016-01-28 14:23:03 -080077 "/system/bin/cameraserver",
James Dong1fc4f802012-09-10 16:08:48 -070078 "/system/bin/drmserver",
Andy Hung5c04e742016-04-13 19:35:34 -070079 "/system/bin/mediacodec", // media.codec
80 "/system/bin/mediadrmserver",
81 "/system/bin/mediaextractor", // media.extractor
Jeff Brownbf7f4922012-06-07 16:40:01 -070082 "/system/bin/mediaserver",
83 "/system/bin/sdcard",
84 "/system/bin/surfaceflinger",
keunyoungd907b322015-10-16 15:21:43 -070085 "/system/bin/vehicle_network_service",
Jeff Brownbf7f4922012-06-07 16:40:01 -070086 NULL,
87};
88
Felipe Lemee844a9d2016-09-21 15:01:39 -070089/* Most simple commands have 10 as timeout, so 5 is a good estimate */
Felipe Leme46b85da2016-11-21 17:40:45 -080090static const int32_t WEIGHT_FILE = 5;
Felipe Lemee844a9d2016-09-21 15:01:39 -070091
Felipe Leme7447d7c2016-11-03 18:12:22 -070092// Reasonable value for max stats.
93static const int STATS_MAX_N_RUNS = 1000;
94static const long STATS_MAX_AVERAGE = 100000;
95
Felipe Leme30dbfa12016-09-02 12:43:26 -070096CommandOptions CommandOptions::DEFAULT = CommandOptions::WithTimeout(10).Build();
Felipe Lemebda15a02016-11-16 17:48:25 -080097CommandOptions Dumpstate::DEFAULT_DUMPSYS = CommandOptions::WithTimeout(30).Build();
Felipe Leme30dbfa12016-09-02 12:43:26 -070098CommandOptions CommandOptions::AS_ROOT_5 = CommandOptions::WithTimeout(5).AsRoot().Build();
99CommandOptions CommandOptions::AS_ROOT_10 = CommandOptions::WithTimeout(10).AsRoot().Build();
100CommandOptions CommandOptions::AS_ROOT_20 = CommandOptions::WithTimeout(20).AsRoot().Build();
101
Felipe Lemebda15a02016-11-16 17:48:25 -0800102CommandOptions::CommandOptionsBuilder::CommandOptionsBuilder(int64_t timeout) : values(timeout) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700103}
104
105CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::Always() {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700106 values.always_ = true;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700107 return *this;
108}
109
110CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::AsRoot() {
Felipe Leme46b85da2016-11-21 17:40:45 -0800111 values.account_mode_ = SU_ROOT;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700112 return *this;
113}
114
115CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::DropRoot() {
Felipe Leme46b85da2016-11-21 17:40:45 -0800116 values.account_mode_ = DROP_ROOT;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700117 return *this;
118}
119
120CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::RedirectStderr() {
Felipe Leme46b85da2016-11-21 17:40:45 -0800121 values.output_mode_ = REDIRECT_TO_STDERR;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700122 return *this;
123}
124
125CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::Log(
126 const std::string& message) {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700127 values.logging_message_ = message;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700128 return *this;
129}
130
131CommandOptions CommandOptions::CommandOptionsBuilder::Build() {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700132 return CommandOptions(values);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700133}
134
Felipe Lemebda15a02016-11-16 17:48:25 -0800135CommandOptions::CommandOptionsValues::CommandOptionsValues(int64_t timeout)
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700136 : timeout_(timeout),
137 always_(false),
Felipe Leme46b85da2016-11-21 17:40:45 -0800138 account_mode_(DONT_DROP_ROOT),
139 output_mode_(NORMAL_OUTPUT),
Felipe Leme9a523ae2016-10-20 15:10:33 -0700140 logging_message_("") {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700141}
142
Felipe Leme9a523ae2016-10-20 15:10:33 -0700143CommandOptions::CommandOptions(const CommandOptionsValues& values) : values(values) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700144}
145
Felipe Lemebda15a02016-11-16 17:48:25 -0800146int64_t CommandOptions::Timeout() const {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700147 return values.timeout_;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700148}
149
150bool CommandOptions::Always() const {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700151 return values.always_;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700152}
153
Felipe Leme46b85da2016-11-21 17:40:45 -0800154PrivilegeMode CommandOptions::PrivilegeMode() const {
155 return values.account_mode_;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700156}
157
Felipe Leme46b85da2016-11-21 17:40:45 -0800158OutputMode CommandOptions::OutputMode() const {
159 return values.output_mode_;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700160}
161
162std::string CommandOptions::LoggingMessage() const {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700163 return values.logging_message_;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700164}
165
Felipe Lemebda15a02016-11-16 17:48:25 -0800166CommandOptions::CommandOptionsBuilder CommandOptions::WithTimeout(int64_t timeout) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700167 return CommandOptions::CommandOptionsBuilder(timeout);
168}
169
Felipe Lemed071c682016-10-20 16:48:00 -0700170Dumpstate::Dumpstate(const std::string& version, bool dry_run, const std::string& build_type)
Felipe Leme75876a22016-10-27 16:31:27 -0700171 : pid_(getpid()),
172 version_(version),
173 now_(time(nullptr)),
174 dry_run_(dry_run),
175 build_type_(build_type) {
Felipe Lemee844a9d2016-09-21 15:01:39 -0700176}
177
178Dumpstate& Dumpstate::GetInstance() {
Felipe Lemed071c682016-10-20 16:48:00 -0700179 static Dumpstate singleton_(android::base::GetProperty("dumpstate.version", VERSION_CURRENT),
180 android::base::GetBoolProperty("dumpstate.dry_run", false),
Felipe Lemed80e6b62016-10-03 13:08:14 -0700181 android::base::GetProperty("ro.build.type", "(unknown)"));
Felipe Leme9a523ae2016-10-20 15:10:33 -0700182 return singleton_;
Felipe Lemee844a9d2016-09-21 15:01:39 -0700183}
184
Felipe Leme46b85da2016-11-21 17:40:45 -0800185DurationReporter::DurationReporter(const std::string& title, bool log_only)
186 : title_(title), log_only_(log_only) {
Felipe Leme678727a2016-09-21 17:22:11 -0700187 if (!title_.empty()) {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700188 started_ = DurationReporter::Nanotime();
Felipe Leme78f2c862015-12-21 09:55:22 -0800189 }
190}
191
192DurationReporter::~DurationReporter() {
Felipe Leme678727a2016-09-21 17:22:11 -0700193 if (!title_.empty()) {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700194 uint64_t elapsed = DurationReporter::Nanotime() - started_;
Felipe Leme46b85da2016-11-21 17:40:45 -0800195 if (log_only_) {
Felipe Leme678727a2016-09-21 17:22:11 -0700196 MYLOGD("Duration of '%s': %.3fs\n", title_.c_str(), (float)elapsed / NANOS_PER_SEC);
Felipe Leme46b85da2016-11-21 17:40:45 -0800197 } else {
198 // Use "Yoda grammar" to make it easier to grep|sort sections.
199 printf("------ %.3fs was the duration of '%s' ------\n", (float)elapsed / NANOS_PER_SEC,
200 title_.c_str());
201 fflush(stdout);
Felipe Leme608385d2016-02-01 10:35:38 -0800202 }
Felipe Leme78f2c862015-12-21 09:55:22 -0800203 }
204}
205
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700206uint64_t DurationReporter::DurationReporter::Nanotime() {
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800207 struct timespec ts;
208 clock_gettime(CLOCK_MONOTONIC, &ts);
Felipe Leme78f2c862015-12-21 09:55:22 -0800209 return (uint64_t) ts.tv_sec * NANOS_PER_SEC + ts.tv_nsec;
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800210}
211
Felipe Leme7447d7c2016-11-03 18:12:22 -0700212const int32_t Progress::kDefaultMax = 5000;
213
214Progress::Progress(const std::string& path) : Progress(Progress::kDefaultMax, 1.1, path) {
215}
216
217Progress::Progress(int32_t initial_max, int32_t progress, float growth_factor)
218 : Progress(initial_max, growth_factor, "") {
219 progress_ = progress;
220}
221
222Progress::Progress(int32_t initial_max, float growth_factor, const std::string& path)
223 : initial_max_(initial_max),
224 progress_(0),
225 max_(initial_max),
226 growth_factor_(growth_factor),
227 n_runs_(0),
228 average_max_(0),
229 path_(path) {
230 if (!path_.empty()) {
231 Load();
232 }
233}
234
235void Progress::Load() {
236 MYLOGD("Loading stats from %s\n", path_.c_str());
237 std::string content;
238 if (!android::base::ReadFileToString(path_, &content)) {
239 MYLOGI("Could not read stats from %s; using max of %d\n", path_.c_str(), max_);
240 return;
241 }
242 if (content.empty()) {
243 MYLOGE("No stats (empty file) on %s; using max of %d\n", path_.c_str(), max_);
244 return;
245 }
246 std::vector<std::string> lines = android::base::Split(content, "\n");
247
248 if (lines.size() < 1) {
249 MYLOGE("Invalid stats on file %s: not enough lines (%d). Using max of %d\n", path_.c_str(),
250 (int)lines.size(), max_);
251 return;
252 }
253 char* ptr;
254 n_runs_ = strtol(lines[0].c_str(), &ptr, 10);
255 average_max_ = strtol(ptr, nullptr, 10);
256 if (n_runs_ <= 0 || average_max_ <= 0 || n_runs_ > STATS_MAX_N_RUNS ||
257 average_max_ > STATS_MAX_AVERAGE) {
258 MYLOGE("Invalid stats line on file %s: %s\n", path_.c_str(), lines[0].c_str());
259 initial_max_ = Progress::kDefaultMax;
260 } else {
261 initial_max_ = average_max_;
262 }
263 max_ = initial_max_;
264
265 MYLOGI("Average max progress: %d in %d runs; estimated max: %d\n", average_max_, n_runs_, max_);
266}
267
268void Progress::Save() {
269 int32_t total = n_runs_ * average_max_ + progress_;
270 int32_t runs = n_runs_ + 1;
271 int32_t average = floor(((float)total) / runs);
272 MYLOGI("Saving stats (total=%d, runs=%d, average=%d) on %s\n", total, runs, average,
273 path_.c_str());
274 if (path_.empty()) {
275 return;
276 }
277
278 std::string content = android::base::StringPrintf("%d %d\n", runs, average);
279 if (!android::base::WriteStringToFile(content, path_)) {
280 MYLOGE("Could not save stats on %s\n", path_.c_str());
281 }
282}
283
284int32_t Progress::Get() const {
285 return progress_;
286}
287
288bool Progress::Inc(int32_t delta) {
289 bool changed = false;
290 if (delta >= 0) {
291 progress_ += delta;
292 if (progress_ > max_) {
293 int32_t old_max = max_;
294 max_ = floor((float)progress_ * growth_factor_);
295 MYLOGD("Adjusting max progress from %d to %d\n", old_max, max_);
296 changed = true;
297 }
298 }
299 return changed;
300}
301
302int32_t Progress::GetMax() const {
303 return max_;
304}
305
306int32_t Progress::GetInitialMax() const {
307 return initial_max_;
308}
309
310void Progress::Dump(int fd, const std::string& prefix) const {
311 const char* pr = prefix.c_str();
312 dprintf(fd, "%sprogress: %d\n", pr, progress_);
313 dprintf(fd, "%smax: %d\n", pr, max_);
314 dprintf(fd, "%sinitial_max: %d\n", pr, initial_max_);
315 dprintf(fd, "%sgrowth_factor: %0.2f\n", pr, growth_factor_);
316 dprintf(fd, "%spath: %s\n", pr, path_.c_str());
317 dprintf(fd, "%sn_runs: %d\n", pr, n_runs_);
318 dprintf(fd, "%saverage_max: %d\n", pr, average_max_);
319}
320
Felipe Leme2b9b06c2016-10-14 09:13:06 -0700321bool Dumpstate::IsDryRun() const {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700322 return dry_run_;
Felipe Leme4c2d6632016-09-28 14:32:00 -0700323}
324
Felipe Leme2b9b06c2016-10-14 09:13:06 -0700325bool Dumpstate::IsUserBuild() const {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700326 return "user" == build_type_;
Felipe Lemee844a9d2016-09-21 15:01:39 -0700327}
328
Felipe Leme75876a22016-10-27 16:31:27 -0700329bool Dumpstate::IsZipping() const {
330 return zip_writer_ != nullptr;
331}
332
Felipe Leme2b9b06c2016-10-14 09:13:06 -0700333std::string Dumpstate::GetPath(const std::string& suffix) const {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700334 return android::base::StringPrintf("%s/%s-%s%s", bugreport_dir_.c_str(), base_name_.c_str(),
Felipe Leme2b9b06c2016-10-14 09:13:06 -0700335 name_.c_str(), suffix.c_str());
Felipe Lemebbaf3c12016-10-11 14:32:25 -0700336}
337
Felipe Leme7447d7c2016-11-03 18:12:22 -0700338void Dumpstate::SetProgress(std::unique_ptr<Progress> progress) {
339 progress_ = std::move(progress);
340}
341
John Spurlock5ecd4be2014-01-29 14:14:40 -0500342void for_each_userid(void (*func)(int), const char *header) {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700343 if (IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700344
John Spurlock5ecd4be2014-01-29 14:14:40 -0500345 DIR *d;
346 struct dirent *de;
347
348 if (header) printf("\n------ %s ------\n", header);
349 func(0);
350
351 if (!(d = opendir("/data/system/users"))) {
352 printf("Failed to open /data/system/users (%s)\n", strerror(errno));
353 return;
354 }
355
356 while ((de = readdir(d))) {
357 int userid;
358 if (de->d_type != DT_DIR || !(userid = atoi(de->d_name))) {
359 continue;
360 }
361 func(userid);
362 }
363
364 closedir(d);
365}
366
Colin Cross0c22e8b2012-11-02 15:46:56 -0700367static void __for_each_pid(void (*helper)(int, const char *, void *), const char *header, void *arg) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700368 DIR *d;
369 struct dirent *de;
370
371 if (!(d = opendir("/proc"))) {
372 printf("Failed to open /proc (%s)\n", strerror(errno));
373 return;
374 }
375
Felipe Leme635ca312016-01-05 14:23:02 -0800376 if (header) printf("\n------ %s ------\n", header);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700377 while ((de = readdir(d))) {
378 int pid;
379 int fd;
380 char cmdpath[255];
381 char cmdline[255];
382
383 if (!(pid = atoi(de->d_name))) {
384 continue;
385 }
386
Colin Crossf45fa6b2012-03-26 12:38:26 -0700387 memset(cmdline, 0, sizeof(cmdline));
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800388
389 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/cmdline", pid);
390 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
391 TEMP_FAILURE_RETRY(read(fd, cmdline, sizeof(cmdline) - 2));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700392 close(fd);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800393 if (cmdline[0]) {
394 helper(pid, cmdline, arg);
395 continue;
396 }
397 }
398
399 // if no cmdline, a kernel thread has comm
400 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/comm", pid);
401 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
402 TEMP_FAILURE_RETRY(read(fd, cmdline + 1, sizeof(cmdline) - 4));
403 close(fd);
404 if (cmdline[1]) {
405 cmdline[0] = '[';
406 size_t len = strcspn(cmdline, "\f\b\r\n");
407 cmdline[len] = ']';
408 cmdline[len+1] = '\0';
409 }
410 }
411 if (!cmdline[0]) {
412 strcpy(cmdline, "N/A");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700413 }
Colin Cross0c22e8b2012-11-02 15:46:56 -0700414 helper(pid, cmdline, arg);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700415 }
416
417 closedir(d);
418}
419
Colin Cross0c22e8b2012-11-02 15:46:56 -0700420static void for_each_pid_helper(int pid, const char *cmdline, void *arg) {
Felipe Leme8620bb42015-11-10 11:04:45 -0800421 for_each_pid_func *func = (for_each_pid_func*) arg;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700422 func(pid, cmdline);
423}
424
425void for_each_pid(for_each_pid_func func, const char *header) {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700426 if (IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700427
Felipe Leme515eb0d2015-12-14 15:09:56 -0800428 __for_each_pid(for_each_pid_helper, header, (void *) func);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700429}
430
431static void for_each_tid_helper(int pid, const char *cmdline, void *arg) {
432 DIR *d;
433 struct dirent *de;
434 char taskpath[255];
Felipe Leme8620bb42015-11-10 11:04:45 -0800435 for_each_tid_func *func = (for_each_tid_func *) arg;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700436
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700437 snprintf(taskpath, sizeof(taskpath), "/proc/%d/task", pid);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700438
439 if (!(d = opendir(taskpath))) {
440 printf("Failed to open %s (%s)\n", taskpath, strerror(errno));
441 return;
442 }
443
444 func(pid, pid, cmdline);
445
446 while ((de = readdir(d))) {
447 int tid;
448 int fd;
449 char commpath[255];
450 char comm[255];
451
452 if (!(tid = atoi(de->d_name))) {
453 continue;
454 }
455
456 if (tid == pid)
457 continue;
458
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700459 snprintf(commpath, sizeof(commpath), "/proc/%d/comm", tid);
Colin Cross1493a392012-11-07 11:25:31 -0800460 memset(comm, 0, sizeof(comm));
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700461 if ((fd = TEMP_FAILURE_RETRY(open(commpath, O_RDONLY | O_CLOEXEC))) < 0) {
Colin Cross0c22e8b2012-11-02 15:46:56 -0700462 strcpy(comm, "N/A");
463 } else {
464 char *c;
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800465 TEMP_FAILURE_RETRY(read(fd, comm, sizeof(comm) - 2));
Colin Cross0c22e8b2012-11-02 15:46:56 -0700466 close(fd);
467
468 c = strrchr(comm, '\n');
469 if (c) {
470 *c = '\0';
471 }
472 }
473 func(pid, tid, comm);
474 }
475
476 closedir(d);
477}
478
479void for_each_tid(for_each_tid_func func, const char *header) {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700480 if (IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700481
Felipe Leme8620bb42015-11-10 11:04:45 -0800482 __for_each_pid(for_each_tid_helper, header, (void *) func);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700483}
484
485void show_wchan(int pid, int tid, const char *name) {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700486 if (IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700487
Colin Crossf45fa6b2012-03-26 12:38:26 -0700488 char path[255];
489 char buffer[255];
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800490 int fd, ret, save_errno;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700491 char name_buffer[255];
Colin Crossf45fa6b2012-03-26 12:38:26 -0700492
493 memset(buffer, 0, sizeof(buffer));
494
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700495 snprintf(path, sizeof(path), "/proc/%d/wchan", tid);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700496 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700497 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
498 return;
499 }
500
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800501 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
502 save_errno = errno;
503 close(fd);
504
505 if (ret < 0) {
506 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
507 return;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700508 }
509
Colin Cross0c22e8b2012-11-02 15:46:56 -0700510 snprintf(name_buffer, sizeof(name_buffer), "%*s%s",
511 pid == tid ? 0 : 3, "", name);
512
513 printf("%-7d %-32s %s\n", tid, name_buffer, buffer);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700514
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800515 return;
516}
517
518// print time in centiseconds
519static void snprcent(char *buffer, size_t len, size_t spc,
520 unsigned long long time) {
521 static long hz; // cache discovered hz
522
523 if (hz <= 0) {
524 hz = sysconf(_SC_CLK_TCK);
525 if (hz <= 0) {
526 hz = 1000;
527 }
528 }
529
530 // convert to centiseconds
531 time = (time * 100 + (hz / 2)) / hz;
532
533 char str[16];
534
535 snprintf(str, sizeof(str), " %llu.%02u",
536 time / 100, (unsigned)(time % 100));
537 size_t offset = strlen(buffer);
538 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
539 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
540}
541
542// print permille as a percent
543static void snprdec(char *buffer, size_t len, size_t spc, unsigned permille) {
544 char str[16];
545
546 snprintf(str, sizeof(str), " %u.%u%%", permille / 10, permille % 10);
547 size_t offset = strlen(buffer);
548 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
549 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
550}
551
552void show_showtime(int pid, const char *name) {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700553 if (IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700554
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800555 char path[255];
556 char buffer[1023];
557 int fd, ret, save_errno;
558
559 memset(buffer, 0, sizeof(buffer));
560
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700561 snprintf(path, sizeof(path), "/proc/%d/stat", pid);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800562 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
563 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
564 return;
565 }
566
567 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
568 save_errno = errno;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700569 close(fd);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800570
571 if (ret < 0) {
572 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
573 return;
574 }
575
576 // field 14 is utime
577 // field 15 is stime
578 // field 42 is iotime
579 unsigned long long utime = 0, stime = 0, iotime = 0;
580 if (sscanf(buffer,
Mark Salyzyn791ddd32016-02-10 07:41:12 -0800581 "%*u %*s %*s %*d %*d %*d %*d %*d %*d %*d %*d "
582 "%*d %*d %llu %llu %*d %*d %*d %*d %*d %*d "
583 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %*d "
584 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %llu ",
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800585 &utime, &stime, &iotime) != 3) {
586 return;
587 }
588
589 unsigned long long total = utime + stime;
590 if (!total) {
591 return;
592 }
593
594 unsigned permille = (iotime * 1000 + (total / 2)) / total;
595 if (permille > 1000) {
596 permille = 1000;
597 }
598
599 // try to beautify and stabilize columns at <80 characters
600 snprintf(buffer, sizeof(buffer), "%-6d%s", pid, name);
601 if ((name[0] != '[') || utime) {
602 snprcent(buffer, sizeof(buffer), 57, utime);
603 }
604 snprcent(buffer, sizeof(buffer), 65, stime);
605 if ((name[0] != '[') || iotime) {
606 snprcent(buffer, sizeof(buffer), 73, iotime);
607 }
608 if (iotime) {
609 snprdec(buffer, sizeof(buffer), 79, permille);
610 }
611 puts(buffer); // adds a trailing newline
612
Colin Crossf45fa6b2012-03-26 12:38:26 -0700613 return;
614}
615
616void do_dmesg() {
Felipe Leme78f2c862015-12-21 09:55:22 -0800617 const char *title = "KERNEL LOG (dmesg)";
618 DurationReporter duration_reporter(title);
619 printf("------ %s ------\n", title);
620
Felipe Leme4c2d6632016-09-28 14:32:00 -0700621 if (IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700622
Elliott Hughes5f87b312012-09-17 11:43:40 -0700623 /* Get size of kernel buffer */
624 int size = klogctl(KLOG_SIZE_BUFFER, NULL, 0);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700625 if (size <= 0) {
626 printf("Unexpected klogctl return value: %d\n\n", size);
627 return;
628 }
629 char *buf = (char *) malloc(size + 1);
630 if (buf == NULL) {
631 printf("memory allocation failed\n\n");
632 return;
633 }
634 int retval = klogctl(KLOG_READ_ALL, buf, size);
635 if (retval < 0) {
636 printf("klogctl failure\n\n");
637 free(buf);
638 return;
639 }
640 buf[retval] = '\0';
641 printf("%s\n\n", buf);
642 free(buf);
643 return;
644}
645
646void do_showmap(int pid, const char *name) {
647 char title[255];
648 char arg[255];
649
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700650 snprintf(title, sizeof(title), "SHOW MAP %d (%s)", pid, name);
651 snprintf(arg, sizeof(arg), "%d", pid);
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700652 RunCommand(title, {"showmap", "-q", arg}, CommandOptions::AS_ROOT_10);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700653}
654
Felipe Leme2b9b06c2016-10-14 09:13:06 -0700655// TODO: when converted to a Dumpstate function, it should be const
Felipe Leme46b85da2016-11-21 17:40:45 -0800656static int _dump_file_from_fd_to_fd(const std::string& title, const char* path, int fd, int out_fd,
657 int32_t* duration) {
Felipe Leme678727a2016-09-21 17:22:11 -0700658 if (!title.empty()) {
Felipe Lemebda15a02016-11-16 17:48:25 -0800659 dprintf(out_fd, "------ %s (%s", title.c_str(), path);
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800660
Colin Crossf45fa6b2012-03-26 12:38:26 -0700661 struct stat st;
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800662 // Only show the modification time of non-device files.
663 size_t path_len = strlen(path);
664 if ((path_len < 6 || memcmp(path, "/proc/", 6)) &&
665 (path_len < 5 || memcmp(path, "/sys/", 5)) &&
666 (path_len < 3 || memcmp(path, "/d/", 3)) &&
667 !fstat(fd, &st)) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700668 char stamp[80];
669 time_t mtime = st.st_mtime;
670 strftime(stamp, sizeof(stamp), "%Y-%m-%d %H:%M:%S", localtime(&mtime));
Felipe Lemebda15a02016-11-16 17:48:25 -0800671 dprintf(out_fd, ": %s", stamp);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700672 }
Felipe Lemebda15a02016-11-16 17:48:25 -0800673 dprintf(out_fd, ") ------\n");
Felipe Leme46b85da2016-11-21 17:40:45 -0800674 fsync(out_fd);
675 }
676
677 if (IsDryRun()) {
678 if (out_fd != STDOUT_FILENO) {
679 // There is no title, but we should still print a dry-run message
680 dprintf(out_fd, "%s: skipped on dry run\n", path);
681 } else if (!title.empty()) {
682 dprintf(out_fd, "\t(skipped on dry run)\n");
683 }
684 fsync(out_fd);
685 if (duration != nullptr) {
686 *duration = WEIGHT_FILE;
687 }
688 return 0;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700689 }
690
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800691 bool newline = false;
692 fd_set read_set;
693 struct timeval tm;
694 while (1) {
695 FD_ZERO(&read_set);
696 FD_SET(fd, &read_set);
697 /* Timeout if no data is read for 30 seconds. */
698 tm.tv_sec = 30;
699 tm.tv_usec = 0;
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700700 uint64_t elapsed = DurationReporter::Nanotime();
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800701 int ret = TEMP_FAILURE_RETRY(select(fd + 1, &read_set, NULL, NULL, &tm));
702 if (ret == -1) {
Felipe Lemebda15a02016-11-16 17:48:25 -0800703 dprintf(out_fd, "*** %s: select failed: %s\n", path, strerror(errno));
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800704 newline = true;
705 break;
706 } else if (ret == 0) {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700707 elapsed = DurationReporter::Nanotime() - elapsed;
Felipe Lemebda15a02016-11-16 17:48:25 -0800708 dprintf(out_fd, "*** %s: Timed out after %.3fs\n", path, (float)elapsed / NANOS_PER_SEC);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800709 newline = true;
710 break;
711 } else {
712 char buffer[65536];
713 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
714 if (bytes_read > 0) {
Felipe Lemebda15a02016-11-16 17:48:25 -0800715 android::base::WriteFully(out_fd, buffer, bytes_read);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800716 newline = (buffer[bytes_read-1] == '\n');
717 } else {
718 if (bytes_read == -1) {
Felipe Lemebda15a02016-11-16 17:48:25 -0800719 dprintf(out_fd, "*** %s: Failed to read from fd: %s", path, strerror(errno));
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800720 newline = true;
721 }
722 break;
723 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700724 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700725 }
Felipe Leme46b85da2016-11-21 17:40:45 -0800726 if (duration != nullptr) {
727 *duration = WEIGHT_FILE;
728 }
Elliott Hughes997abb62015-05-15 17:05:40 -0700729 close(fd);
Christopher Ferris7dc7f322014-07-22 16:08:19 -0700730
Felipe Lemebda15a02016-11-16 17:48:25 -0800731 if (!newline) dprintf(out_fd, "\n");
732 if (!title.empty()) dprintf(out_fd, "\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700733 return 0;
734}
735
Felipe Leme46b85da2016-11-21 17:40:45 -0800736// Internal function used by both Dumpstate::DumpFile and DumpFileToFd - the former prints title
737// information, while the latter doesn't.
738static int InternalDumpFileToFd(const std::string& title, int out_fd, const std::string& path,
739 int32_t* duration) {
740 if (duration) {
741 *duration = 0;
742 }
Felipe Lemebda15a02016-11-16 17:48:25 -0800743 int fd = TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_NONBLOCK | O_CLOEXEC));
744 if (fd < 0) {
745 int err = errno;
746 if (title.empty()) {
Felipe Leme46b85da2016-11-21 17:40:45 -0800747 dprintf(out_fd, "*** Error dumping %s: %s\n", path.c_str(), strerror(err));
Felipe Lemebda15a02016-11-16 17:48:25 -0800748 } else {
Felipe Leme46b85da2016-11-21 17:40:45 -0800749 dprintf(out_fd, "*** Error dumping %s (%s): %s\n", path.c_str(), title.c_str(),
750 strerror(err));
Felipe Lemebda15a02016-11-16 17:48:25 -0800751 }
Felipe Leme46b85da2016-11-21 17:40:45 -0800752 fsync(out_fd);
Felipe Lemebda15a02016-11-16 17:48:25 -0800753 return -1;
754 }
Felipe Leme46b85da2016-11-21 17:40:45 -0800755 return _dump_file_from_fd_to_fd(title, path.c_str(), fd, out_fd, duration);
Felipe Lemebda15a02016-11-16 17:48:25 -0800756}
757
758int DumpFileToFd(int out_fd, const std::string& path) {
Felipe Leme46b85da2016-11-21 17:40:45 -0800759 return InternalDumpFileToFd("", out_fd, path, nullptr);
Felipe Lemebda15a02016-11-16 17:48:25 -0800760}
761
Felipe Leme678727a2016-09-21 17:22:11 -0700762int Dumpstate::DumpFile(const std::string& title, const std::string& path) {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700763 DurationReporter duration_reporter(title);
Felipe Leme46b85da2016-11-21 17:40:45 -0800764 int32_t duration;
765
766 int status = InternalDumpFileToFd(title, STDOUT_FILENO, path, &duration);
767
768 if (duration > 0) {
769 UpdateProgress(duration);
Felipe Lemecef02982016-10-03 17:22:22 -0700770 }
Felipe Leme46b85da2016-11-21 17:40:45 -0800771
772 fflush(stdout);
773
774 return status;
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800775}
776
Felipe Leme71a74ac2016-03-17 15:43:25 -0700777int read_file_as_long(const char *path, long int *output) {
778 int fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
779 if (fd < 0) {
780 int err = errno;
781 MYLOGE("Error opening file descriptor for %s: %s\n", path, strerror(err));
782 return -1;
783 }
784 char buffer[50];
785 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
786 if (bytes_read == -1) {
787 MYLOGE("Error reading file %s: %s\n", path, strerror(errno));
788 return -2;
789 }
790 if (bytes_read == 0) {
791 MYLOGE("File %s is empty\n", path);
792 return -3;
793 }
794 *output = atoi(buffer);
795 return 0;
796}
797
Mark Salyzyn326842f2015-04-30 09:49:41 -0700798/* calls skip to gate calling dump_from_fd recursively
799 * in the specified directory. dump_from_fd defaults to
800 * dump_file_from_fd above when set to NULL. skip defaults
801 * to false when set to NULL. dump_from_fd will always be
802 * called with title NULL.
803 */
Felipe Leme678727a2016-09-21 17:22:11 -0700804int dump_files(const std::string& title, const char* dir, bool (*skip)(const char* path),
805 int (*dump_from_fd)(const char* title, const char* path, int fd)) {
Felipe Leme78f2c862015-12-21 09:55:22 -0800806 DurationReporter duration_reporter(title);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700807 DIR *dirp;
808 struct dirent *d;
809 char *newpath = NULL;
Felipe Leme8620bb42015-11-10 11:04:45 -0800810 const char *slash = "/";
Mark Salyzyn326842f2015-04-30 09:49:41 -0700811 int fd, retval = 0;
812
Felipe Leme678727a2016-09-21 17:22:11 -0700813 if (!title.empty()) {
814 printf("------ %s (%s) ------\n", title.c_str(), dir);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700815 }
Felipe Leme4c2d6632016-09-28 14:32:00 -0700816 if (IsDryRun()) return 0;
Mark Salyzyn326842f2015-04-30 09:49:41 -0700817
818 if (dir[strlen(dir) - 1] == '/') {
819 ++slash;
820 }
821 dirp = opendir(dir);
822 if (dirp == NULL) {
823 retval = -errno;
Felipe Leme107a05f2016-03-08 15:11:15 -0800824 MYLOGE("%s: %s\n", dir, strerror(errno));
Mark Salyzyn326842f2015-04-30 09:49:41 -0700825 return retval;
826 }
827
828 if (!dump_from_fd) {
829 dump_from_fd = dump_file_from_fd;
830 }
831 for (; ((d = readdir(dirp))); free(newpath), newpath = NULL) {
832 if ((d->d_name[0] == '.')
833 && (((d->d_name[1] == '.') && (d->d_name[2] == '\0'))
834 || (d->d_name[1] == '\0'))) {
835 continue;
836 }
837 asprintf(&newpath, "%s%s%s%s", dir, slash, d->d_name,
838 (d->d_type == DT_DIR) ? "/" : "");
839 if (!newpath) {
840 retval = -errno;
841 continue;
842 }
843 if (skip && (*skip)(newpath)) {
844 continue;
845 }
846 if (d->d_type == DT_DIR) {
Felipe Leme678727a2016-09-21 17:22:11 -0700847 int ret = dump_files("", newpath, skip, dump_from_fd);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700848 if (ret < 0) {
849 retval = ret;
850 }
851 continue;
852 }
853 fd = TEMP_FAILURE_RETRY(open(newpath, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
854 if (fd < 0) {
855 retval = fd;
856 printf("*** %s: %s\n", newpath, strerror(errno));
857 continue;
858 }
859 (*dump_from_fd)(NULL, newpath, fd);
860 }
861 closedir(dirp);
Felipe Leme678727a2016-09-21 17:22:11 -0700862 if (!title.empty()) {
Mark Salyzyn326842f2015-04-30 09:49:41 -0700863 printf("\n");
864 }
865 return retval;
866}
867
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800868/* fd must have been opened with the flag O_NONBLOCK. With this flag set,
869 * it's possible to avoid issues where opening the file itself can get
870 * stuck.
871 */
872int dump_file_from_fd(const char *title, const char *path, int fd) {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700873 if (IsDryRun()) return 0;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700874
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800875 int flags = fcntl(fd, F_GETFL);
876 if (flags == -1) {
877 printf("*** %s: failed to get flags on fd %d: %s\n", path, fd, strerror(errno));
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800878 close(fd);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800879 return -1;
880 } else if (!(flags & O_NONBLOCK)) {
881 printf("*** %s: fd must have O_NONBLOCK set.\n", path);
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800882 close(fd);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800883 return -1;
884 }
Felipe Leme46b85da2016-11-21 17:40:45 -0800885 return _dump_file_from_fd_to_fd(title, path, fd, STDOUT_FILENO, nullptr);
Jeff Brown1dc94e32014-09-11 14:15:27 -0700886}
887
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800888bool waitpid_with_timeout(pid_t pid, int timeout_seconds, int* status) {
889 sigset_t child_mask, old_mask;
890 sigemptyset(&child_mask);
891 sigaddset(&child_mask, SIGCHLD);
892
893 if (sigprocmask(SIG_BLOCK, &child_mask, &old_mask) == -1) {
894 printf("*** sigprocmask failed: %s\n", strerror(errno));
895 return false;
896 }
897
898 struct timespec ts;
899 ts.tv_sec = timeout_seconds;
900 ts.tv_nsec = 0;
901 int ret = TEMP_FAILURE_RETRY(sigtimedwait(&child_mask, NULL, &ts));
902 int saved_errno = errno;
903 // Set the signals back the way they were.
904 if (sigprocmask(SIG_SETMASK, &old_mask, NULL) == -1) {
905 printf("*** sigprocmask failed: %s\n", strerror(errno));
906 if (ret == 0) {
907 return false;
908 }
909 }
910 if (ret == -1) {
911 errno = saved_errno;
912 if (errno == EAGAIN) {
913 errno = ETIMEDOUT;
914 } else {
915 printf("*** sigtimedwait failed: %s\n", strerror(errno));
916 }
917 return false;
918 }
919
920 pid_t child_pid = waitpid(pid, status, WNOHANG);
921 if (child_pid != pid) {
922 if (child_pid != -1) {
923 printf("*** Waiting for pid %d, got pid %d instead\n", pid, child_pid);
924 } else {
925 printf("*** waitpid failed: %s\n", strerror(errno));
926 }
927 return false;
928 }
929 return true;
930}
931
Felipe Leme46b85da2016-11-21 17:40:45 -0800932// Internal function used by both Dumpstate::DumpFile and DumpFileToFd - the former prints title
933// information, while the latter doesn't.
934static int InternalRunCommandToFd(const std::string& title, int fd,
935 const std::vector<std::string>& full_command,
936 const CommandOptions& options, int32_t* duration) {
937 if (duration) {
938 *duration = 0;
939 }
Felipe Leme9a523ae2016-10-20 15:10:33 -0700940 if (full_command.empty()) {
Felipe Leme46b85da2016-11-21 17:40:45 -0800941 MYLOGE("No arguments on RunCommandToFd(%s)\n", title.c_str());
Felipe Leme30dbfa12016-09-02 12:43:26 -0700942 return -1;
943 }
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800944
Felipe Leme9a523ae2016-10-20 15:10:33 -0700945 int size = full_command.size() + 1; // null terminated
946 int starting_index = 0;
Felipe Leme46b85da2016-11-21 17:40:45 -0800947 if (options.PrivilegeMode() == SU_ROOT) {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700948 starting_index = 2; // "su" "root"
949 size += starting_index;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700950 }
951
Felipe Leme6ad9c062016-09-28 11:58:36 -0700952 std::vector<const char*> args;
953 args.resize(size);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700954
Felipe Leme9a523ae2016-10-20 15:10:33 -0700955 std::string command_string;
Felipe Leme46b85da2016-11-21 17:40:45 -0800956 if (options.PrivilegeMode() == SU_ROOT) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700957 args[0] = SU_PATH;
Felipe Leme9a523ae2016-10-20 15:10:33 -0700958 command_string += SU_PATH;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700959 args[1] = "root";
Felipe Leme9a523ae2016-10-20 15:10:33 -0700960 command_string += " root ";
Felipe Leme30dbfa12016-09-02 12:43:26 -0700961 }
Felipe Leme46b85da2016-11-21 17:40:45 -0800962 for (size_t i = 0; i < full_command.size(); i++) {
963 args[i + starting_index] = full_command[i].data();
964 command_string += args[i + starting_index];
965 if (i != full_command.size() - 1) {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700966 command_string += " ";
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800967 }
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800968 }
Felipe Leme46b85da2016-11-21 17:40:45 -0800969 args[size - 1] = nullptr;
970
Felipe Leme9a523ae2016-10-20 15:10:33 -0700971 const char* command = command_string.c_str();
Felipe Lemec5d6cfc2016-09-26 15:57:04 -0700972
Felipe Leme46b85da2016-11-21 17:40:45 -0800973 if (options.PrivilegeMode() == SU_ROOT && ds.IsUserBuild()) {
974 dprintf(fd, "Skipping '%s' on user build.\n", command);
Felipe Leme6ad9c062016-09-28 11:58:36 -0700975 return 0;
976 }
977
Felipe Leme678727a2016-09-21 17:22:11 -0700978 if (!title.empty()) {
Felipe Leme46b85da2016-11-21 17:40:45 -0800979 dprintf(fd, "------ %s (%s) ------\n", title.c_str(), command);
980 fsync(fd);
Felipe Lemec5d6cfc2016-09-26 15:57:04 -0700981 }
Felipe Leme30dbfa12016-09-02 12:43:26 -0700982
Felipe Leme9a523ae2016-10-20 15:10:33 -0700983 const std::string& logging_message = options.LoggingMessage();
984 if (!logging_message.empty()) {
985 MYLOGI(logging_message.c_str(), command_string.c_str());
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800986 }
987
Felipe Leme30dbfa12016-09-02 12:43:26 -0700988 /* TODO: for now we're simplifying the progress calculation by using the
989 * timeout as the weight. It's a good approximation for most cases, except when calling dumpsys,
990 * where its weight should be much higher proportionally to its timeout.
991 * Ideally, it should use a options.EstimatedDuration() instead...*/
Felipe Leme46b85da2016-11-21 17:40:45 -0800992 if (duration != nullptr) {
993 *duration = options.Timeout();
Felipe Leme2b9b06c2016-10-14 09:13:06 -0700994 }
995
Felipe Leme46b85da2016-11-21 17:40:45 -0800996 bool silent = (options.OutputMode() == REDIRECT_TO_STDERR);
997 bool redirecting_to_fd = STDOUT_FILENO != fd;
Felipe Leme2b9b06c2016-10-14 09:13:06 -0700998
Felipe Leme46b85da2016-11-21 17:40:45 -0800999 if (IsDryRun() && !options.Always()) {
1000 if (redirecting_to_fd) {
1001 // There is no title, but we should still print a dry-run message
1002 dprintf(fd, "%s: skipped on dry run\n", command_string.c_str());
1003 } else if (!title.empty()) {
1004 dprintf(fd, "\t(skipped on dry run)\n");
1005 }
1006 fsync(fd);
1007 return 0;
Felipe Lemebda15a02016-11-16 17:48:25 -08001008 }
Felipe Lemebda15a02016-11-16 17:48:25 -08001009
Felipe Leme46b85da2016-11-21 17:40:45 -08001010 const char* path = args[0];
Felipe Leme2b9b06c2016-10-14 09:13:06 -07001011
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001012 uint64_t start = DurationReporter::Nanotime();
Colin Crossf45fa6b2012-03-26 12:38:26 -07001013 pid_t pid = fork();
1014
1015 /* handle error case */
1016 if (pid < 0) {
Felipe Leme46b85da2016-11-21 17:40:45 -08001017 if (!silent) dprintf(fd, "*** fork: %s\n", strerror(errno));
Felipe Leme29c39712016-04-01 10:02:00 -07001018 MYLOGE("*** fork: %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001019 return pid;
1020 }
1021
1022 /* handle child case */
1023 if (pid == 0) {
Felipe Leme46b85da2016-11-21 17:40:45 -08001024 if (options.PrivilegeMode() == DROP_ROOT && !drop_root_user()) {
1025 if (!silent) {
1026 dprintf(fd, "*** failed to drop root before running %s: %s\n", command,
1027 strerror(errno));
1028 }
Felipe Leme29c39712016-04-01 10:02:00 -07001029 MYLOGE("*** could not drop root before running %s: %s\n", command, strerror(errno));
Felipe Leme73f731c2016-03-23 16:47:00 -07001030 return -1;
Felipe Lemecf6a8b42016-03-11 10:38:19 -08001031 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001032
Felipe Leme46b85da2016-11-21 17:40:45 -08001033 if (silent) {
1034 // Redirects stdout to stderr
1035 TEMP_FAILURE_RETRY(dup2(STDERR_FILENO, STDOUT_FILENO));
1036 } else if (redirecting_to_fd) {
1037 // Redirect stdout to fd
Felipe Lemebda15a02016-11-16 17:48:25 -08001038 TEMP_FAILURE_RETRY(dup2(fd, STDOUT_FILENO));
1039 close(fd);
1040 }
Felipe Leme29c39712016-04-01 10:02:00 -07001041
John Michelaue7b6cf12013-03-07 15:35:35 -06001042 /* make sure the child dies when dumpstate dies */
1043 prctl(PR_SET_PDEATHSIG, SIGKILL);
1044
Andres Morales2e671bb2014-08-21 12:38:22 -07001045 /* just ignore SIGPIPE, will go down with parent's */
1046 struct sigaction sigact;
1047 memset(&sigact, 0, sizeof(sigact));
1048 sigact.sa_handler = SIG_IGN;
1049 sigaction(SIGPIPE, &sigact, NULL);
1050
Felipe Leme46b85da2016-11-21 17:40:45 -08001051 execvp(path, (char**)args.data());
Felipe Leme30dbfa12016-09-02 12:43:26 -07001052 // execvp's result will be handled after waitpid_with_timeout() below, but
1053 // if it failed, it's safer to exit dumpstate.
1054 MYLOGD("execvp on command '%s' failed (error: %s)\n", command, strerror(errno));
Felipe Leme30dbfa12016-09-02 12:43:26 -07001055 // Must call _exit (instead of exit), otherwise it will corrupt the zip
1056 // file.
Felipe Lemebaa85bd2016-03-29 13:29:11 -07001057 _exit(EXIT_FAILURE);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001058 }
1059
1060 /* handle parent case */
Christopher Ferris1a9a3382015-01-30 11:00:52 -08001061 int status;
Felipe Leme30dbfa12016-09-02 12:43:26 -07001062 bool ret = waitpid_with_timeout(pid, options.Timeout(), &status);
Felipe Lemebda15a02016-11-16 17:48:25 -08001063 fsync(fd);
1064
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001065 uint64_t elapsed = DurationReporter::Nanotime() - start;
Christopher Ferris1a9a3382015-01-30 11:00:52 -08001066 if (!ret) {
1067 if (errno == ETIMEDOUT) {
Felipe Leme30dbfa12016-09-02 12:43:26 -07001068 if (!silent)
Felipe Leme46b85da2016-11-21 17:40:45 -08001069 dprintf(fd, "*** command '%s' timed out after %.3fs (killing pid %d)\n", command,
1070 (float)elapsed / NANOS_PER_SEC, pid);
Felipe Lemefd8affa2016-09-30 17:38:57 -07001071 MYLOGE("*** command '%s' timed out after %.3fs (killing pid %d)\n", command,
Felipe Leme30dbfa12016-09-02 12:43:26 -07001072 (float)elapsed / NANOS_PER_SEC, pid);
Christopher Ferris1a9a3382015-01-30 11:00:52 -08001073 } else {
Felipe Leme30dbfa12016-09-02 12:43:26 -07001074 if (!silent)
Felipe Leme46b85da2016-11-21 17:40:45 -08001075 dprintf(fd, "*** command '%s': Error after %.4fs (killing pid %d)\n", command,
1076 (float)elapsed / NANOS_PER_SEC, pid);
Felipe Leme30dbfa12016-09-02 12:43:26 -07001077 MYLOGE("command '%s': Error after %.4fs (killing pid %d)\n", command,
1078 (float)elapsed / NANOS_PER_SEC, pid);
Christopher Ferris1a9a3382015-01-30 11:00:52 -08001079 }
1080 kill(pid, SIGTERM);
Felipe Lemefd8affa2016-09-30 17:38:57 -07001081 if (!waitpid_with_timeout(pid, 5, nullptr)) {
Christopher Ferris1a9a3382015-01-30 11:00:52 -08001082 kill(pid, SIGKILL);
Felipe Lemefd8affa2016-09-30 17:38:57 -07001083 if (!waitpid_with_timeout(pid, 5, nullptr)) {
Felipe Leme30dbfa12016-09-02 12:43:26 -07001084 if (!silent)
Felipe Leme46b85da2016-11-21 17:40:45 -08001085 dprintf(fd, "could not kill command '%s' (pid %d) even with SIGKILL.\n",
1086 command, pid);
Felipe Leme14e034a2016-03-30 18:51:03 -07001087 MYLOGE("could not kill command '%s' (pid %d) even with SIGKILL.\n", command, pid);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001088 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001089 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -08001090 return -1;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001091 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -08001092
1093 if (WIFSIGNALED(status)) {
Felipe Lemefd8affa2016-09-30 17:38:57 -07001094 if (!silent)
Felipe Leme46b85da2016-11-21 17:40:45 -08001095 dprintf(fd, "*** command '%s' failed: killed by signal %d\n", command, WTERMSIG(status));
Felipe Lemefd8affa2016-09-30 17:38:57 -07001096 MYLOGE("*** command '%s' failed: killed by signal %d\n", command, WTERMSIG(status));
Christopher Ferris1a9a3382015-01-30 11:00:52 -08001097 } else if (WIFEXITED(status) && WEXITSTATUS(status) > 0) {
Felipe Lemefd8affa2016-09-30 17:38:57 -07001098 status = WEXITSTATUS(status);
Felipe Leme46b85da2016-11-21 17:40:45 -08001099 if (!silent) dprintf(fd, "*** command '%s' failed: exit code %d\n", command, status);
Felipe Lemefd8affa2016-09-30 17:38:57 -07001100 MYLOGE("*** command '%s' failed: exit code %d\n", command, status);
Christopher Ferris1a9a3382015-01-30 11:00:52 -08001101 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -08001102
1103 return status;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001104}
1105
Felipe Leme46b85da2016-11-21 17:40:45 -08001106int Dumpstate::RunCommand(const std::string& title, const std::vector<std::string>& full_command,
1107 const CommandOptions& options) {
1108 DurationReporter duration_reporter(title);
1109
1110 int32_t duration;
1111 int status = InternalRunCommandToFd(title, STDOUT_FILENO, full_command, options, &duration);
1112
1113 if (duration > 0) {
1114 UpdateProgress(duration);
1115 }
1116
1117 fflush(stdout);
1118
1119 return status;
1120}
1121
1122int RunCommandToFd(int fd, const std::vector<std::string>& full_command,
1123 const CommandOptions& options) {
1124 return InternalRunCommandToFd("", fd, full_command, options, nullptr);
1125}
1126
Felipe Leme9a523ae2016-10-20 15:10:33 -07001127void Dumpstate::RunDumpsys(const std::string& title, const std::vector<std::string>& dumpsys_args,
Felipe Leme678727a2016-09-21 17:22:11 -07001128 const CommandOptions& options, long dumpsysTimeout) {
Felipe Leme5bcce572016-09-27 09:21:08 -07001129 long timeout = dumpsysTimeout > 0 ? dumpsysTimeout : options.Timeout();
1130 std::vector<std::string> dumpsys = {"/system/bin/dumpsys", "-t", std::to_string(timeout)};
Felipe Leme9a523ae2016-10-20 15:10:33 -07001131 dumpsys.insert(dumpsys.end(), dumpsys_args.begin(), dumpsys_args.end());
Felipe Leme678727a2016-09-21 17:22:11 -07001132 RunCommand(title, dumpsys, options);
Felipe Leme30dbfa12016-09-02 12:43:26 -07001133}
1134
Felipe Lemecf6a8b42016-03-11 10:38:19 -08001135bool drop_root_user() {
1136 if (getgid() == AID_SHELL && getuid() == AID_SHELL) {
Felipe Leme26c41572016-10-06 14:34:43 -07001137 MYLOGD("drop_root_user(): already running as Shell\n");
Felipe Lemecf6a8b42016-03-11 10:38:19 -08001138 return true;
1139 }
1140 /* ensure we will keep capabilities when we drop root */
1141 if (prctl(PR_SET_KEEPCAPS, 1) < 0) {
1142 MYLOGE("prctl(PR_SET_KEEPCAPS) failed: %s\n", strerror(errno));
1143 return false;
1144 }
1145
1146 gid_t groups[] = { AID_LOG, AID_SDCARD_R, AID_SDCARD_RW,
Ajay Panickerd886ec42016-09-14 12:26:46 -07001147 AID_MOUNT, AID_INET, AID_NET_BW_STATS, AID_READPROC, AID_WAKELOCK,
1148 AID_BLUETOOTH };
Felipe Lemecf6a8b42016-03-11 10:38:19 -08001149 if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) {
1150 MYLOGE("Unable to setgroups, aborting: %s\n", strerror(errno));
1151 return false;
1152 }
1153 if (setgid(AID_SHELL) != 0) {
1154 MYLOGE("Unable to setgid, aborting: %s\n", strerror(errno));
1155 return false;
1156 }
1157 if (setuid(AID_SHELL) != 0) {
1158 MYLOGE("Unable to setuid, aborting: %s\n", strerror(errno));
1159 return false;
1160 }
1161
1162 struct __user_cap_header_struct capheader;
1163 struct __user_cap_data_struct capdata[2];
1164 memset(&capheader, 0, sizeof(capheader));
1165 memset(&capdata, 0, sizeof(capdata));
1166 capheader.version = _LINUX_CAPABILITY_VERSION_3;
1167 capheader.pid = 0;
1168
Wei Liuf87959e2016-08-26 14:51:42 -07001169 capdata[CAP_TO_INDEX(CAP_SYSLOG)].permitted =
1170 (CAP_TO_MASK(CAP_SYSLOG) | CAP_TO_MASK(CAP_BLOCK_SUSPEND));
1171 capdata[CAP_TO_INDEX(CAP_SYSLOG)].effective =
1172 (CAP_TO_MASK(CAP_SYSLOG) | CAP_TO_MASK(CAP_BLOCK_SUSPEND));
Felipe Lemecf6a8b42016-03-11 10:38:19 -08001173 capdata[0].inheritable = 0;
1174 capdata[1].inheritable = 0;
1175
1176 if (capset(&capheader, &capdata[0]) < 0) {
1177 MYLOGE("capset failed: %s\n", strerror(errno));
1178 return false;
1179 }
1180
1181 return true;
1182}
1183
Felipe Leme36b3f6f2015-11-19 15:41:04 -08001184void send_broadcast(const std::string& action, const std::vector<std::string>& args) {
Felipe Leme30dbfa12016-09-02 12:43:26 -07001185 std::vector<std::string> am = {"/system/bin/am", "broadcast", "--user", "0", "-a", action};
1186
1187 am.insert(am.end(), args.begin(), args.end());
1188
Felipe Leme678727a2016-09-21 17:22:11 -07001189 RunCommand("", am, CommandOptions::WithTimeout(20)
1190 .Log("Sending broadcast: '%s'\n")
1191 .Always()
1192 .DropRoot()
1193 .RedirectStderr()
1194 .Build());
Felipe Leme36b3f6f2015-11-19 15:41:04 -08001195}
1196
Colin Crossf45fa6b2012-03-26 12:38:26 -07001197size_t num_props = 0;
1198static char* props[2000];
1199
1200static void print_prop(const char *key, const char *name, void *user) {
1201 (void) user;
1202 if (num_props < sizeof(props) / sizeof(props[0])) {
1203 char buf[PROPERTY_KEY_MAX + PROPERTY_VALUE_MAX + 10];
1204 snprintf(buf, sizeof(buf), "[%s]: [%s]\n", key, name);
1205 props[num_props++] = strdup(buf);
1206 }
1207}
1208
1209static int compare_prop(const void *a, const void *b) {
1210 return strcmp(*(char * const *) a, *(char * const *) b);
1211}
1212
1213/* prints all the system properties */
1214void print_properties() {
Felipe Leme78f2c862015-12-21 09:55:22 -08001215 const char* title = "SYSTEM PROPERTIES";
1216 DurationReporter duration_reporter(title);
1217 printf("------ %s ------\n", title);
Felipe Leme4c2d6632016-09-28 14:32:00 -07001218 if (IsDryRun()) return;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001219 size_t i;
1220 num_props = 0;
1221 property_list(print_prop, NULL);
1222 qsort(&props, num_props, sizeof(props[0]), compare_prop);
1223
Colin Crossf45fa6b2012-03-26 12:38:26 -07001224 for (i = 0; i < num_props; ++i) {
1225 fputs(props[i], stdout);
1226 free(props[i]);
1227 }
1228 printf("\n");
1229}
1230
Felipe Leme2628e9e2016-04-12 16:36:51 -07001231int open_socket(const char *service) {
Colin Crossf45fa6b2012-03-26 12:38:26 -07001232 int s = android_get_control_socket(service);
1233 if (s < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001234 MYLOGE("android_get_control_socket(%s): %s\n", service, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001235 exit(1);
1236 }
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001237 fcntl(s, F_SETFD, FD_CLOEXEC);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001238 if (listen(s, 4) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001239 MYLOGE("listen(control socket): %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001240 exit(1);
1241 }
1242
1243 struct sockaddr addr;
1244 socklen_t alen = sizeof(addr);
1245 int fd = accept(s, &addr, &alen);
1246 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001247 MYLOGE("accept(control socket): %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001248 exit(1);
1249 }
1250
Felipe Leme2628e9e2016-04-12 16:36:51 -07001251 return fd;
1252}
1253
1254/* redirect output to a service control socket */
1255void redirect_to_socket(FILE *redirect, const char *service) {
1256 int fd = open_socket(service);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001257 fflush(redirect);
1258 dup2(fd, fileno(redirect));
1259 close(fd);
1260}
1261
Felipe Leme2628e9e2016-04-12 16:36:51 -07001262// TODO: should call is_valid_output_file and/or be merged into it.
Felipe Leme111b9d02016-02-03 09:28:24 -08001263void create_parent_dirs(const char *path) {
Srinath Sridharanfdf52d32016-02-01 15:50:22 -08001264 char *chp = const_cast<char *> (path);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001265
1266 /* skip initial slash */
1267 if (chp[0] == '/')
1268 chp++;
1269
1270 /* create leading directories, if necessary */
Felipe Leme111b9d02016-02-03 09:28:24 -08001271 struct stat dir_stat;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001272 while (chp && chp[0]) {
1273 chp = strchr(chp, '/');
1274 if (chp) {
1275 *chp = 0;
Felipe Leme111b9d02016-02-03 09:28:24 -08001276 if (stat(path, &dir_stat) == -1 || !S_ISDIR(dir_stat.st_mode)) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001277 MYLOGI("Creating directory %s\n", path);
Felipe Leme111b9d02016-02-03 09:28:24 -08001278 if (mkdir(path, 0770)) { /* drwxrwx--- */
Felipe Lemecbce55d2016-02-08 09:53:18 -08001279 MYLOGE("Unable to create directory %s: %s\n", path, strerror(errno));
Felipe Leme111b9d02016-02-03 09:28:24 -08001280 } else if (chown(path, AID_SHELL, AID_SHELL)) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001281 MYLOGE("Unable to change ownership of dir %s: %s\n", path, strerror(errno));
Felipe Leme111b9d02016-02-03 09:28:24 -08001282 }
1283 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001284 *chp++ = '/';
1285 }
1286 }
Felipe Leme111b9d02016-02-03 09:28:24 -08001287}
1288
Felipe Leme0f3fb202016-06-10 17:10:53 -07001289void _redirect_to_file(FILE *redirect, char *path, int truncate_flag) {
Felipe Leme111b9d02016-02-03 09:28:24 -08001290 create_parent_dirs(path);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001291
Felipe Leme0f3fb202016-06-10 17:10:53 -07001292 int fd = TEMP_FAILURE_RETRY(open(path,
1293 O_WRONLY | O_CREAT | truncate_flag | O_CLOEXEC | O_NOFOLLOW,
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -08001294 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001295 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001296 MYLOGE("%s: %s\n", path, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001297 exit(1);
1298 }
1299
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -08001300 TEMP_FAILURE_RETRY(dup2(fd, fileno(redirect)));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001301 close(fd);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001302}
1303
Felipe Leme0f3fb202016-06-10 17:10:53 -07001304void redirect_to_file(FILE *redirect, char *path) {
1305 _redirect_to_file(redirect, path, O_TRUNC);
1306}
1307
1308void redirect_to_existing_file(FILE *redirect, char *path) {
1309 _redirect_to_file(redirect, path, O_APPEND);
1310}
1311
Jeff Brownbf7f4922012-06-07 16:40:01 -07001312static bool should_dump_native_traces(const char* path) {
1313 for (const char** p = native_processes_to_dump; *p; p++) {
1314 if (!strcmp(*p, path)) {
1315 return true;
1316 }
1317 }
1318 return false;
1319}
1320
1321/* dump Dalvik and native stack traces, return the trace file location (NULL if none) */
1322const char *dump_traces() {
Felipe Lemee184f662016-10-27 10:04:47 -07001323 DurationReporter duration_reporter("DUMP TRACES");
Felipe Lemed402e7d2016-08-03 09:22:27 -07001324
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001325 const char* result = nullptr;
Jeff Brownbf7f4922012-06-07 16:40:01 -07001326
Felipe Lemee184f662016-10-27 10:04:47 -07001327 std::string traces_path = android::base::GetProperty("dalvik.vm.stack-trace-file", "");
1328 if (traces_path.empty()) return nullptr;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001329
1330 /* move the old traces.txt (if any) out of the way temporarily */
Felipe Lemee184f662016-10-27 10:04:47 -07001331 std::string anrtraces_path = traces_path + ".anr";
1332 if (rename(traces_path.c_str(), anrtraces_path.c_str()) && errno != ENOENT) {
1333 MYLOGE("rename(%s, %s): %s\n", traces_path.c_str(), anrtraces_path.c_str(), strerror(errno));
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001334 return nullptr; // Can't rename old traces.txt -- no permission? -- leave it alone instead
Colin Crossf45fa6b2012-03-26 12:38:26 -07001335 }
1336
Colin Crossf45fa6b2012-03-26 12:38:26 -07001337 /* create a new, empty traces.txt file to receive stack dumps */
Felipe Lemee184f662016-10-27 10:04:47 -07001338 int fd = TEMP_FAILURE_RETRY(open(traces_path.c_str(),
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001339 O_CREAT | O_WRONLY | O_TRUNC | O_NOFOLLOW | O_CLOEXEC,
1340 0666)); /* -rw-rw-rw- */
Colin Crossf45fa6b2012-03-26 12:38:26 -07001341 if (fd < 0) {
Felipe Lemee184f662016-10-27 10:04:47 -07001342 MYLOGE("%s: %s\n", traces_path.c_str(), strerror(errno));
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001343 return nullptr;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001344 }
Nick Kralevichc7f1fe22012-04-06 09:31:28 -07001345 int chmod_ret = fchmod(fd, 0666);
1346 if (chmod_ret < 0) {
Felipe Lemee184f662016-10-27 10:04:47 -07001347 MYLOGE("fchmod on %s failed: %s\n", traces_path.c_str(), strerror(errno));
Nick Kralevichc7f1fe22012-04-06 09:31:28 -07001348 close(fd);
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001349 return nullptr;
Nick Kralevichc7f1fe22012-04-06 09:31:28 -07001350 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001351
Felipe Leme8620bb42015-11-10 11:04:45 -08001352 /* Variables below must be initialized before 'goto' statements */
1353 int dalvik_found = 0;
1354 int ifd, wfd = -1;
1355
Colin Crossf45fa6b2012-03-26 12:38:26 -07001356 /* walk /proc and kill -QUIT all Dalvik processes */
1357 DIR *proc = opendir("/proc");
1358 if (proc == NULL) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001359 MYLOGE("/proc: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001360 goto error_close_fd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001361 }
1362
1363 /* use inotify to find when processes are done dumping */
Felipe Leme8620bb42015-11-10 11:04:45 -08001364 ifd = inotify_init();
Colin Crossf45fa6b2012-03-26 12:38:26 -07001365 if (ifd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001366 MYLOGE("inotify_init: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001367 goto error_close_fd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001368 }
1369
Felipe Lemee184f662016-10-27 10:04:47 -07001370 wfd = inotify_add_watch(ifd, traces_path.c_str(), IN_CLOSE_WRITE);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001371 if (wfd < 0) {
Felipe Lemee184f662016-10-27 10:04:47 -07001372 MYLOGE("inotify_add_watch(%s): %s\n", traces_path.c_str(), strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001373 goto error_close_ifd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001374 }
1375
1376 struct dirent *d;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001377 while ((d = readdir(proc))) {
1378 int pid = atoi(d->d_name);
1379 if (pid <= 0) continue;
1380
Jeff Brownbf7f4922012-06-07 16:40:01 -07001381 char path[PATH_MAX];
1382 char data[PATH_MAX];
Colin Crossf45fa6b2012-03-26 12:38:26 -07001383 snprintf(path, sizeof(path), "/proc/%d/exe", pid);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001384 ssize_t len = readlink(path, data, sizeof(data) - 1);
1385 if (len <= 0) {
Colin Crossf45fa6b2012-03-26 12:38:26 -07001386 continue;
1387 }
Jeff Brownbf7f4922012-06-07 16:40:01 -07001388 data[len] = '\0';
Colin Crossf45fa6b2012-03-26 12:38:26 -07001389
Colin Cross0d6180f2014-07-16 19:00:46 -07001390 if (!strncmp(data, "/system/bin/app_process", strlen("/system/bin/app_process"))) {
Jeff Brownbf7f4922012-06-07 16:40:01 -07001391 /* skip zygote -- it won't dump its stack anyway */
1392 snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001393 int cfd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC));
Jeff Brown1dc94e32014-09-11 14:15:27 -07001394 len = read(cfd, data, sizeof(data) - 1);
1395 close(cfd);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001396 if (len <= 0) {
1397 continue;
1398 }
1399 data[len] = '\0';
Colin Cross0d6180f2014-07-16 19:00:46 -07001400 if (!strncmp(data, "zygote", strlen("zygote"))) {
Jeff Brownbf7f4922012-06-07 16:40:01 -07001401 continue;
1402 }
1403
1404 ++dalvik_found;
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001405 uint64_t start = DurationReporter::Nanotime();
Jeff Brownbf7f4922012-06-07 16:40:01 -07001406 if (kill(pid, SIGQUIT)) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001407 MYLOGE("kill(%d, SIGQUIT): %s\n", pid, strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001408 continue;
1409 }
1410
1411 /* wait for the writable-close notification from inotify */
1412 struct pollfd pfd = { ifd, POLLIN, 0 };
Felipe Leme61884122016-06-13 09:23:30 -07001413 int ret = poll(&pfd, 1, TRACE_DUMP_TIMEOUT_MS);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001414 if (ret < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001415 MYLOGE("poll: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001416 } else if (ret == 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001417 MYLOGE("warning: timed out dumping pid %d\n", pid);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001418 } else {
1419 struct inotify_event ie;
1420 read(ifd, &ie, sizeof(ie));
1421 }
Jeff Brown1dc94e32014-09-11 14:15:27 -07001422
1423 if (lseek(fd, 0, SEEK_END) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001424 MYLOGE("lseek: %s\n", strerror(errno));
Jeff Brown1dc94e32014-09-11 14:15:27 -07001425 } else {
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001426 dprintf(fd, "[dump dalvik stack %d: %.3fs elapsed]\n", pid,
1427 (float)(DurationReporter::Nanotime() - start) / NANOS_PER_SEC);
Jeff Brown1dc94e32014-09-11 14:15:27 -07001428 }
Jeff Brownbf7f4922012-06-07 16:40:01 -07001429 } else if (should_dump_native_traces(data)) {
1430 /* dump native process if appropriate */
1431 if (lseek(fd, 0, SEEK_END) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001432 MYLOGE("lseek: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001433 } else {
Christopher Ferris31ef8552015-01-14 13:23:30 -08001434 static uint16_t timeout_failures = 0;
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001435 uint64_t start = DurationReporter::Nanotime();
Christopher Ferris31ef8552015-01-14 13:23:30 -08001436
1437 /* If 3 backtrace dumps fail in a row, consider debuggerd dead. */
1438 if (timeout_failures == 3) {
1439 dprintf(fd, "too many stack dump failures, skipping...\n");
1440 } else if (dump_backtrace_to_file_timeout(pid, fd, 20) == -1) {
1441 dprintf(fd, "dumping failed, likely due to a timeout\n");
1442 timeout_failures++;
1443 } else {
1444 timeout_failures = 0;
1445 }
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001446 dprintf(fd, "[dump native stack %d: %.3fs elapsed]\n", pid,
1447 (float)(DurationReporter::Nanotime() - start) / NANOS_PER_SEC);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001448 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001449 }
1450 }
1451
Colin Crossf45fa6b2012-03-26 12:38:26 -07001452 if (dalvik_found == 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001453 MYLOGE("Warning: no Dalvik processes found to dump stacks\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -07001454 }
1455
Felipe Lemee184f662016-10-27 10:04:47 -07001456 static std::string dumptraces_path = android::base::StringPrintf(
1457 "%s/bugreport-%s", dirname(traces_path.c_str()), basename(traces_path.c_str()));
1458 if (rename(traces_path.c_str(), dumptraces_path.c_str())) {
1459 MYLOGE("rename(%s, %s): %s\n", traces_path.c_str(), dumptraces_path.c_str(),
1460 strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001461 goto error_close_ifd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001462 }
Felipe Lemee184f662016-10-27 10:04:47 -07001463 result = dumptraces_path.c_str();
Colin Crossf45fa6b2012-03-26 12:38:26 -07001464
1465 /* replace the saved [ANR] traces.txt file */
Felipe Lemee184f662016-10-27 10:04:47 -07001466 rename(anrtraces_path.c_str(), traces_path.c_str());
Jeff Brownbf7f4922012-06-07 16:40:01 -07001467
1468error_close_ifd:
1469 close(ifd);
1470error_close_fd:
1471 close(fd);
1472 return result;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001473}
1474
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001475void dump_route_tables() {
Felipe Leme78f2c862015-12-21 09:55:22 -08001476 DurationReporter duration_reporter("DUMP ROUTE TABLES");
Felipe Leme4c2d6632016-09-28 14:32:00 -07001477 if (IsDryRun()) return;
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001478 const char* const RT_TABLES_PATH = "/data/misc/net/rt_tables";
Felipe Lemec7fe8fe2016-09-21 18:13:20 -07001479 ds.DumpFile("RT_TABLES", RT_TABLES_PATH);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001480 FILE* fp = fopen(RT_TABLES_PATH, "re");
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001481 if (!fp) {
1482 printf("*** %s: %s\n", RT_TABLES_PATH, strerror(errno));
1483 return;
1484 }
1485 char table[16];
1486 // Each line has an integer (the table number), a space, and a string (the table name). We only
1487 // need the table number. It's a 32-bit unsigned number, so max 10 chars. Skip the table name.
1488 // Add a fixed max limit so this doesn't go awry.
1489 for (int i = 0; i < 64 && fscanf(fp, " %10s %*s", table) == 1; ++i) {
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001490 RunCommand("ROUTE TABLE IPv4", {"ip", "-4", "route", "show", "table", table});
1491 RunCommand("ROUTE TABLE IPv6", {"ip", "-6", "route", "show", "table", table});
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001492 }
1493 fclose(fp);
1494}
Felipe Leme71bbfc52015-11-23 14:14:51 -08001495
Felipe Leme71bbfc52015-11-23 14:14:51 -08001496// TODO: make this function thread safe if sections are generated in parallel.
Felipe Leme7447d7c2016-11-03 18:12:22 -07001497void Dumpstate::UpdateProgress(int32_t delta) {
1498 if (progress_ == nullptr) {
1499 MYLOGE("UpdateProgress: progress_ not set\n");
1500 return;
1501 }
Felipe Leme71bbfc52015-11-23 14:14:51 -08001502
Felipe Leme7447d7c2016-11-03 18:12:22 -07001503 // Always update progess so stats can be tuned...
1504 bool max_changed = progress_->Inc(delta);
1505
1506 // ...but only notifiy listeners when necessary.
1507 if (!update_progress_) return;
Felipe Leme71bbfc52015-11-23 14:14:51 -08001508
Felipe Leme009ecbb2016-11-07 10:18:44 -08001509 int progress = progress_->Get();
1510 int max = progress_->GetMax();
Felipe Lemead5f6c42015-11-30 14:26:46 -08001511
1512 // adjusts max on the fly
Felipe Leme009ecbb2016-11-07 10:18:44 -08001513 if (max_changed && listener_ != nullptr) {
1514 listener_->onMaxProgressUpdated(max);
Felipe Lemead5f6c42015-11-30 14:26:46 -08001515 }
1516
Felipe Leme009ecbb2016-11-07 10:18:44 -08001517 int32_t last_update_delta = progress - last_updated_progress_;
1518 if (last_updated_progress_ > 0 && last_update_delta < update_progress_threshold_) {
1519 return;
1520 }
1521 last_updated_progress_ = progress;
Felipe Leme7447d7c2016-11-03 18:12:22 -07001522
Felipe Leme9a523ae2016-10-20 15:10:33 -07001523 if (control_socket_fd_ >= 0) {
Felipe Leme7447d7c2016-11-03 18:12:22 -07001524 dprintf(control_socket_fd_, "PROGRESS:%d/%d\n", progress, max);
Felipe Leme9a523ae2016-10-20 15:10:33 -07001525 fsync(control_socket_fd_);
Felipe Leme02b7e002016-07-22 12:03:20 -07001526 }
1527
Felipe Leme75876a22016-10-27 16:31:27 -07001528 if (listener_ != nullptr) {
Felipe Leme7447d7c2016-11-03 18:12:22 -07001529 if (progress % 100 == 0) {
Felipe Leme75876a22016-10-27 16:31:27 -07001530 // We don't want to spam logcat, so only log multiples of 100.
Felipe Leme7447d7c2016-11-03 18:12:22 -07001531 MYLOGD("Setting progress (%s): %d/%d\n", listener_name_.c_str(), progress, max);
Felipe Leme75876a22016-10-27 16:31:27 -07001532 } else {
1533 // stderr is ignored on normal invocations, but useful when calling
1534 // /system/bin/dumpstate directly for debuggging.
Felipe Leme7447d7c2016-11-03 18:12:22 -07001535 fprintf(stderr, "Setting progress (%s): %d/%d\n", listener_name_.c_str(), progress, max);
Felipe Leme75876a22016-10-27 16:31:27 -07001536 }
Felipe Leme7447d7c2016-11-03 18:12:22 -07001537 listener_->onProgressUpdated(progress);
Felipe Leme71bbfc52015-11-23 14:14:51 -08001538 }
1539}
Felipe Lemee338bf62015-12-07 14:03:50 -08001540
Felipe Lemebbaf3c12016-10-11 14:32:25 -07001541void Dumpstate::TakeScreenshot(const std::string& path) {
Felipe Leme9a523ae2016-10-20 15:10:33 -07001542 const std::string& real_path = path.empty() ? screenshot_path_ : path;
Felipe Lemebbaf3c12016-10-11 14:32:25 -07001543 int status =
Felipe Leme9a523ae2016-10-20 15:10:33 -07001544 RunCommand("", {"/system/bin/screencap", "-p", real_path},
Felipe Lemebbaf3c12016-10-11 14:32:25 -07001545 CommandOptions::WithTimeout(10).Always().DropRoot().RedirectStderr().Build());
1546 if (status == 0) {
Felipe Leme9a523ae2016-10-20 15:10:33 -07001547 MYLOGD("Screenshot saved on %s\n", real_path.c_str());
Felipe Lemebbaf3c12016-10-11 14:32:25 -07001548 } else {
Felipe Leme9a523ae2016-10-20 15:10:33 -07001549 MYLOGE("Failed to take screenshot on %s\n", real_path.c_str());
Felipe Lemebbaf3c12016-10-11 14:32:25 -07001550 }
Felipe Lemee338bf62015-12-07 14:03:50 -08001551}
Mark Salyzynf55d4022015-12-11 07:32:31 -08001552
Felipe Leme0c80cf02016-01-05 13:25:34 -08001553void vibrate(FILE* vibrator, int ms) {
1554 fprintf(vibrator, "%d\n", ms);
1555 fflush(vibrator);
1556}
1557
1558bool is_dir(const char* pathname) {
1559 struct stat info;
1560 if (stat(pathname, &info) == -1) {
1561 return false;
1562 }
1563 return S_ISDIR(info.st_mode);
1564}
1565
1566time_t get_mtime(int fd, time_t default_mtime) {
1567 struct stat info;
1568 if (fstat(fd, &info) == -1) {
1569 return default_mtime;
1570 }
1571 return info.st_mtime;
1572}
1573
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001574void dump_emmc_ecsd(const char *ext_csd_path) {
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001575 // List of interesting offsets
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001576 struct hex {
1577 char str[2];
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001578 };
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001579 static const size_t EXT_CSD_REV = 192 * sizeof(hex);
1580 static const size_t EXT_PRE_EOL_INFO = 267 * sizeof(hex);
1581 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_A = 268 * sizeof(hex);
1582 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_B = 269 * sizeof(hex);
1583
1584 std::string buffer;
1585 if (!android::base::ReadFileToString(ext_csd_path, &buffer)) {
1586 return;
1587 }
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001588
1589 printf("------ %s Extended CSD ------\n", ext_csd_path);
1590
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001591 if (buffer.length() < (EXT_CSD_REV + sizeof(hex))) {
1592 printf("*** %s: truncated content %zu\n\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001593 return;
1594 }
1595
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001596 int ext_csd_rev = 0;
1597 std::string sub = buffer.substr(EXT_CSD_REV, sizeof(hex));
1598 if (sscanf(sub.c_str(), "%2x", &ext_csd_rev) != 1) {
1599 printf("*** %s: EXT_CSD_REV parse error \"%s\"\n\n",
1600 ext_csd_path, sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001601 return;
1602 }
1603
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001604 static const char *ver_str[] = {
1605 "4.0", "4.1", "4.2", "4.3", "Obsolete", "4.41", "4.5", "5.0"
1606 };
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001607 printf("rev 1.%d (MMC %s)\n",
1608 ext_csd_rev,
1609 (ext_csd_rev < (int)(sizeof(ver_str) / sizeof(ver_str[0]))) ?
1610 ver_str[ext_csd_rev] :
1611 "Unknown");
1612 if (ext_csd_rev < 7) {
1613 printf("\n");
1614 return;
1615 }
1616
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001617 if (buffer.length() < (EXT_PRE_EOL_INFO + sizeof(hex))) {
1618 printf("*** %s: truncated content %zu\n\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001619 return;
1620 }
1621
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001622 int ext_pre_eol_info = 0;
1623 sub = buffer.substr(EXT_PRE_EOL_INFO, sizeof(hex));
1624 if (sscanf(sub.c_str(), "%2x", &ext_pre_eol_info) != 1) {
1625 printf("*** %s: PRE_EOL_INFO parse error \"%s\"\n\n",
1626 ext_csd_path, sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001627 return;
1628 }
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001629
1630 static const char *eol_str[] = {
1631 "Undefined",
1632 "Normal",
1633 "Warning (consumed 80% of reserve)",
1634 "Urgent (consumed 90% of reserve)"
1635 };
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001636 printf("PRE_EOL_INFO %d (MMC %s)\n",
1637 ext_pre_eol_info,
1638 eol_str[(ext_pre_eol_info < (int)
1639 (sizeof(eol_str) / sizeof(eol_str[0]))) ?
1640 ext_pre_eol_info : 0]);
1641
1642 for (size_t lifetime = EXT_DEVICE_LIFE_TIME_EST_TYP_A;
1643 lifetime <= EXT_DEVICE_LIFE_TIME_EST_TYP_B;
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001644 lifetime += sizeof(hex)) {
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001645 int ext_device_life_time_est;
1646 static const char *est_str[] = {
1647 "Undefined",
1648 "0-10% of device lifetime used",
1649 "10-20% of device lifetime used",
1650 "20-30% of device lifetime used",
1651 "30-40% of device lifetime used",
1652 "40-50% of device lifetime used",
1653 "50-60% of device lifetime used",
1654 "60-70% of device lifetime used",
1655 "70-80% of device lifetime used",
1656 "80-90% of device lifetime used",
1657 "90-100% of device lifetime used",
1658 "Exceeded the maximum estimated device lifetime",
1659 };
1660
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001661 if (buffer.length() < (lifetime + sizeof(hex))) {
1662 printf("*** %s: truncated content %zu\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001663 break;
1664 }
1665
1666 ext_device_life_time_est = 0;
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001667 sub = buffer.substr(lifetime, sizeof(hex));
1668 if (sscanf(sub.c_str(), "%2x", &ext_device_life_time_est) != 1) {
1669 printf("*** %s: DEVICE_LIFE_TIME_EST_TYP_%c parse error \"%s\"\n",
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001670 ext_csd_path,
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001671 (unsigned)((lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) /
1672 sizeof(hex)) + 'A',
1673 sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001674 continue;
1675 }
1676 printf("DEVICE_LIFE_TIME_EST_TYP_%c %d (MMC %s)\n",
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001677 (unsigned)((lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) /
1678 sizeof(hex)) + 'A',
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001679 ext_device_life_time_est,
1680 est_str[(ext_device_life_time_est < (int)
1681 (sizeof(est_str) / sizeof(est_str[0]))) ?
1682 ext_device_life_time_est : 0]);
1683 }
1684
1685 printf("\n");
1686}