blob: d33460c31fdbfbe75b818f0decccd9390d5ffc88 [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 Leme7447d7c2016-11-03 18:12:22 -070072static void UpdateProgress(int32_t delta) {
Felipe Lemed80e6b62016-10-03 13:08:14 -070073 ds.UpdateProgress(delta);
74}
Felipe Lemee844a9d2016-09-21 15:01:39 -070075
Jeff Brownbf7f4922012-06-07 16:40:01 -070076/* list of native processes to include in the native dumps */
Andy Hung5c04e742016-04-13 19:35:34 -070077// This matches the /proc/pid/exe link instead of /proc/pid/cmdline.
Jeff Brownbf7f4922012-06-07 16:40:01 -070078static const char* native_processes_to_dump[] = {
Andy Hung9609bbd2015-12-15 12:42:50 -080079 "/system/bin/audioserver",
Chien-Yu Chenf5248da2016-01-28 14:23:03 -080080 "/system/bin/cameraserver",
James Dong1fc4f802012-09-10 16:08:48 -070081 "/system/bin/drmserver",
Andy Hung5c04e742016-04-13 19:35:34 -070082 "/system/bin/mediacodec", // media.codec
83 "/system/bin/mediadrmserver",
84 "/system/bin/mediaextractor", // media.extractor
Jeff Brownbf7f4922012-06-07 16:40:01 -070085 "/system/bin/mediaserver",
86 "/system/bin/sdcard",
87 "/system/bin/surfaceflinger",
keunyoungd907b322015-10-16 15:21:43 -070088 "/system/bin/vehicle_network_service",
Jeff Brownbf7f4922012-06-07 16:40:01 -070089 NULL,
90};
91
Felipe Lemee844a9d2016-09-21 15:01:39 -070092/* Most simple commands have 10 as timeout, so 5 is a good estimate */
93static const int WEIGHT_FILE = 5;
94
Felipe Leme7447d7c2016-11-03 18:12:22 -070095// Reasonable value for max stats.
96static const int STATS_MAX_N_RUNS = 1000;
97static const long STATS_MAX_AVERAGE = 100000;
98
Felipe Leme30dbfa12016-09-02 12:43:26 -070099CommandOptions CommandOptions::DEFAULT = CommandOptions::WithTimeout(10).Build();
100CommandOptions CommandOptions::DEFAULT_DUMPSYS = CommandOptions::WithTimeout(30).Build();
101CommandOptions CommandOptions::AS_ROOT_5 = CommandOptions::WithTimeout(5).AsRoot().Build();
102CommandOptions CommandOptions::AS_ROOT_10 = CommandOptions::WithTimeout(10).AsRoot().Build();
103CommandOptions CommandOptions::AS_ROOT_20 = CommandOptions::WithTimeout(20).AsRoot().Build();
104
Felipe Leme9a523ae2016-10-20 15:10:33 -0700105CommandOptions::CommandOptionsBuilder::CommandOptionsBuilder(long timeout) : values(timeout) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700106}
107
108CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::Always() {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700109 values.always_ = true;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700110 return *this;
111}
112
113CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::AsRoot() {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700114 values.root_mode_ = SU_ROOT;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700115 return *this;
116}
117
118CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::DropRoot() {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700119 values.root_mode_ = DROP_ROOT;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700120 return *this;
121}
122
123CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::RedirectStderr() {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700124 values.stdout_mode_ = REDIRECT_TO_STDERR;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700125 return *this;
126}
127
128CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::Log(
129 const std::string& message) {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700130 values.logging_message_ = message;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700131 return *this;
132}
133
134CommandOptions CommandOptions::CommandOptionsBuilder::Build() {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700135 return CommandOptions(values);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700136}
137
138CommandOptions::CommandOptionsValues::CommandOptionsValues(long timeout)
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700139 : timeout_(timeout),
140 always_(false),
Felipe Leme9a523ae2016-10-20 15:10:33 -0700141 root_mode_(DONT_DROP_ROOT),
142 stdout_mode_(NORMAL_STDOUT),
143 logging_message_("") {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700144}
145
Felipe Leme9a523ae2016-10-20 15:10:33 -0700146CommandOptions::CommandOptions(const CommandOptionsValues& values) : values(values) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700147}
148
149long CommandOptions::Timeout() const {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700150 return values.timeout_;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700151}
152
153bool CommandOptions::Always() const {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700154 return values.always_;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700155}
156
157RootMode CommandOptions::RootMode() const {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700158 return values.root_mode_;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700159}
160
161StdoutMode CommandOptions::StdoutMode() const {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700162 return values.stdout_mode_;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700163}
164
165std::string CommandOptions::LoggingMessage() const {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700166 return values.logging_message_;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700167}
168
169CommandOptions::CommandOptionsBuilder CommandOptions::WithTimeout(long timeout) {
170 return CommandOptions::CommandOptionsBuilder(timeout);
171}
172
Felipe Lemed071c682016-10-20 16:48:00 -0700173Dumpstate::Dumpstate(const std::string& version, bool dry_run, const std::string& build_type)
Felipe Leme75876a22016-10-27 16:31:27 -0700174 : pid_(getpid()),
175 version_(version),
176 now_(time(nullptr)),
177 dry_run_(dry_run),
178 build_type_(build_type) {
Felipe Lemee844a9d2016-09-21 15:01:39 -0700179}
180
181Dumpstate& Dumpstate::GetInstance() {
Felipe Lemed071c682016-10-20 16:48:00 -0700182 static Dumpstate singleton_(android::base::GetProperty("dumpstate.version", VERSION_CURRENT),
183 android::base::GetBoolProperty("dumpstate.dry_run", false),
Felipe Lemed80e6b62016-10-03 13:08:14 -0700184 android::base::GetProperty("ro.build.type", "(unknown)"));
Felipe Leme9a523ae2016-10-20 15:10:33 -0700185 return singleton_;
Felipe Lemee844a9d2016-09-21 15:01:39 -0700186}
187
Felipe Leme678727a2016-09-21 17:22:11 -0700188DurationReporter::DurationReporter(const std::string& title) : DurationReporter(title, stdout) {
189}
Felipe Leme608385d2016-02-01 10:35:38 -0800190
Felipe Leme678727a2016-09-21 17:22:11 -0700191DurationReporter::DurationReporter(const std::string& title, FILE* out) : title_(title), out_(out) {
192 if (!title_.empty()) {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700193 started_ = DurationReporter::Nanotime();
Felipe Leme78f2c862015-12-21 09:55:22 -0800194 }
195}
196
197DurationReporter::~DurationReporter() {
Felipe Leme678727a2016-09-21 17:22:11 -0700198 if (!title_.empty()) {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700199 uint64_t elapsed = DurationReporter::Nanotime() - started_;
Felipe Leme78f2c862015-12-21 09:55:22 -0800200 // Use "Yoda grammar" to make it easier to grep|sort sections.
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700201 if (out_ != nullptr) {
202 fprintf(out_, "------ %.3fs was the duration of '%s' ------\n",
Felipe Leme678727a2016-09-21 17:22:11 -0700203 (float)elapsed / NANOS_PER_SEC, title_.c_str());
Felipe Leme608385d2016-02-01 10:35:38 -0800204 } else {
Felipe Leme678727a2016-09-21 17:22:11 -0700205 MYLOGD("Duration of '%s': %.3fs\n", title_.c_str(), (float)elapsed / NANOS_PER_SEC);
Felipe Leme608385d2016-02-01 10:35:38 -0800206 }
Felipe Leme78f2c862015-12-21 09:55:22 -0800207 }
208}
209
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700210uint64_t DurationReporter::DurationReporter::Nanotime() {
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800211 struct timespec ts;
212 clock_gettime(CLOCK_MONOTONIC, &ts);
Felipe Leme78f2c862015-12-21 09:55:22 -0800213 return (uint64_t) ts.tv_sec * NANOS_PER_SEC + ts.tv_nsec;
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800214}
215
Felipe Leme7447d7c2016-11-03 18:12:22 -0700216const int32_t Progress::kDefaultMax = 5000;
217
218Progress::Progress(const std::string& path) : Progress(Progress::kDefaultMax, 1.1, path) {
219}
220
221Progress::Progress(int32_t initial_max, int32_t progress, float growth_factor)
222 : Progress(initial_max, growth_factor, "") {
223 progress_ = progress;
224}
225
226Progress::Progress(int32_t initial_max, float growth_factor, const std::string& path)
227 : initial_max_(initial_max),
228 progress_(0),
229 max_(initial_max),
230 growth_factor_(growth_factor),
231 n_runs_(0),
232 average_max_(0),
233 path_(path) {
234 if (!path_.empty()) {
235 Load();
236 }
237}
238
239void Progress::Load() {
240 MYLOGD("Loading stats from %s\n", path_.c_str());
241 std::string content;
242 if (!android::base::ReadFileToString(path_, &content)) {
243 MYLOGI("Could not read stats from %s; using max of %d\n", path_.c_str(), max_);
244 return;
245 }
246 if (content.empty()) {
247 MYLOGE("No stats (empty file) on %s; using max of %d\n", path_.c_str(), max_);
248 return;
249 }
250 std::vector<std::string> lines = android::base::Split(content, "\n");
251
252 if (lines.size() < 1) {
253 MYLOGE("Invalid stats on file %s: not enough lines (%d). Using max of %d\n", path_.c_str(),
254 (int)lines.size(), max_);
255 return;
256 }
257 char* ptr;
258 n_runs_ = strtol(lines[0].c_str(), &ptr, 10);
259 average_max_ = strtol(ptr, nullptr, 10);
260 if (n_runs_ <= 0 || average_max_ <= 0 || n_runs_ > STATS_MAX_N_RUNS ||
261 average_max_ > STATS_MAX_AVERAGE) {
262 MYLOGE("Invalid stats line on file %s: %s\n", path_.c_str(), lines[0].c_str());
263 initial_max_ = Progress::kDefaultMax;
264 } else {
265 initial_max_ = average_max_;
266 }
267 max_ = initial_max_;
268
269 MYLOGI("Average max progress: %d in %d runs; estimated max: %d\n", average_max_, n_runs_, max_);
270}
271
272void Progress::Save() {
273 int32_t total = n_runs_ * average_max_ + progress_;
274 int32_t runs = n_runs_ + 1;
275 int32_t average = floor(((float)total) / runs);
276 MYLOGI("Saving stats (total=%d, runs=%d, average=%d) on %s\n", total, runs, average,
277 path_.c_str());
278 if (path_.empty()) {
279 return;
280 }
281
282 std::string content = android::base::StringPrintf("%d %d\n", runs, average);
283 if (!android::base::WriteStringToFile(content, path_)) {
284 MYLOGE("Could not save stats on %s\n", path_.c_str());
285 }
286}
287
288int32_t Progress::Get() const {
289 return progress_;
290}
291
292bool Progress::Inc(int32_t delta) {
293 bool changed = false;
294 if (delta >= 0) {
295 progress_ += delta;
296 if (progress_ > max_) {
297 int32_t old_max = max_;
298 max_ = floor((float)progress_ * growth_factor_);
299 MYLOGD("Adjusting max progress from %d to %d\n", old_max, max_);
300 changed = true;
301 }
302 }
303 return changed;
304}
305
306int32_t Progress::GetMax() const {
307 return max_;
308}
309
310int32_t Progress::GetInitialMax() const {
311 return initial_max_;
312}
313
314void Progress::Dump(int fd, const std::string& prefix) const {
315 const char* pr = prefix.c_str();
316 dprintf(fd, "%sprogress: %d\n", pr, progress_);
317 dprintf(fd, "%smax: %d\n", pr, max_);
318 dprintf(fd, "%sinitial_max: %d\n", pr, initial_max_);
319 dprintf(fd, "%sgrowth_factor: %0.2f\n", pr, growth_factor_);
320 dprintf(fd, "%spath: %s\n", pr, path_.c_str());
321 dprintf(fd, "%sn_runs: %d\n", pr, n_runs_);
322 dprintf(fd, "%saverage_max: %d\n", pr, average_max_);
323}
324
Felipe Leme2b9b06c2016-10-14 09:13:06 -0700325bool Dumpstate::IsDryRun() const {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700326 return dry_run_;
Felipe Leme4c2d6632016-09-28 14:32:00 -0700327}
328
Felipe Leme2b9b06c2016-10-14 09:13:06 -0700329bool Dumpstate::IsUserBuild() const {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700330 return "user" == build_type_;
Felipe Lemee844a9d2016-09-21 15:01:39 -0700331}
332
Felipe Leme75876a22016-10-27 16:31:27 -0700333bool Dumpstate::IsZipping() const {
334 return zip_writer_ != nullptr;
335}
336
Felipe Leme2b9b06c2016-10-14 09:13:06 -0700337std::string Dumpstate::GetPath(const std::string& suffix) const {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700338 return android::base::StringPrintf("%s/%s-%s%s", bugreport_dir_.c_str(), base_name_.c_str(),
Felipe Leme2b9b06c2016-10-14 09:13:06 -0700339 name_.c_str(), suffix.c_str());
Felipe Lemebbaf3c12016-10-11 14:32:25 -0700340}
341
Felipe Leme7447d7c2016-11-03 18:12:22 -0700342void Dumpstate::SetProgress(std::unique_ptr<Progress> progress) {
343 progress_ = std::move(progress);
344}
345
John Spurlock5ecd4be2014-01-29 14:14:40 -0500346void for_each_userid(void (*func)(int), const char *header) {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700347 if (IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700348
John Spurlock5ecd4be2014-01-29 14:14:40 -0500349 DIR *d;
350 struct dirent *de;
351
352 if (header) printf("\n------ %s ------\n", header);
353 func(0);
354
355 if (!(d = opendir("/data/system/users"))) {
356 printf("Failed to open /data/system/users (%s)\n", strerror(errno));
357 return;
358 }
359
360 while ((de = readdir(d))) {
361 int userid;
362 if (de->d_type != DT_DIR || !(userid = atoi(de->d_name))) {
363 continue;
364 }
365 func(userid);
366 }
367
368 closedir(d);
369}
370
Colin Cross0c22e8b2012-11-02 15:46:56 -0700371static void __for_each_pid(void (*helper)(int, const char *, void *), const char *header, void *arg) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700372 DIR *d;
373 struct dirent *de;
374
375 if (!(d = opendir("/proc"))) {
376 printf("Failed to open /proc (%s)\n", strerror(errno));
377 return;
378 }
379
Felipe Leme635ca312016-01-05 14:23:02 -0800380 if (header) printf("\n------ %s ------\n", header);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700381 while ((de = readdir(d))) {
382 int pid;
383 int fd;
384 char cmdpath[255];
385 char cmdline[255];
386
387 if (!(pid = atoi(de->d_name))) {
388 continue;
389 }
390
Colin Crossf45fa6b2012-03-26 12:38:26 -0700391 memset(cmdline, 0, sizeof(cmdline));
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800392
393 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/cmdline", pid);
394 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
395 TEMP_FAILURE_RETRY(read(fd, cmdline, sizeof(cmdline) - 2));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700396 close(fd);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800397 if (cmdline[0]) {
398 helper(pid, cmdline, arg);
399 continue;
400 }
401 }
402
403 // if no cmdline, a kernel thread has comm
404 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/comm", pid);
405 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
406 TEMP_FAILURE_RETRY(read(fd, cmdline + 1, sizeof(cmdline) - 4));
407 close(fd);
408 if (cmdline[1]) {
409 cmdline[0] = '[';
410 size_t len = strcspn(cmdline, "\f\b\r\n");
411 cmdline[len] = ']';
412 cmdline[len+1] = '\0';
413 }
414 }
415 if (!cmdline[0]) {
416 strcpy(cmdline, "N/A");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700417 }
Colin Cross0c22e8b2012-11-02 15:46:56 -0700418 helper(pid, cmdline, arg);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700419 }
420
421 closedir(d);
422}
423
Colin Cross0c22e8b2012-11-02 15:46:56 -0700424static void for_each_pid_helper(int pid, const char *cmdline, void *arg) {
Felipe Leme8620bb42015-11-10 11:04:45 -0800425 for_each_pid_func *func = (for_each_pid_func*) arg;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700426 func(pid, cmdline);
427}
428
429void for_each_pid(for_each_pid_func func, const char *header) {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700430 if (IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700431
Felipe Leme515eb0d2015-12-14 15:09:56 -0800432 __for_each_pid(for_each_pid_helper, header, (void *) func);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700433}
434
435static void for_each_tid_helper(int pid, const char *cmdline, void *arg) {
436 DIR *d;
437 struct dirent *de;
438 char taskpath[255];
Felipe Leme8620bb42015-11-10 11:04:45 -0800439 for_each_tid_func *func = (for_each_tid_func *) arg;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700440
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700441 snprintf(taskpath, sizeof(taskpath), "/proc/%d/task", pid);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700442
443 if (!(d = opendir(taskpath))) {
444 printf("Failed to open %s (%s)\n", taskpath, strerror(errno));
445 return;
446 }
447
448 func(pid, pid, cmdline);
449
450 while ((de = readdir(d))) {
451 int tid;
452 int fd;
453 char commpath[255];
454 char comm[255];
455
456 if (!(tid = atoi(de->d_name))) {
457 continue;
458 }
459
460 if (tid == pid)
461 continue;
462
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700463 snprintf(commpath, sizeof(commpath), "/proc/%d/comm", tid);
Colin Cross1493a392012-11-07 11:25:31 -0800464 memset(comm, 0, sizeof(comm));
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700465 if ((fd = TEMP_FAILURE_RETRY(open(commpath, O_RDONLY | O_CLOEXEC))) < 0) {
Colin Cross0c22e8b2012-11-02 15:46:56 -0700466 strcpy(comm, "N/A");
467 } else {
468 char *c;
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800469 TEMP_FAILURE_RETRY(read(fd, comm, sizeof(comm) - 2));
Colin Cross0c22e8b2012-11-02 15:46:56 -0700470 close(fd);
471
472 c = strrchr(comm, '\n');
473 if (c) {
474 *c = '\0';
475 }
476 }
477 func(pid, tid, comm);
478 }
479
480 closedir(d);
481}
482
483void for_each_tid(for_each_tid_func func, const char *header) {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700484 if (IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700485
Felipe Leme8620bb42015-11-10 11:04:45 -0800486 __for_each_pid(for_each_tid_helper, header, (void *) func);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700487}
488
489void show_wchan(int pid, int tid, const char *name) {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700490 if (IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700491
Colin Crossf45fa6b2012-03-26 12:38:26 -0700492 char path[255];
493 char buffer[255];
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800494 int fd, ret, save_errno;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700495 char name_buffer[255];
Colin Crossf45fa6b2012-03-26 12:38:26 -0700496
497 memset(buffer, 0, sizeof(buffer));
498
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700499 snprintf(path, sizeof(path), "/proc/%d/wchan", tid);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700500 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700501 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
502 return;
503 }
504
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800505 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
506 save_errno = errno;
507 close(fd);
508
509 if (ret < 0) {
510 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
511 return;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700512 }
513
Colin Cross0c22e8b2012-11-02 15:46:56 -0700514 snprintf(name_buffer, sizeof(name_buffer), "%*s%s",
515 pid == tid ? 0 : 3, "", name);
516
517 printf("%-7d %-32s %s\n", tid, name_buffer, buffer);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700518
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800519 return;
520}
521
522// print time in centiseconds
523static void snprcent(char *buffer, size_t len, size_t spc,
524 unsigned long long time) {
525 static long hz; // cache discovered hz
526
527 if (hz <= 0) {
528 hz = sysconf(_SC_CLK_TCK);
529 if (hz <= 0) {
530 hz = 1000;
531 }
532 }
533
534 // convert to centiseconds
535 time = (time * 100 + (hz / 2)) / hz;
536
537 char str[16];
538
539 snprintf(str, sizeof(str), " %llu.%02u",
540 time / 100, (unsigned)(time % 100));
541 size_t offset = strlen(buffer);
542 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
543 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
544}
545
546// print permille as a percent
547static void snprdec(char *buffer, size_t len, size_t spc, unsigned permille) {
548 char str[16];
549
550 snprintf(str, sizeof(str), " %u.%u%%", permille / 10, permille % 10);
551 size_t offset = strlen(buffer);
552 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
553 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
554}
555
556void show_showtime(int pid, const char *name) {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700557 if (IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700558
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800559 char path[255];
560 char buffer[1023];
561 int fd, ret, save_errno;
562
563 memset(buffer, 0, sizeof(buffer));
564
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700565 snprintf(path, sizeof(path), "/proc/%d/stat", pid);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800566 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
567 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
568 return;
569 }
570
571 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
572 save_errno = errno;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700573 close(fd);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800574
575 if (ret < 0) {
576 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
577 return;
578 }
579
580 // field 14 is utime
581 // field 15 is stime
582 // field 42 is iotime
583 unsigned long long utime = 0, stime = 0, iotime = 0;
584 if (sscanf(buffer,
Mark Salyzyn791ddd32016-02-10 07:41:12 -0800585 "%*u %*s %*s %*d %*d %*d %*d %*d %*d %*d %*d "
586 "%*d %*d %llu %llu %*d %*d %*d %*d %*d %*d "
587 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %*d "
588 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %llu ",
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800589 &utime, &stime, &iotime) != 3) {
590 return;
591 }
592
593 unsigned long long total = utime + stime;
594 if (!total) {
595 return;
596 }
597
598 unsigned permille = (iotime * 1000 + (total / 2)) / total;
599 if (permille > 1000) {
600 permille = 1000;
601 }
602
603 // try to beautify and stabilize columns at <80 characters
604 snprintf(buffer, sizeof(buffer), "%-6d%s", pid, name);
605 if ((name[0] != '[') || utime) {
606 snprcent(buffer, sizeof(buffer), 57, utime);
607 }
608 snprcent(buffer, sizeof(buffer), 65, stime);
609 if ((name[0] != '[') || iotime) {
610 snprcent(buffer, sizeof(buffer), 73, iotime);
611 }
612 if (iotime) {
613 snprdec(buffer, sizeof(buffer), 79, permille);
614 }
615 puts(buffer); // adds a trailing newline
616
Colin Crossf45fa6b2012-03-26 12:38:26 -0700617 return;
618}
619
620void do_dmesg() {
Felipe Leme78f2c862015-12-21 09:55:22 -0800621 const char *title = "KERNEL LOG (dmesg)";
622 DurationReporter duration_reporter(title);
623 printf("------ %s ------\n", title);
624
Felipe Leme4c2d6632016-09-28 14:32:00 -0700625 if (IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700626
Elliott Hughes5f87b312012-09-17 11:43:40 -0700627 /* Get size of kernel buffer */
628 int size = klogctl(KLOG_SIZE_BUFFER, NULL, 0);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700629 if (size <= 0) {
630 printf("Unexpected klogctl return value: %d\n\n", size);
631 return;
632 }
633 char *buf = (char *) malloc(size + 1);
634 if (buf == NULL) {
635 printf("memory allocation failed\n\n");
636 return;
637 }
638 int retval = klogctl(KLOG_READ_ALL, buf, size);
639 if (retval < 0) {
640 printf("klogctl failure\n\n");
641 free(buf);
642 return;
643 }
644 buf[retval] = '\0';
645 printf("%s\n\n", buf);
646 free(buf);
647 return;
648}
649
650void do_showmap(int pid, const char *name) {
651 char title[255];
652 char arg[255];
653
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700654 snprintf(title, sizeof(title), "SHOW MAP %d (%s)", pid, name);
655 snprintf(arg, sizeof(arg), "%d", pid);
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700656 RunCommand(title, {"showmap", "-q", arg}, CommandOptions::AS_ROOT_10);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700657}
658
Felipe Leme2b9b06c2016-10-14 09:13:06 -0700659// TODO: when converted to a Dumpstate function, it should be const
Felipe Leme678727a2016-09-21 17:22:11 -0700660static int _dump_file_from_fd(const std::string& title, const char* path, int fd) {
661 if (!title.empty()) {
662 printf("------ %s (%s", title.c_str(), path);
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800663
Colin Crossf45fa6b2012-03-26 12:38:26 -0700664 struct stat st;
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800665 // Only show the modification time of non-device files.
666 size_t path_len = strlen(path);
667 if ((path_len < 6 || memcmp(path, "/proc/", 6)) &&
668 (path_len < 5 || memcmp(path, "/sys/", 5)) &&
669 (path_len < 3 || memcmp(path, "/d/", 3)) &&
670 !fstat(fd, &st)) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700671 char stamp[80];
672 time_t mtime = st.st_mtime;
673 strftime(stamp, sizeof(stamp), "%Y-%m-%d %H:%M:%S", localtime(&mtime));
674 printf(": %s", stamp);
675 }
676 printf(") ------\n");
677 }
678
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800679 bool newline = false;
680 fd_set read_set;
681 struct timeval tm;
682 while (1) {
683 FD_ZERO(&read_set);
684 FD_SET(fd, &read_set);
685 /* Timeout if no data is read for 30 seconds. */
686 tm.tv_sec = 30;
687 tm.tv_usec = 0;
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700688 uint64_t elapsed = DurationReporter::Nanotime();
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800689 int ret = TEMP_FAILURE_RETRY(select(fd + 1, &read_set, NULL, NULL, &tm));
690 if (ret == -1) {
691 printf("*** %s: select failed: %s\n", path, strerror(errno));
692 newline = true;
693 break;
694 } else if (ret == 0) {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700695 elapsed = DurationReporter::Nanotime() - elapsed;
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800696 printf("*** %s: Timed out after %.3fs\n", path,
697 (float) elapsed / NANOS_PER_SEC);
698 newline = true;
699 break;
700 } else {
701 char buffer[65536];
702 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
703 if (bytes_read > 0) {
704 fwrite(buffer, bytes_read, 1, stdout);
705 newline = (buffer[bytes_read-1] == '\n');
706 } else {
707 if (bytes_read == -1) {
708 printf("*** %s: Failed to read from fd: %s", path, strerror(errno));
709 newline = true;
710 }
711 break;
712 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700713 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700714 }
Felipe Lemed80e6b62016-10-03 13:08:14 -0700715 UpdateProgress(WEIGHT_FILE);
Elliott Hughes997abb62015-05-15 17:05:40 -0700716 close(fd);
Christopher Ferris7dc7f322014-07-22 16:08:19 -0700717
Colin Crossf45fa6b2012-03-26 12:38:26 -0700718 if (!newline) printf("\n");
Felipe Leme678727a2016-09-21 17:22:11 -0700719 if (!title.empty()) printf("\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700720 return 0;
721}
722
Felipe Leme678727a2016-09-21 17:22:11 -0700723int Dumpstate::DumpFile(const std::string& title, const std::string& path) {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700724 DurationReporter duration_reporter(title);
Felipe Lemecef02982016-10-03 17:22:22 -0700725 if (IsDryRun()) {
726 if (!title.empty()) {
727 printf("------ %s (%s) ------\n", title.c_str(), path.c_str());
728 printf("\t(skipped on dry run)\n");
729 }
730 UpdateProgress(WEIGHT_FILE);
731 return 0;
732 }
Felipe Leme2b9b06c2016-10-14 09:13:06 -0700733 return JustDumpFile(title, path);
734}
Felipe Lemecef02982016-10-03 17:22:22 -0700735
Felipe Leme2b9b06c2016-10-14 09:13:06 -0700736int Dumpstate::JustDumpFile(const std::string& title, const std::string& path) const {
Felipe Leme0bcc7ca2016-09-13 16:45:56 -0700737 int fd = TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_NONBLOCK | O_CLOEXEC));
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800738 if (fd < 0) {
739 int err = errno;
Felipe Lemecef02982016-10-03 17:22:22 -0700740 if (title.empty()) {
741 printf("*** Error dumping %s: %s\n", path.c_str(), strerror(err));
742 } else {
743 printf("*** Error dumping %s (%s): %s\n", path.c_str(), title.c_str(), strerror(err));
744 }
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800745 return -1;
746 }
Felipe Leme0bcc7ca2016-09-13 16:45:56 -0700747 return _dump_file_from_fd(title, path.c_str(), fd);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800748}
749
Felipe Leme71a74ac2016-03-17 15:43:25 -0700750int read_file_as_long(const char *path, long int *output) {
751 int fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
752 if (fd < 0) {
753 int err = errno;
754 MYLOGE("Error opening file descriptor for %s: %s\n", path, strerror(err));
755 return -1;
756 }
757 char buffer[50];
758 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
759 if (bytes_read == -1) {
760 MYLOGE("Error reading file %s: %s\n", path, strerror(errno));
761 return -2;
762 }
763 if (bytes_read == 0) {
764 MYLOGE("File %s is empty\n", path);
765 return -3;
766 }
767 *output = atoi(buffer);
768 return 0;
769}
770
Mark Salyzyn326842f2015-04-30 09:49:41 -0700771/* calls skip to gate calling dump_from_fd recursively
772 * in the specified directory. dump_from_fd defaults to
773 * dump_file_from_fd above when set to NULL. skip defaults
774 * to false when set to NULL. dump_from_fd will always be
775 * called with title NULL.
776 */
Felipe Leme678727a2016-09-21 17:22:11 -0700777int dump_files(const std::string& title, const char* dir, bool (*skip)(const char* path),
778 int (*dump_from_fd)(const char* title, const char* path, int fd)) {
Felipe Leme78f2c862015-12-21 09:55:22 -0800779 DurationReporter duration_reporter(title);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700780 DIR *dirp;
781 struct dirent *d;
782 char *newpath = NULL;
Felipe Leme8620bb42015-11-10 11:04:45 -0800783 const char *slash = "/";
Mark Salyzyn326842f2015-04-30 09:49:41 -0700784 int fd, retval = 0;
785
Felipe Leme678727a2016-09-21 17:22:11 -0700786 if (!title.empty()) {
787 printf("------ %s (%s) ------\n", title.c_str(), dir);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700788 }
Felipe Leme4c2d6632016-09-28 14:32:00 -0700789 if (IsDryRun()) return 0;
Mark Salyzyn326842f2015-04-30 09:49:41 -0700790
791 if (dir[strlen(dir) - 1] == '/') {
792 ++slash;
793 }
794 dirp = opendir(dir);
795 if (dirp == NULL) {
796 retval = -errno;
Felipe Leme107a05f2016-03-08 15:11:15 -0800797 MYLOGE("%s: %s\n", dir, strerror(errno));
Mark Salyzyn326842f2015-04-30 09:49:41 -0700798 return retval;
799 }
800
801 if (!dump_from_fd) {
802 dump_from_fd = dump_file_from_fd;
803 }
804 for (; ((d = readdir(dirp))); free(newpath), newpath = NULL) {
805 if ((d->d_name[0] == '.')
806 && (((d->d_name[1] == '.') && (d->d_name[2] == '\0'))
807 || (d->d_name[1] == '\0'))) {
808 continue;
809 }
810 asprintf(&newpath, "%s%s%s%s", dir, slash, d->d_name,
811 (d->d_type == DT_DIR) ? "/" : "");
812 if (!newpath) {
813 retval = -errno;
814 continue;
815 }
816 if (skip && (*skip)(newpath)) {
817 continue;
818 }
819 if (d->d_type == DT_DIR) {
Felipe Leme678727a2016-09-21 17:22:11 -0700820 int ret = dump_files("", newpath, skip, dump_from_fd);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700821 if (ret < 0) {
822 retval = ret;
823 }
824 continue;
825 }
826 fd = TEMP_FAILURE_RETRY(open(newpath, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
827 if (fd < 0) {
828 retval = fd;
829 printf("*** %s: %s\n", newpath, strerror(errno));
830 continue;
831 }
832 (*dump_from_fd)(NULL, newpath, fd);
833 }
834 closedir(dirp);
Felipe Leme678727a2016-09-21 17:22:11 -0700835 if (!title.empty()) {
Mark Salyzyn326842f2015-04-30 09:49:41 -0700836 printf("\n");
837 }
838 return retval;
839}
840
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800841/* fd must have been opened with the flag O_NONBLOCK. With this flag set,
842 * it's possible to avoid issues where opening the file itself can get
843 * stuck.
844 */
845int dump_file_from_fd(const char *title, const char *path, int fd) {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700846 if (IsDryRun()) return 0;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700847
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800848 int flags = fcntl(fd, F_GETFL);
849 if (flags == -1) {
850 printf("*** %s: failed to get flags on fd %d: %s\n", path, fd, strerror(errno));
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800851 close(fd);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800852 return -1;
853 } else if (!(flags & O_NONBLOCK)) {
854 printf("*** %s: fd must have O_NONBLOCK set.\n", path);
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800855 close(fd);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800856 return -1;
857 }
858 return _dump_file_from_fd(title, path, fd);
Jeff Brown1dc94e32014-09-11 14:15:27 -0700859}
860
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800861bool waitpid_with_timeout(pid_t pid, int timeout_seconds, int* status) {
862 sigset_t child_mask, old_mask;
863 sigemptyset(&child_mask);
864 sigaddset(&child_mask, SIGCHLD);
865
866 if (sigprocmask(SIG_BLOCK, &child_mask, &old_mask) == -1) {
867 printf("*** sigprocmask failed: %s\n", strerror(errno));
868 return false;
869 }
870
871 struct timespec ts;
872 ts.tv_sec = timeout_seconds;
873 ts.tv_nsec = 0;
874 int ret = TEMP_FAILURE_RETRY(sigtimedwait(&child_mask, NULL, &ts));
875 int saved_errno = errno;
876 // Set the signals back the way they were.
877 if (sigprocmask(SIG_SETMASK, &old_mask, NULL) == -1) {
878 printf("*** sigprocmask failed: %s\n", strerror(errno));
879 if (ret == 0) {
880 return false;
881 }
882 }
883 if (ret == -1) {
884 errno = saved_errno;
885 if (errno == EAGAIN) {
886 errno = ETIMEDOUT;
887 } else {
888 printf("*** sigtimedwait failed: %s\n", strerror(errno));
889 }
890 return false;
891 }
892
893 pid_t child_pid = waitpid(pid, status, WNOHANG);
894 if (child_pid != pid) {
895 if (child_pid != -1) {
896 printf("*** Waiting for pid %d, got pid %d instead\n", pid, child_pid);
897 } else {
898 printf("*** waitpid failed: %s\n", strerror(errno));
899 }
900 return false;
901 }
902 return true;
903}
904
Felipe Leme9a523ae2016-10-20 15:10:33 -0700905int Dumpstate::RunCommand(const std::string& title, const std::vector<std::string>& full_command,
Felipe Leme678727a2016-09-21 17:22:11 -0700906 const CommandOptions& options) {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700907 if (full_command.empty()) {
Felipe Leme678727a2016-09-21 17:22:11 -0700908 MYLOGE("No arguments on command '%s'\n", title.c_str());
Felipe Leme30dbfa12016-09-02 12:43:26 -0700909 return -1;
910 }
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800911
Felipe Leme9a523ae2016-10-20 15:10:33 -0700912 int size = full_command.size() + 1; // null terminated
913 int starting_index = 0;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700914 if (options.RootMode() == SU_ROOT) {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700915 starting_index = 2; // "su" "root"
916 size += starting_index;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700917 }
918
Felipe Leme6ad9c062016-09-28 11:58:36 -0700919 std::vector<const char*> args;
920 args.resize(size);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700921
Felipe Leme9a523ae2016-10-20 15:10:33 -0700922 std::string command_string;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700923 if (options.RootMode() == SU_ROOT) {
924 args[0] = SU_PATH;
Felipe Leme9a523ae2016-10-20 15:10:33 -0700925 command_string += SU_PATH;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700926 args[1] = "root";
Felipe Leme9a523ae2016-10-20 15:10:33 -0700927 command_string += " root ";
Felipe Leme30dbfa12016-09-02 12:43:26 -0700928 }
Felipe Leme9a523ae2016-10-20 15:10:33 -0700929 int i = starting_index;
930 for (auto arg = full_command.begin(); arg != full_command.end(); ++arg) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700931 args[i++] = arg->c_str();
Felipe Leme9a523ae2016-10-20 15:10:33 -0700932 command_string += arg->c_str();
933 if (arg != full_command.end() - 1) {
934 command_string += " ";
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800935 }
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800936 }
Felipe Leme30dbfa12016-09-02 12:43:26 -0700937 args[i] = nullptr;
938 const char* path = args[0];
Felipe Leme9a523ae2016-10-20 15:10:33 -0700939 const char* command = command_string.c_str();
Felipe Lemec5d6cfc2016-09-26 15:57:04 -0700940
Felipe Leme6ad9c062016-09-28 11:58:36 -0700941 if (options.RootMode() == SU_ROOT && ds.IsUserBuild()) {
942 printf("Skipping '%s' on user build.\n", command);
943 return 0;
944 }
945
Felipe Leme678727a2016-09-21 17:22:11 -0700946 if (!title.empty()) {
Felipe Leme6ad9c062016-09-28 11:58:36 -0700947 printf("------ %s (%s) ------\n", title.c_str(), command);
Felipe Lemec5d6cfc2016-09-26 15:57:04 -0700948 }
Felipe Leme30dbfa12016-09-02 12:43:26 -0700949
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800950 fflush(stdout);
Felipe Leme9a523ae2016-10-20 15:10:33 -0700951 DurationReporter duration_reporter(title);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700952
Felipe Leme9a523ae2016-10-20 15:10:33 -0700953 const std::string& logging_message = options.LoggingMessage();
954 if (!logging_message.empty()) {
955 MYLOGI(logging_message.c_str(), command_string.c_str());
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800956 }
957
Felipe Leme4c2d6632016-09-28 14:32:00 -0700958 if (IsDryRun() && !options.Always()) {
959 if (!title.empty()) {
960 printf("\t(skipped on dry run)\n");
961 }
Felipe Lemed80e6b62016-10-03 13:08:14 -0700962 UpdateProgress(options.Timeout());
Felipe Leme30dbfa12016-09-02 12:43:26 -0700963 return 0;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700964 }
Felipe Leme93d705b2015-11-10 20:10:25 -0800965
Felipe Leme2b9b06c2016-10-14 09:13:06 -0700966 int status = JustRunCommand(command, path, args, options);
Felipe Lemeea160d12016-03-24 11:29:44 -0700967
Felipe Leme30dbfa12016-09-02 12:43:26 -0700968 /* TODO: for now we're simplifying the progress calculation by using the
969 * timeout as the weight. It's a good approximation for most cases, except when calling dumpsys,
970 * where its weight should be much higher proportionally to its timeout.
971 * Ideally, it should use a options.EstimatedDuration() instead...*/
972 int weight = options.Timeout();
Felipe Leme93d705b2015-11-10 20:10:25 -0800973
Felipe Leme2b9b06c2016-10-14 09:13:06 -0700974 if (weight > 0) {
975 UpdateProgress(weight);
976 }
977
978 return status;
979}
980
981int Dumpstate::JustRunCommand(const char* command, const char* path, std::vector<const char*>& args,
982 const CommandOptions& options) const {
983 bool silent = (options.StdoutMode() == REDIRECT_TO_STDERR);
984
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700985 uint64_t start = DurationReporter::Nanotime();
Colin Crossf45fa6b2012-03-26 12:38:26 -0700986 pid_t pid = fork();
987
988 /* handle error case */
989 if (pid < 0) {
Felipe Leme29c39712016-04-01 10:02:00 -0700990 if (!silent) printf("*** fork: %s\n", strerror(errno));
991 MYLOGE("*** fork: %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700992 return pid;
993 }
994
995 /* handle child case */
996 if (pid == 0) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700997 if (options.RootMode() == DROP_ROOT && !drop_root_user()) {
998 if (!silent)
999 printf("*** failed to drop root before running %s: %s\n", command, strerror(errno));
Felipe Leme29c39712016-04-01 10:02:00 -07001000 MYLOGE("*** could not drop root before running %s: %s\n", command, strerror(errno));
Felipe Leme73f731c2016-03-23 16:47:00 -07001001 return -1;
Felipe Lemecf6a8b42016-03-11 10:38:19 -08001002 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001003
Felipe Leme29c39712016-04-01 10:02:00 -07001004 if (silent) {
1005 // Redirect stderr to stdout
1006 dup2(STDERR_FILENO, STDOUT_FILENO);
1007 }
1008
John Michelaue7b6cf12013-03-07 15:35:35 -06001009 /* make sure the child dies when dumpstate dies */
1010 prctl(PR_SET_PDEATHSIG, SIGKILL);
1011
Andres Morales2e671bb2014-08-21 12:38:22 -07001012 /* just ignore SIGPIPE, will go down with parent's */
1013 struct sigaction sigact;
1014 memset(&sigact, 0, sizeof(sigact));
1015 sigact.sa_handler = SIG_IGN;
1016 sigaction(SIGPIPE, &sigact, NULL);
1017
Felipe Leme6ad9c062016-09-28 11:58:36 -07001018 execvp(path, (char**)args.data());
Felipe Leme30dbfa12016-09-02 12:43:26 -07001019 // execvp's result will be handled after waitpid_with_timeout() below, but
1020 // if it failed, it's safer to exit dumpstate.
1021 MYLOGD("execvp on command '%s' failed (error: %s)\n", command, strerror(errno));
Felipe Lemeec725782016-03-23 11:47:00 -07001022 fflush(stdout);
Felipe Leme30dbfa12016-09-02 12:43:26 -07001023 // Must call _exit (instead of exit), otherwise it will corrupt the zip
1024 // file.
Felipe Lemebaa85bd2016-03-29 13:29:11 -07001025 _exit(EXIT_FAILURE);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001026 }
1027
1028 /* handle parent case */
Christopher Ferris1a9a3382015-01-30 11:00:52 -08001029 int status;
Felipe Leme30dbfa12016-09-02 12:43:26 -07001030 bool ret = waitpid_with_timeout(pid, options.Timeout(), &status);
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001031 uint64_t elapsed = DurationReporter::Nanotime() - start;
Christopher Ferris1a9a3382015-01-30 11:00:52 -08001032 if (!ret) {
1033 if (errno == ETIMEDOUT) {
Felipe Leme30dbfa12016-09-02 12:43:26 -07001034 if (!silent)
1035 printf("*** command '%s' timed out after %.3fs (killing pid %d)\n", command,
1036 (float)elapsed / NANOS_PER_SEC, pid);
Felipe Lemefd8affa2016-09-30 17:38:57 -07001037 MYLOGE("*** command '%s' timed out after %.3fs (killing pid %d)\n", command,
Felipe Leme30dbfa12016-09-02 12:43:26 -07001038 (float)elapsed / NANOS_PER_SEC, pid);
Christopher Ferris1a9a3382015-01-30 11:00:52 -08001039 } else {
Felipe Leme30dbfa12016-09-02 12:43:26 -07001040 if (!silent)
1041 printf("*** command '%s': Error after %.4fs (killing pid %d)\n", command,
1042 (float)elapsed / NANOS_PER_SEC, pid);
1043 MYLOGE("command '%s': Error after %.4fs (killing pid %d)\n", command,
1044 (float)elapsed / NANOS_PER_SEC, pid);
Christopher Ferris1a9a3382015-01-30 11:00:52 -08001045 }
1046 kill(pid, SIGTERM);
Felipe Lemefd8affa2016-09-30 17:38:57 -07001047 if (!waitpid_with_timeout(pid, 5, nullptr)) {
Christopher Ferris1a9a3382015-01-30 11:00:52 -08001048 kill(pid, SIGKILL);
Felipe Lemefd8affa2016-09-30 17:38:57 -07001049 if (!waitpid_with_timeout(pid, 5, nullptr)) {
Felipe Leme30dbfa12016-09-02 12:43:26 -07001050 if (!silent)
1051 printf("could not kill command '%s' (pid %d) even with SIGKILL.\n", command,
1052 pid);
Felipe Leme14e034a2016-03-30 18:51:03 -07001053 MYLOGE("could not kill command '%s' (pid %d) even with SIGKILL.\n", command, pid);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001054 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001055 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -08001056 return -1;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001057 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -08001058
1059 if (WIFSIGNALED(status)) {
Felipe Lemefd8affa2016-09-30 17:38:57 -07001060 if (!silent)
1061 printf("*** command '%s' failed: killed by signal %d\n", command, WTERMSIG(status));
1062 MYLOGE("*** command '%s' failed: killed by signal %d\n", command, WTERMSIG(status));
Christopher Ferris1a9a3382015-01-30 11:00:52 -08001063 } else if (WIFEXITED(status) && WEXITSTATUS(status) > 0) {
Felipe Lemefd8affa2016-09-30 17:38:57 -07001064 status = WEXITSTATUS(status);
1065 if (!silent) printf("*** command '%s' failed: exit code %d\n", command, status);
1066 MYLOGE("*** command '%s' failed: exit code %d\n", command, status);
Christopher Ferris1a9a3382015-01-30 11:00:52 -08001067 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -08001068
1069 return status;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001070}
1071
Felipe Leme9a523ae2016-10-20 15:10:33 -07001072void Dumpstate::RunDumpsys(const std::string& title, const std::vector<std::string>& dumpsys_args,
Felipe Leme678727a2016-09-21 17:22:11 -07001073 const CommandOptions& options, long dumpsysTimeout) {
Felipe Leme5bcce572016-09-27 09:21:08 -07001074 long timeout = dumpsysTimeout > 0 ? dumpsysTimeout : options.Timeout();
1075 std::vector<std::string> dumpsys = {"/system/bin/dumpsys", "-t", std::to_string(timeout)};
Felipe Leme9a523ae2016-10-20 15:10:33 -07001076 dumpsys.insert(dumpsys.end(), dumpsys_args.begin(), dumpsys_args.end());
Felipe Leme678727a2016-09-21 17:22:11 -07001077 RunCommand(title, dumpsys, options);
Felipe Leme30dbfa12016-09-02 12:43:26 -07001078}
1079
Felipe Lemecf6a8b42016-03-11 10:38:19 -08001080bool drop_root_user() {
1081 if (getgid() == AID_SHELL && getuid() == AID_SHELL) {
Felipe Leme26c41572016-10-06 14:34:43 -07001082 MYLOGD("drop_root_user(): already running as Shell\n");
Felipe Lemecf6a8b42016-03-11 10:38:19 -08001083 return true;
1084 }
1085 /* ensure we will keep capabilities when we drop root */
1086 if (prctl(PR_SET_KEEPCAPS, 1) < 0) {
1087 MYLOGE("prctl(PR_SET_KEEPCAPS) failed: %s\n", strerror(errno));
1088 return false;
1089 }
1090
1091 gid_t groups[] = { AID_LOG, AID_SDCARD_R, AID_SDCARD_RW,
Ajay Panickerd886ec42016-09-14 12:26:46 -07001092 AID_MOUNT, AID_INET, AID_NET_BW_STATS, AID_READPROC, AID_WAKELOCK,
1093 AID_BLUETOOTH };
Felipe Lemecf6a8b42016-03-11 10:38:19 -08001094 if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) {
1095 MYLOGE("Unable to setgroups, aborting: %s\n", strerror(errno));
1096 return false;
1097 }
1098 if (setgid(AID_SHELL) != 0) {
1099 MYLOGE("Unable to setgid, aborting: %s\n", strerror(errno));
1100 return false;
1101 }
1102 if (setuid(AID_SHELL) != 0) {
1103 MYLOGE("Unable to setuid, aborting: %s\n", strerror(errno));
1104 return false;
1105 }
1106
1107 struct __user_cap_header_struct capheader;
1108 struct __user_cap_data_struct capdata[2];
1109 memset(&capheader, 0, sizeof(capheader));
1110 memset(&capdata, 0, sizeof(capdata));
1111 capheader.version = _LINUX_CAPABILITY_VERSION_3;
1112 capheader.pid = 0;
1113
Wei Liuf87959e2016-08-26 14:51:42 -07001114 capdata[CAP_TO_INDEX(CAP_SYSLOG)].permitted =
1115 (CAP_TO_MASK(CAP_SYSLOG) | CAP_TO_MASK(CAP_BLOCK_SUSPEND));
1116 capdata[CAP_TO_INDEX(CAP_SYSLOG)].effective =
1117 (CAP_TO_MASK(CAP_SYSLOG) | CAP_TO_MASK(CAP_BLOCK_SUSPEND));
Felipe Lemecf6a8b42016-03-11 10:38:19 -08001118 capdata[0].inheritable = 0;
1119 capdata[1].inheritable = 0;
1120
1121 if (capset(&capheader, &capdata[0]) < 0) {
1122 MYLOGE("capset failed: %s\n", strerror(errno));
1123 return false;
1124 }
1125
1126 return true;
1127}
1128
Felipe Leme36b3f6f2015-11-19 15:41:04 -08001129void send_broadcast(const std::string& action, const std::vector<std::string>& args) {
Felipe Leme30dbfa12016-09-02 12:43:26 -07001130 std::vector<std::string> am = {"/system/bin/am", "broadcast", "--user", "0", "-a", action};
1131
1132 am.insert(am.end(), args.begin(), args.end());
1133
Felipe Leme678727a2016-09-21 17:22:11 -07001134 RunCommand("", am, CommandOptions::WithTimeout(20)
1135 .Log("Sending broadcast: '%s'\n")
1136 .Always()
1137 .DropRoot()
1138 .RedirectStderr()
1139 .Build());
Felipe Leme36b3f6f2015-11-19 15:41:04 -08001140}
1141
Colin Crossf45fa6b2012-03-26 12:38:26 -07001142size_t num_props = 0;
1143static char* props[2000];
1144
1145static void print_prop(const char *key, const char *name, void *user) {
1146 (void) user;
1147 if (num_props < sizeof(props) / sizeof(props[0])) {
1148 char buf[PROPERTY_KEY_MAX + PROPERTY_VALUE_MAX + 10];
1149 snprintf(buf, sizeof(buf), "[%s]: [%s]\n", key, name);
1150 props[num_props++] = strdup(buf);
1151 }
1152}
1153
1154static int compare_prop(const void *a, const void *b) {
1155 return strcmp(*(char * const *) a, *(char * const *) b);
1156}
1157
1158/* prints all the system properties */
1159void print_properties() {
Felipe Leme78f2c862015-12-21 09:55:22 -08001160 const char* title = "SYSTEM PROPERTIES";
1161 DurationReporter duration_reporter(title);
1162 printf("------ %s ------\n", title);
Felipe Leme4c2d6632016-09-28 14:32:00 -07001163 if (IsDryRun()) return;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001164 size_t i;
1165 num_props = 0;
1166 property_list(print_prop, NULL);
1167 qsort(&props, num_props, sizeof(props[0]), compare_prop);
1168
Colin Crossf45fa6b2012-03-26 12:38:26 -07001169 for (i = 0; i < num_props; ++i) {
1170 fputs(props[i], stdout);
1171 free(props[i]);
1172 }
1173 printf("\n");
1174}
1175
Felipe Leme2628e9e2016-04-12 16:36:51 -07001176int open_socket(const char *service) {
Colin Crossf45fa6b2012-03-26 12:38:26 -07001177 int s = android_get_control_socket(service);
1178 if (s < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001179 MYLOGE("android_get_control_socket(%s): %s\n", service, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001180 exit(1);
1181 }
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001182 fcntl(s, F_SETFD, FD_CLOEXEC);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001183 if (listen(s, 4) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001184 MYLOGE("listen(control socket): %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001185 exit(1);
1186 }
1187
1188 struct sockaddr addr;
1189 socklen_t alen = sizeof(addr);
1190 int fd = accept(s, &addr, &alen);
1191 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001192 MYLOGE("accept(control socket): %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001193 exit(1);
1194 }
1195
Felipe Leme2628e9e2016-04-12 16:36:51 -07001196 return fd;
1197}
1198
1199/* redirect output to a service control socket */
1200void redirect_to_socket(FILE *redirect, const char *service) {
1201 int fd = open_socket(service);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001202 fflush(redirect);
1203 dup2(fd, fileno(redirect));
1204 close(fd);
1205}
1206
Felipe Leme2628e9e2016-04-12 16:36:51 -07001207// TODO: should call is_valid_output_file and/or be merged into it.
Felipe Leme111b9d02016-02-03 09:28:24 -08001208void create_parent_dirs(const char *path) {
Srinath Sridharanfdf52d32016-02-01 15:50:22 -08001209 char *chp = const_cast<char *> (path);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001210
1211 /* skip initial slash */
1212 if (chp[0] == '/')
1213 chp++;
1214
1215 /* create leading directories, if necessary */
Felipe Leme111b9d02016-02-03 09:28:24 -08001216 struct stat dir_stat;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001217 while (chp && chp[0]) {
1218 chp = strchr(chp, '/');
1219 if (chp) {
1220 *chp = 0;
Felipe Leme111b9d02016-02-03 09:28:24 -08001221 if (stat(path, &dir_stat) == -1 || !S_ISDIR(dir_stat.st_mode)) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001222 MYLOGI("Creating directory %s\n", path);
Felipe Leme111b9d02016-02-03 09:28:24 -08001223 if (mkdir(path, 0770)) { /* drwxrwx--- */
Felipe Lemecbce55d2016-02-08 09:53:18 -08001224 MYLOGE("Unable to create directory %s: %s\n", path, strerror(errno));
Felipe Leme111b9d02016-02-03 09:28:24 -08001225 } else if (chown(path, AID_SHELL, AID_SHELL)) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001226 MYLOGE("Unable to change ownership of dir %s: %s\n", path, strerror(errno));
Felipe Leme111b9d02016-02-03 09:28:24 -08001227 }
1228 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001229 *chp++ = '/';
1230 }
1231 }
Felipe Leme111b9d02016-02-03 09:28:24 -08001232}
1233
Felipe Leme0f3fb202016-06-10 17:10:53 -07001234void _redirect_to_file(FILE *redirect, char *path, int truncate_flag) {
Felipe Leme111b9d02016-02-03 09:28:24 -08001235 create_parent_dirs(path);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001236
Felipe Leme0f3fb202016-06-10 17:10:53 -07001237 int fd = TEMP_FAILURE_RETRY(open(path,
1238 O_WRONLY | O_CREAT | truncate_flag | O_CLOEXEC | O_NOFOLLOW,
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -08001239 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001240 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001241 MYLOGE("%s: %s\n", path, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001242 exit(1);
1243 }
1244
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -08001245 TEMP_FAILURE_RETRY(dup2(fd, fileno(redirect)));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001246 close(fd);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001247}
1248
Felipe Leme0f3fb202016-06-10 17:10:53 -07001249void redirect_to_file(FILE *redirect, char *path) {
1250 _redirect_to_file(redirect, path, O_TRUNC);
1251}
1252
1253void redirect_to_existing_file(FILE *redirect, char *path) {
1254 _redirect_to_file(redirect, path, O_APPEND);
1255}
1256
Jeff Brownbf7f4922012-06-07 16:40:01 -07001257static bool should_dump_native_traces(const char* path) {
1258 for (const char** p = native_processes_to_dump; *p; p++) {
1259 if (!strcmp(*p, path)) {
1260 return true;
1261 }
1262 }
1263 return false;
1264}
1265
1266/* dump Dalvik and native stack traces, return the trace file location (NULL if none) */
1267const char *dump_traces() {
Felipe Lemee184f662016-10-27 10:04:47 -07001268 DurationReporter duration_reporter("DUMP TRACES");
Felipe Lemed402e7d2016-08-03 09:22:27 -07001269
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001270 const char* result = nullptr;
Jeff Brownbf7f4922012-06-07 16:40:01 -07001271
Felipe Lemee184f662016-10-27 10:04:47 -07001272 std::string traces_path = android::base::GetProperty("dalvik.vm.stack-trace-file", "");
1273 if (traces_path.empty()) return nullptr;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001274
1275 /* move the old traces.txt (if any) out of the way temporarily */
Felipe Lemee184f662016-10-27 10:04:47 -07001276 std::string anrtraces_path = traces_path + ".anr";
1277 if (rename(traces_path.c_str(), anrtraces_path.c_str()) && errno != ENOENT) {
1278 MYLOGE("rename(%s, %s): %s\n", traces_path.c_str(), anrtraces_path.c_str(), strerror(errno));
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001279 return nullptr; // Can't rename old traces.txt -- no permission? -- leave it alone instead
Colin Crossf45fa6b2012-03-26 12:38:26 -07001280 }
1281
Colin Crossf45fa6b2012-03-26 12:38:26 -07001282 /* create a new, empty traces.txt file to receive stack dumps */
Felipe Lemee184f662016-10-27 10:04:47 -07001283 int fd = TEMP_FAILURE_RETRY(open(traces_path.c_str(),
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001284 O_CREAT | O_WRONLY | O_TRUNC | O_NOFOLLOW | O_CLOEXEC,
1285 0666)); /* -rw-rw-rw- */
Colin Crossf45fa6b2012-03-26 12:38:26 -07001286 if (fd < 0) {
Felipe Lemee184f662016-10-27 10:04:47 -07001287 MYLOGE("%s: %s\n", traces_path.c_str(), strerror(errno));
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001288 return nullptr;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001289 }
Nick Kralevichc7f1fe22012-04-06 09:31:28 -07001290 int chmod_ret = fchmod(fd, 0666);
1291 if (chmod_ret < 0) {
Felipe Lemee184f662016-10-27 10:04:47 -07001292 MYLOGE("fchmod on %s failed: %s\n", traces_path.c_str(), strerror(errno));
Nick Kralevichc7f1fe22012-04-06 09:31:28 -07001293 close(fd);
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001294 return nullptr;
Nick Kralevichc7f1fe22012-04-06 09:31:28 -07001295 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001296
Felipe Leme8620bb42015-11-10 11:04:45 -08001297 /* Variables below must be initialized before 'goto' statements */
1298 int dalvik_found = 0;
1299 int ifd, wfd = -1;
1300
Colin Crossf45fa6b2012-03-26 12:38:26 -07001301 /* walk /proc and kill -QUIT all Dalvik processes */
1302 DIR *proc = opendir("/proc");
1303 if (proc == NULL) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001304 MYLOGE("/proc: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001305 goto error_close_fd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001306 }
1307
1308 /* use inotify to find when processes are done dumping */
Felipe Leme8620bb42015-11-10 11:04:45 -08001309 ifd = inotify_init();
Colin Crossf45fa6b2012-03-26 12:38:26 -07001310 if (ifd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001311 MYLOGE("inotify_init: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001312 goto error_close_fd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001313 }
1314
Felipe Lemee184f662016-10-27 10:04:47 -07001315 wfd = inotify_add_watch(ifd, traces_path.c_str(), IN_CLOSE_WRITE);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001316 if (wfd < 0) {
Felipe Lemee184f662016-10-27 10:04:47 -07001317 MYLOGE("inotify_add_watch(%s): %s\n", traces_path.c_str(), strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001318 goto error_close_ifd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001319 }
1320
1321 struct dirent *d;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001322 while ((d = readdir(proc))) {
1323 int pid = atoi(d->d_name);
1324 if (pid <= 0) continue;
1325
Jeff Brownbf7f4922012-06-07 16:40:01 -07001326 char path[PATH_MAX];
1327 char data[PATH_MAX];
Colin Crossf45fa6b2012-03-26 12:38:26 -07001328 snprintf(path, sizeof(path), "/proc/%d/exe", pid);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001329 ssize_t len = readlink(path, data, sizeof(data) - 1);
1330 if (len <= 0) {
Colin Crossf45fa6b2012-03-26 12:38:26 -07001331 continue;
1332 }
Jeff Brownbf7f4922012-06-07 16:40:01 -07001333 data[len] = '\0';
Colin Crossf45fa6b2012-03-26 12:38:26 -07001334
Colin Cross0d6180f2014-07-16 19:00:46 -07001335 if (!strncmp(data, "/system/bin/app_process", strlen("/system/bin/app_process"))) {
Jeff Brownbf7f4922012-06-07 16:40:01 -07001336 /* skip zygote -- it won't dump its stack anyway */
1337 snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001338 int cfd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC));
Jeff Brown1dc94e32014-09-11 14:15:27 -07001339 len = read(cfd, data, sizeof(data) - 1);
1340 close(cfd);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001341 if (len <= 0) {
1342 continue;
1343 }
1344 data[len] = '\0';
Colin Cross0d6180f2014-07-16 19:00:46 -07001345 if (!strncmp(data, "zygote", strlen("zygote"))) {
Jeff Brownbf7f4922012-06-07 16:40:01 -07001346 continue;
1347 }
1348
1349 ++dalvik_found;
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001350 uint64_t start = DurationReporter::Nanotime();
Jeff Brownbf7f4922012-06-07 16:40:01 -07001351 if (kill(pid, SIGQUIT)) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001352 MYLOGE("kill(%d, SIGQUIT): %s\n", pid, strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001353 continue;
1354 }
1355
1356 /* wait for the writable-close notification from inotify */
1357 struct pollfd pfd = { ifd, POLLIN, 0 };
Felipe Leme61884122016-06-13 09:23:30 -07001358 int ret = poll(&pfd, 1, TRACE_DUMP_TIMEOUT_MS);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001359 if (ret < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001360 MYLOGE("poll: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001361 } else if (ret == 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001362 MYLOGE("warning: timed out dumping pid %d\n", pid);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001363 } else {
1364 struct inotify_event ie;
1365 read(ifd, &ie, sizeof(ie));
1366 }
Jeff Brown1dc94e32014-09-11 14:15:27 -07001367
1368 if (lseek(fd, 0, SEEK_END) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001369 MYLOGE("lseek: %s\n", strerror(errno));
Jeff Brown1dc94e32014-09-11 14:15:27 -07001370 } else {
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001371 dprintf(fd, "[dump dalvik stack %d: %.3fs elapsed]\n", pid,
1372 (float)(DurationReporter::Nanotime() - start) / NANOS_PER_SEC);
Jeff Brown1dc94e32014-09-11 14:15:27 -07001373 }
Jeff Brownbf7f4922012-06-07 16:40:01 -07001374 } else if (should_dump_native_traces(data)) {
1375 /* dump native process if appropriate */
1376 if (lseek(fd, 0, SEEK_END) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001377 MYLOGE("lseek: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001378 } else {
Christopher Ferris31ef8552015-01-14 13:23:30 -08001379 static uint16_t timeout_failures = 0;
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001380 uint64_t start = DurationReporter::Nanotime();
Christopher Ferris31ef8552015-01-14 13:23:30 -08001381
1382 /* If 3 backtrace dumps fail in a row, consider debuggerd dead. */
1383 if (timeout_failures == 3) {
1384 dprintf(fd, "too many stack dump failures, skipping...\n");
1385 } else if (dump_backtrace_to_file_timeout(pid, fd, 20) == -1) {
1386 dprintf(fd, "dumping failed, likely due to a timeout\n");
1387 timeout_failures++;
1388 } else {
1389 timeout_failures = 0;
1390 }
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001391 dprintf(fd, "[dump native stack %d: %.3fs elapsed]\n", pid,
1392 (float)(DurationReporter::Nanotime() - start) / NANOS_PER_SEC);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001393 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001394 }
1395 }
1396
Colin Crossf45fa6b2012-03-26 12:38:26 -07001397 if (dalvik_found == 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001398 MYLOGE("Warning: no Dalvik processes found to dump stacks\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -07001399 }
1400
Felipe Lemee184f662016-10-27 10:04:47 -07001401 static std::string dumptraces_path = android::base::StringPrintf(
1402 "%s/bugreport-%s", dirname(traces_path.c_str()), basename(traces_path.c_str()));
1403 if (rename(traces_path.c_str(), dumptraces_path.c_str())) {
1404 MYLOGE("rename(%s, %s): %s\n", traces_path.c_str(), dumptraces_path.c_str(),
1405 strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001406 goto error_close_ifd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001407 }
Felipe Lemee184f662016-10-27 10:04:47 -07001408 result = dumptraces_path.c_str();
Colin Crossf45fa6b2012-03-26 12:38:26 -07001409
1410 /* replace the saved [ANR] traces.txt file */
Felipe Lemee184f662016-10-27 10:04:47 -07001411 rename(anrtraces_path.c_str(), traces_path.c_str());
Jeff Brownbf7f4922012-06-07 16:40:01 -07001412
1413error_close_ifd:
1414 close(ifd);
1415error_close_fd:
1416 close(fd);
1417 return result;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001418}
1419
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001420void dump_route_tables() {
Felipe Leme78f2c862015-12-21 09:55:22 -08001421 DurationReporter duration_reporter("DUMP ROUTE TABLES");
Felipe Leme4c2d6632016-09-28 14:32:00 -07001422 if (IsDryRun()) return;
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001423 const char* const RT_TABLES_PATH = "/data/misc/net/rt_tables";
Felipe Lemec7fe8fe2016-09-21 18:13:20 -07001424 ds.DumpFile("RT_TABLES", RT_TABLES_PATH);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001425 FILE* fp = fopen(RT_TABLES_PATH, "re");
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001426 if (!fp) {
1427 printf("*** %s: %s\n", RT_TABLES_PATH, strerror(errno));
1428 return;
1429 }
1430 char table[16];
1431 // Each line has an integer (the table number), a space, and a string (the table name). We only
1432 // need the table number. It's a 32-bit unsigned number, so max 10 chars. Skip the table name.
1433 // Add a fixed max limit so this doesn't go awry.
1434 for (int i = 0; i < 64 && fscanf(fp, " %10s %*s", table) == 1; ++i) {
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001435 RunCommand("ROUTE TABLE IPv4", {"ip", "-4", "route", "show", "table", table});
1436 RunCommand("ROUTE TABLE IPv6", {"ip", "-6", "route", "show", "table", table});
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001437 }
1438 fclose(fp);
1439}
Felipe Leme71bbfc52015-11-23 14:14:51 -08001440
Felipe Leme71bbfc52015-11-23 14:14:51 -08001441// TODO: make this function thread safe if sections are generated in parallel.
Felipe Leme7447d7c2016-11-03 18:12:22 -07001442void Dumpstate::UpdateProgress(int32_t delta) {
1443 if (progress_ == nullptr) {
1444 MYLOGE("UpdateProgress: progress_ not set\n");
1445 return;
1446 }
Felipe Leme71bbfc52015-11-23 14:14:51 -08001447
Felipe Leme7447d7c2016-11-03 18:12:22 -07001448 // Always update progess so stats can be tuned...
1449 bool max_changed = progress_->Inc(delta);
1450
1451 // ...but only notifiy listeners when necessary.
1452 if (!update_progress_) return;
Felipe Leme71bbfc52015-11-23 14:14:51 -08001453
Felipe Leme75876a22016-10-27 16:31:27 -07001454 // TODO: remove property support once Shell uses IDumpstateListener
Felipe Leme71bbfc52015-11-23 14:14:51 -08001455 char key[PROPERTY_KEY_MAX];
1456 char value[PROPERTY_VALUE_MAX];
Felipe Lemead5f6c42015-11-30 14:26:46 -08001457
1458 // adjusts max on the fly
Felipe Leme7447d7c2016-11-03 18:12:22 -07001459 if (max_changed) {
Felipe Leme75876a22016-10-27 16:31:27 -07001460 if (listener_ != nullptr) {
Felipe Leme7447d7c2016-11-03 18:12:22 -07001461 listener_->onMaxProgressUpdated(progress_->GetMax());
Felipe Leme75876a22016-10-27 16:31:27 -07001462 } else {
1463 snprintf(key, sizeof(key), "dumpstate.%d.max", pid_);
Felipe Leme7447d7c2016-11-03 18:12:22 -07001464 snprintf(value, sizeof(value), "%d", progress_->GetMax());
Felipe Leme75876a22016-10-27 16:31:27 -07001465 int status = property_set(key, value);
1466 if (status != 0) {
1467 MYLOGE("Could not update max weight by setting system property %s to %s: %d\n", key,
1468 value, status);
1469 }
Felipe Lemead5f6c42015-11-30 14:26:46 -08001470 }
1471 }
1472
Felipe Leme7447d7c2016-11-03 18:12:22 -07001473 int32_t progress = progress_->Get();
1474 int32_t max = progress_->GetMax();
1475
Felipe Leme9a523ae2016-10-20 15:10:33 -07001476 if (control_socket_fd_ >= 0) {
Felipe Leme7447d7c2016-11-03 18:12:22 -07001477 dprintf(control_socket_fd_, "PROGRESS:%d/%d\n", progress, max);
Felipe Leme9a523ae2016-10-20 15:10:33 -07001478 fsync(control_socket_fd_);
Felipe Leme02b7e002016-07-22 12:03:20 -07001479 }
1480
Felipe Leme75876a22016-10-27 16:31:27 -07001481 if (listener_ != nullptr) {
Felipe Leme7447d7c2016-11-03 18:12:22 -07001482 if (progress % 100 == 0) {
Felipe Leme75876a22016-10-27 16:31:27 -07001483 // We don't want to spam logcat, so only log multiples of 100.
Felipe Leme7447d7c2016-11-03 18:12:22 -07001484 MYLOGD("Setting progress (%s): %d/%d\n", listener_name_.c_str(), progress, max);
Felipe Leme75876a22016-10-27 16:31:27 -07001485 } else {
1486 // stderr is ignored on normal invocations, but useful when calling
1487 // /system/bin/dumpstate directly for debuggging.
Felipe Leme7447d7c2016-11-03 18:12:22 -07001488 fprintf(stderr, "Setting progress (%s): %d/%d\n", listener_name_.c_str(), progress, max);
Felipe Leme75876a22016-10-27 16:31:27 -07001489 }
Felipe Leme7447d7c2016-11-03 18:12:22 -07001490 listener_->onProgressUpdated(progress);
Felipe Leme75876a22016-10-27 16:31:27 -07001491 } else {
1492 snprintf(key, sizeof(key), "dumpstate.%d.progress", pid_);
Felipe Leme7447d7c2016-11-03 18:12:22 -07001493 snprintf(value, sizeof(value), "%d", progress);
Felipe Leme75876a22016-10-27 16:31:27 -07001494
Felipe Leme7447d7c2016-11-03 18:12:22 -07001495 if (progress % 100 == 0) {
Felipe Leme75876a22016-10-27 16:31:27 -07001496 // We don't want to spam logcat, so only log multiples of 100.
Felipe Leme7447d7c2016-11-03 18:12:22 -07001497 MYLOGD("Setting progress (%s): %s/%d\n", key, value, max);
Felipe Leme75876a22016-10-27 16:31:27 -07001498 } else {
1499 // stderr is ignored on normal invocations, but useful when calling
1500 // /system/bin/dumpstate directly for debuggging.
Felipe Leme7447d7c2016-11-03 18:12:22 -07001501 fprintf(stderr, "Setting progress (%s): %s/%d\n", key, value, max);
Felipe Leme75876a22016-10-27 16:31:27 -07001502 }
1503
1504 int status = property_set(key, value);
1505 if (status) {
1506 MYLOGE("Could not update progress by setting system property %s to %s: %d\n", key,
1507 value, status);
1508 }
Felipe Leme71bbfc52015-11-23 14:14:51 -08001509 }
1510}
Felipe Lemee338bf62015-12-07 14:03:50 -08001511
Felipe Lemebbaf3c12016-10-11 14:32:25 -07001512void Dumpstate::TakeScreenshot(const std::string& path) {
Felipe Leme9a523ae2016-10-20 15:10:33 -07001513 const std::string& real_path = path.empty() ? screenshot_path_ : path;
Felipe Lemebbaf3c12016-10-11 14:32:25 -07001514 int status =
Felipe Leme9a523ae2016-10-20 15:10:33 -07001515 RunCommand("", {"/system/bin/screencap", "-p", real_path},
Felipe Lemebbaf3c12016-10-11 14:32:25 -07001516 CommandOptions::WithTimeout(10).Always().DropRoot().RedirectStderr().Build());
1517 if (status == 0) {
Felipe Leme9a523ae2016-10-20 15:10:33 -07001518 MYLOGD("Screenshot saved on %s\n", real_path.c_str());
Felipe Lemebbaf3c12016-10-11 14:32:25 -07001519 } else {
Felipe Leme9a523ae2016-10-20 15:10:33 -07001520 MYLOGE("Failed to take screenshot on %s\n", real_path.c_str());
Felipe Lemebbaf3c12016-10-11 14:32:25 -07001521 }
Felipe Lemee338bf62015-12-07 14:03:50 -08001522}
Mark Salyzynf55d4022015-12-11 07:32:31 -08001523
Felipe Leme0c80cf02016-01-05 13:25:34 -08001524void vibrate(FILE* vibrator, int ms) {
1525 fprintf(vibrator, "%d\n", ms);
1526 fflush(vibrator);
1527}
1528
1529bool is_dir(const char* pathname) {
1530 struct stat info;
1531 if (stat(pathname, &info) == -1) {
1532 return false;
1533 }
1534 return S_ISDIR(info.st_mode);
1535}
1536
1537time_t get_mtime(int fd, time_t default_mtime) {
1538 struct stat info;
1539 if (fstat(fd, &info) == -1) {
1540 return default_mtime;
1541 }
1542 return info.st_mtime;
1543}
1544
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001545void dump_emmc_ecsd(const char *ext_csd_path) {
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001546 // List of interesting offsets
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001547 struct hex {
1548 char str[2];
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001549 };
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001550 static const size_t EXT_CSD_REV = 192 * sizeof(hex);
1551 static const size_t EXT_PRE_EOL_INFO = 267 * sizeof(hex);
1552 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_A = 268 * sizeof(hex);
1553 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_B = 269 * sizeof(hex);
1554
1555 std::string buffer;
1556 if (!android::base::ReadFileToString(ext_csd_path, &buffer)) {
1557 return;
1558 }
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001559
1560 printf("------ %s Extended CSD ------\n", ext_csd_path);
1561
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001562 if (buffer.length() < (EXT_CSD_REV + sizeof(hex))) {
1563 printf("*** %s: truncated content %zu\n\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001564 return;
1565 }
1566
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001567 int ext_csd_rev = 0;
1568 std::string sub = buffer.substr(EXT_CSD_REV, sizeof(hex));
1569 if (sscanf(sub.c_str(), "%2x", &ext_csd_rev) != 1) {
1570 printf("*** %s: EXT_CSD_REV parse error \"%s\"\n\n",
1571 ext_csd_path, sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001572 return;
1573 }
1574
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001575 static const char *ver_str[] = {
1576 "4.0", "4.1", "4.2", "4.3", "Obsolete", "4.41", "4.5", "5.0"
1577 };
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001578 printf("rev 1.%d (MMC %s)\n",
1579 ext_csd_rev,
1580 (ext_csd_rev < (int)(sizeof(ver_str) / sizeof(ver_str[0]))) ?
1581 ver_str[ext_csd_rev] :
1582 "Unknown");
1583 if (ext_csd_rev < 7) {
1584 printf("\n");
1585 return;
1586 }
1587
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001588 if (buffer.length() < (EXT_PRE_EOL_INFO + sizeof(hex))) {
1589 printf("*** %s: truncated content %zu\n\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001590 return;
1591 }
1592
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001593 int ext_pre_eol_info = 0;
1594 sub = buffer.substr(EXT_PRE_EOL_INFO, sizeof(hex));
1595 if (sscanf(sub.c_str(), "%2x", &ext_pre_eol_info) != 1) {
1596 printf("*** %s: PRE_EOL_INFO parse error \"%s\"\n\n",
1597 ext_csd_path, sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001598 return;
1599 }
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001600
1601 static const char *eol_str[] = {
1602 "Undefined",
1603 "Normal",
1604 "Warning (consumed 80% of reserve)",
1605 "Urgent (consumed 90% of reserve)"
1606 };
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001607 printf("PRE_EOL_INFO %d (MMC %s)\n",
1608 ext_pre_eol_info,
1609 eol_str[(ext_pre_eol_info < (int)
1610 (sizeof(eol_str) / sizeof(eol_str[0]))) ?
1611 ext_pre_eol_info : 0]);
1612
1613 for (size_t lifetime = EXT_DEVICE_LIFE_TIME_EST_TYP_A;
1614 lifetime <= EXT_DEVICE_LIFE_TIME_EST_TYP_B;
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001615 lifetime += sizeof(hex)) {
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001616 int ext_device_life_time_est;
1617 static const char *est_str[] = {
1618 "Undefined",
1619 "0-10% of device lifetime used",
1620 "10-20% of device lifetime used",
1621 "20-30% of device lifetime used",
1622 "30-40% of device lifetime used",
1623 "40-50% of device lifetime used",
1624 "50-60% of device lifetime used",
1625 "60-70% of device lifetime used",
1626 "70-80% of device lifetime used",
1627 "80-90% of device lifetime used",
1628 "90-100% of device lifetime used",
1629 "Exceeded the maximum estimated device lifetime",
1630 };
1631
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001632 if (buffer.length() < (lifetime + sizeof(hex))) {
1633 printf("*** %s: truncated content %zu\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001634 break;
1635 }
1636
1637 ext_device_life_time_est = 0;
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001638 sub = buffer.substr(lifetime, sizeof(hex));
1639 if (sscanf(sub.c_str(), "%2x", &ext_device_life_time_est) != 1) {
1640 printf("*** %s: DEVICE_LIFE_TIME_EST_TYP_%c parse error \"%s\"\n",
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001641 ext_csd_path,
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001642 (unsigned)((lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) /
1643 sizeof(hex)) + 'A',
1644 sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001645 continue;
1646 }
1647 printf("DEVICE_LIFE_TIME_EST_TYP_%c %d (MMC %s)\n",
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001648 (unsigned)((lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) /
1649 sizeof(hex)) + 'A',
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001650 ext_device_life_time_est,
1651 est_str[(ext_device_life_time_est < (int)
1652 (sizeof(est_str) / sizeof(est_str[0]))) ?
1653 ext_device_life_time_est : 0]);
1654 }
1655
1656 printf("\n");
1657}