blob: 8b9298820d70acf2902cd2e880d3dc9aefc347cf [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
Felipe Lemef0292972016-11-22 13:57:05 -080017#define LOG_TAG "dumpstate"
18
19#include "dumpstate.h"
20
Colin Crossf45fa6b2012-03-26 12:38:26 -070021#include <dirent.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070022#include <fcntl.h>
Felipe Lemee184f662016-10-27 10:04:47 -070023#include <libgen.h>
Felipe Leme7447d7c2016-11-03 18:12:22 -070024#include <math.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070025#include <poll.h>
26#include <signal.h>
27#include <stdarg.h>
28#include <stdio.h>
29#include <stdlib.h>
30#include <string.h>
Felipe Lemecf6a8b42016-03-11 10:38:19 -080031#include <sys/capability.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070032#include <sys/inotify.h>
Felipe Lemee184f662016-10-27 10:04:47 -070033#include <sys/klog.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070034#include <sys/prctl.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070035#include <sys/stat.h>
36#include <sys/time.h>
37#include <sys/wait.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070038#include <time.h>
39#include <unistd.h>
Mark Salyzyn261a7332016-05-24 12:38:40 -070040
Narayan Kamath8f788292017-05-25 13:20:39 +010041#include <memory>
Steven Moreland17b29e12017-03-21 18:38:05 -070042#include <set>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070043#include <string>
Felipe Leme36b3f6f2015-11-19 15:41:04 -080044#include <vector>
Colin Crossf45fa6b2012-03-26 12:38:26 -070045
Mark Salyzyn290f4b92016-05-16 08:33:59 -070046#include <android-base/file.h>
Felipe Leme96c2bbb2016-09-26 09:21:21 -070047#include <android-base/properties.h>
Felipe Leme2b9b06c2016-10-14 09:13:06 -070048#include <android-base/stringprintf.h>
Felipe Leme7447d7c2016-11-03 18:12:22 -070049#include <android-base/strings.h>
Narayan Kamath8f788292017-05-25 13:20:39 +010050#include <android-base/unique_fd.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070051#include <cutils/properties.h>
52#include <cutils/sockets.h>
Mark Salyzyn4eb13822017-01-12 13:57:51 -080053#include <log/log.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070054#include <private/android_filesystem_config.h>
55
Felipe Lemef0292972016-11-22 13:57:05 -080056#include "DumpstateInternal.h"
Jeff Brown1dc94e32014-09-11 14:15:27 -070057
Felipe Leme47e9be22016-12-21 15:37:07 -080058// TODO: remove once moved to namespace
59using android::os::dumpstate::CommandOptions;
60using android::os::dumpstate::DumpFileToFd;
61using android::os::dumpstate::PropertiesHelper;
62
Brian Carlstroma3322752017-03-19 17:48:01 -070063// Keep in sync with
64// frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
Felipe Leme61884122016-06-13 09:23:30 -070065static const int TRACE_DUMP_TIMEOUT_MS = 10000; // 10 seconds
66
Felipe Lemef0292972016-11-22 13:57:05 -080067/* Most simple commands have 10 as timeout, so 5 is a good estimate */
68static const int32_t WEIGHT_FILE = 5;
69
Felipe Lemee844a9d2016-09-21 15:01:39 -070070// TODO: temporary variables and functions used during C++ refactoring
71static Dumpstate& ds = Dumpstate::GetInstance();
Felipe Leme9a523ae2016-10-20 15:10:33 -070072static int RunCommand(const std::string& title, const std::vector<std::string>& full_command,
Felipe Leme678727a2016-09-21 17:22:11 -070073 const CommandOptions& options = CommandOptions::DEFAULT) {
Felipe Leme9a523ae2016-10-20 15:10:33 -070074 return ds.RunCommand(title, full_command, options);
Felipe Leme678727a2016-09-21 17:22:11 -070075}
Felipe Lemee844a9d2016-09-21 15:01:39 -070076
Felipe Leme7447d7c2016-11-03 18:12:22 -070077// Reasonable value for max stats.
78static const int STATS_MAX_N_RUNS = 1000;
79static const long STATS_MAX_AVERAGE = 100000;
80
Felipe Lemebda15a02016-11-16 17:48:25 -080081CommandOptions Dumpstate::DEFAULT_DUMPSYS = CommandOptions::WithTimeout(30).Build();
Felipe Leme30dbfa12016-09-02 12:43:26 -070082
Nandana Dutt197661d2018-11-16 16:40:21 +000083// TODO(111441001): Default DumpOptions to sensible values.
Felipe Lemef0292972016-11-22 13:57:05 -080084Dumpstate::Dumpstate(const std::string& version)
Nandana Dutt197661d2018-11-16 16:40:21 +000085 : pid_(getpid()),
86 options_(new Dumpstate::DumpOptions()),
87 version_(version),
88 now_(time(nullptr)) {
Felipe Lemee844a9d2016-09-21 15:01:39 -070089}
90
91Dumpstate& Dumpstate::GetInstance() {
Felipe Lemef0292972016-11-22 13:57:05 -080092 static Dumpstate singleton_(android::base::GetProperty("dumpstate.version", VERSION_CURRENT));
Felipe Leme9a523ae2016-10-20 15:10:33 -070093 return singleton_;
Felipe Lemee844a9d2016-09-21 15:01:39 -070094}
95
Nandana Dutta8470b82019-03-11 11:00:58 +000096DurationReporter::DurationReporter(const std::string& title, bool logcat_only)
97 : title_(title), logcat_only_(logcat_only) {
Felipe Leme678727a2016-09-21 17:22:11 -070098 if (!title_.empty()) {
Felipe Lemef0292972016-11-22 13:57:05 -080099 started_ = Nanotime();
Felipe Leme78f2c862015-12-21 09:55:22 -0800100 }
101}
102
103DurationReporter::~DurationReporter() {
Felipe Leme678727a2016-09-21 17:22:11 -0700104 if (!title_.empty()) {
Felipe Lemef0292972016-11-22 13:57:05 -0800105 uint64_t elapsed = Nanotime() - started_;
Nandana Dutta8470b82019-03-11 11:00:58 +0000106 MYLOGD("Duration of '%s': %.3fs\n", title_.c_str(), (float)elapsed / NANOS_PER_SEC);
107 if (logcat_only_) {
108 return;
Felipe Leme608385d2016-02-01 10:35:38 -0800109 }
Nandana Dutta8470b82019-03-11 11:00:58 +0000110 // Use "Yoda grammar" to make it easier to grep|sort sections.
111 printf("------ %.3fs was the duration of '%s' ------\n", (float)elapsed / NANOS_PER_SEC,
112 title_.c_str());
Felipe Leme78f2c862015-12-21 09:55:22 -0800113 }
114}
115
Felipe Leme7447d7c2016-11-03 18:12:22 -0700116const int32_t Progress::kDefaultMax = 5000;
117
118Progress::Progress(const std::string& path) : Progress(Progress::kDefaultMax, 1.1, path) {
119}
120
121Progress::Progress(int32_t initial_max, int32_t progress, float growth_factor)
122 : Progress(initial_max, growth_factor, "") {
123 progress_ = progress;
124}
125
126Progress::Progress(int32_t initial_max, float growth_factor, const std::string& path)
127 : initial_max_(initial_max),
128 progress_(0),
129 max_(initial_max),
130 growth_factor_(growth_factor),
131 n_runs_(0),
132 average_max_(0),
133 path_(path) {
134 if (!path_.empty()) {
135 Load();
136 }
137}
138
139void Progress::Load() {
140 MYLOGD("Loading stats from %s\n", path_.c_str());
141 std::string content;
142 if (!android::base::ReadFileToString(path_, &content)) {
143 MYLOGI("Could not read stats from %s; using max of %d\n", path_.c_str(), max_);
144 return;
145 }
146 if (content.empty()) {
147 MYLOGE("No stats (empty file) on %s; using max of %d\n", path_.c_str(), max_);
148 return;
149 }
150 std::vector<std::string> lines = android::base::Split(content, "\n");
151
152 if (lines.size() < 1) {
153 MYLOGE("Invalid stats on file %s: not enough lines (%d). Using max of %d\n", path_.c_str(),
154 (int)lines.size(), max_);
155 return;
156 }
157 char* ptr;
158 n_runs_ = strtol(lines[0].c_str(), &ptr, 10);
159 average_max_ = strtol(ptr, nullptr, 10);
160 if (n_runs_ <= 0 || average_max_ <= 0 || n_runs_ > STATS_MAX_N_RUNS ||
161 average_max_ > STATS_MAX_AVERAGE) {
162 MYLOGE("Invalid stats line on file %s: %s\n", path_.c_str(), lines[0].c_str());
163 initial_max_ = Progress::kDefaultMax;
164 } else {
165 initial_max_ = average_max_;
166 }
167 max_ = initial_max_;
168
169 MYLOGI("Average max progress: %d in %d runs; estimated max: %d\n", average_max_, n_runs_, max_);
170}
171
172void Progress::Save() {
173 int32_t total = n_runs_ * average_max_ + progress_;
174 int32_t runs = n_runs_ + 1;
175 int32_t average = floor(((float)total) / runs);
176 MYLOGI("Saving stats (total=%d, runs=%d, average=%d) on %s\n", total, runs, average,
177 path_.c_str());
178 if (path_.empty()) {
179 return;
180 }
181
182 std::string content = android::base::StringPrintf("%d %d\n", runs, average);
183 if (!android::base::WriteStringToFile(content, path_)) {
184 MYLOGE("Could not save stats on %s\n", path_.c_str());
185 }
186}
187
188int32_t Progress::Get() const {
189 return progress_;
190}
191
Vishnu Nair6921f802017-11-22 09:17:23 -0800192bool Progress::Inc(int32_t delta_sec) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700193 bool changed = false;
Vishnu Nair6921f802017-11-22 09:17:23 -0800194 if (delta_sec >= 0) {
195 progress_ += delta_sec;
Felipe Leme7447d7c2016-11-03 18:12:22 -0700196 if (progress_ > max_) {
197 int32_t old_max = max_;
198 max_ = floor((float)progress_ * growth_factor_);
199 MYLOGD("Adjusting max progress from %d to %d\n", old_max, max_);
200 changed = true;
201 }
202 }
203 return changed;
204}
205
206int32_t Progress::GetMax() const {
207 return max_;
208}
209
210int32_t Progress::GetInitialMax() const {
211 return initial_max_;
212}
213
214void Progress::Dump(int fd, const std::string& prefix) const {
215 const char* pr = prefix.c_str();
216 dprintf(fd, "%sprogress: %d\n", pr, progress_);
217 dprintf(fd, "%smax: %d\n", pr, max_);
218 dprintf(fd, "%sinitial_max: %d\n", pr, initial_max_);
219 dprintf(fd, "%sgrowth_factor: %0.2f\n", pr, growth_factor_);
220 dprintf(fd, "%spath: %s\n", pr, path_.c_str());
221 dprintf(fd, "%sn_runs: %d\n", pr, n_runs_);
222 dprintf(fd, "%saverage_max: %d\n", pr, average_max_);
223}
224
Felipe Leme75876a22016-10-27 16:31:27 -0700225bool Dumpstate::IsZipping() const {
226 return zip_writer_ != nullptr;
227}
228
Felipe Leme2b9b06c2016-10-14 09:13:06 -0700229std::string Dumpstate::GetPath(const std::string& suffix) const {
Nandana Dutt979388e2018-11-30 16:48:55 +0000230 return GetPath(bugreport_internal_dir_, suffix);
231}
232
233std::string Dumpstate::GetPath(const std::string& directory, const std::string& suffix) const {
234 return android::base::StringPrintf("%s/%s-%s%s", directory.c_str(), base_name_.c_str(),
Felipe Leme2b9b06c2016-10-14 09:13:06 -0700235 name_.c_str(), suffix.c_str());
Felipe Lemebbaf3c12016-10-11 14:32:25 -0700236}
237
Felipe Leme7447d7c2016-11-03 18:12:22 -0700238void Dumpstate::SetProgress(std::unique_ptr<Progress> progress) {
239 progress_ = std::move(progress);
240}
241
John Spurlock5ecd4be2014-01-29 14:14:40 -0500242void for_each_userid(void (*func)(int), const char *header) {
Felipe Leme8f00ed02016-12-07 17:42:44 -0800243 std::string title = header == nullptr ? "for_each_userid" : android::base::StringPrintf(
244 "for_each_userid(%s)", header);
245 DurationReporter duration_reporter(title);
Felipe Lemef0292972016-11-22 13:57:05 -0800246 if (PropertiesHelper::IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700247
John Spurlock5ecd4be2014-01-29 14:14:40 -0500248 DIR *d;
249 struct dirent *de;
250
Felipe Lemed8b94e52016-12-08 10:21:44 -0800251 if (header) printf("\n------ %s ------\n", header);
John Spurlock5ecd4be2014-01-29 14:14:40 -0500252 func(0);
253
254 if (!(d = opendir("/data/system/users"))) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800255 printf("Failed to open /data/system/users (%s)\n", strerror(errno));
John Spurlock5ecd4be2014-01-29 14:14:40 -0500256 return;
257 }
258
259 while ((de = readdir(d))) {
260 int userid;
261 if (de->d_type != DT_DIR || !(userid = atoi(de->d_name))) {
262 continue;
263 }
264 func(userid);
265 }
266
267 closedir(d);
268}
269
Colin Cross0c22e8b2012-11-02 15:46:56 -0700270static void __for_each_pid(void (*helper)(int, const char *, void *), const char *header, void *arg) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700271 DIR *d;
272 struct dirent *de;
273
274 if (!(d = opendir("/proc"))) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800275 printf("Failed to open /proc (%s)\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700276 return;
277 }
278
Felipe Lemed8b94e52016-12-08 10:21:44 -0800279 if (header) printf("\n------ %s ------\n", header);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700280 while ((de = readdir(d))) {
281 int pid;
282 int fd;
283 char cmdpath[255];
284 char cmdline[255];
285
286 if (!(pid = atoi(de->d_name))) {
287 continue;
288 }
289
Colin Crossf45fa6b2012-03-26 12:38:26 -0700290 memset(cmdline, 0, sizeof(cmdline));
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800291
292 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/cmdline", pid);
293 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
294 TEMP_FAILURE_RETRY(read(fd, cmdline, sizeof(cmdline) - 2));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700295 close(fd);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800296 if (cmdline[0]) {
297 helper(pid, cmdline, arg);
298 continue;
299 }
300 }
301
302 // if no cmdline, a kernel thread has comm
303 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/comm", pid);
304 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
305 TEMP_FAILURE_RETRY(read(fd, cmdline + 1, sizeof(cmdline) - 4));
306 close(fd);
307 if (cmdline[1]) {
308 cmdline[0] = '[';
309 size_t len = strcspn(cmdline, "\f\b\r\n");
310 cmdline[len] = ']';
311 cmdline[len+1] = '\0';
312 }
313 }
314 if (!cmdline[0]) {
315 strcpy(cmdline, "N/A");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700316 }
Colin Cross0c22e8b2012-11-02 15:46:56 -0700317 helper(pid, cmdline, arg);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700318 }
319
320 closedir(d);
321}
322
Colin Cross0c22e8b2012-11-02 15:46:56 -0700323static void for_each_pid_helper(int pid, const char *cmdline, void *arg) {
Felipe Leme8620bb42015-11-10 11:04:45 -0800324 for_each_pid_func *func = (for_each_pid_func*) arg;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700325 func(pid, cmdline);
326}
327
328void for_each_pid(for_each_pid_func func, const char *header) {
Felipe Leme8f00ed02016-12-07 17:42:44 -0800329 std::string title = header == nullptr ? "for_each_pid"
330 : android::base::StringPrintf("for_each_pid(%s)", header);
331 DurationReporter duration_reporter(title);
Felipe Lemef0292972016-11-22 13:57:05 -0800332 if (PropertiesHelper::IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700333
Felipe Leme515eb0d2015-12-14 15:09:56 -0800334 __for_each_pid(for_each_pid_helper, header, (void *) func);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700335}
336
337static void for_each_tid_helper(int pid, const char *cmdline, void *arg) {
338 DIR *d;
339 struct dirent *de;
340 char taskpath[255];
Felipe Leme8620bb42015-11-10 11:04:45 -0800341 for_each_tid_func *func = (for_each_tid_func *) arg;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700342
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700343 snprintf(taskpath, sizeof(taskpath), "/proc/%d/task", pid);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700344
345 if (!(d = opendir(taskpath))) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800346 printf("Failed to open %s (%s)\n", taskpath, strerror(errno));
Colin Cross0c22e8b2012-11-02 15:46:56 -0700347 return;
348 }
349
350 func(pid, pid, cmdline);
351
352 while ((de = readdir(d))) {
353 int tid;
354 int fd;
355 char commpath[255];
356 char comm[255];
357
358 if (!(tid = atoi(de->d_name))) {
359 continue;
360 }
361
362 if (tid == pid)
363 continue;
364
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700365 snprintf(commpath, sizeof(commpath), "/proc/%d/comm", tid);
Colin Cross1493a392012-11-07 11:25:31 -0800366 memset(comm, 0, sizeof(comm));
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700367 if ((fd = TEMP_FAILURE_RETRY(open(commpath, O_RDONLY | O_CLOEXEC))) < 0) {
Colin Cross0c22e8b2012-11-02 15:46:56 -0700368 strcpy(comm, "N/A");
369 } else {
370 char *c;
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800371 TEMP_FAILURE_RETRY(read(fd, comm, sizeof(comm) - 2));
Colin Cross0c22e8b2012-11-02 15:46:56 -0700372 close(fd);
373
374 c = strrchr(comm, '\n');
375 if (c) {
376 *c = '\0';
377 }
378 }
379 func(pid, tid, comm);
380 }
381
382 closedir(d);
383}
384
385void for_each_tid(for_each_tid_func func, const char *header) {
Felipe Leme8f00ed02016-12-07 17:42:44 -0800386 std::string title = header == nullptr ? "for_each_tid"
387 : android::base::StringPrintf("for_each_tid(%s)", header);
388 DurationReporter duration_reporter(title);
Felipe Lemed8b94e52016-12-08 10:21:44 -0800389
Felipe Lemef0292972016-11-22 13:57:05 -0800390 if (PropertiesHelper::IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700391
Felipe Leme8620bb42015-11-10 11:04:45 -0800392 __for_each_pid(for_each_tid_helper, header, (void *) func);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700393}
394
395void show_wchan(int pid, int tid, const char *name) {
Felipe Lemef0292972016-11-22 13:57:05 -0800396 if (PropertiesHelper::IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700397
Colin Crossf45fa6b2012-03-26 12:38:26 -0700398 char path[255];
399 char buffer[255];
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800400 int fd, ret, save_errno;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700401 char name_buffer[255];
Colin Crossf45fa6b2012-03-26 12:38:26 -0700402
403 memset(buffer, 0, sizeof(buffer));
404
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700405 snprintf(path, sizeof(path), "/proc/%d/wchan", tid);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700406 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800407 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700408 return;
409 }
410
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800411 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
412 save_errno = errno;
413 close(fd);
414
415 if (ret < 0) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800416 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800417 return;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700418 }
419
Colin Cross0c22e8b2012-11-02 15:46:56 -0700420 snprintf(name_buffer, sizeof(name_buffer), "%*s%s",
421 pid == tid ? 0 : 3, "", name);
422
Felipe Lemed8b94e52016-12-08 10:21:44 -0800423 printf("%-7d %-32s %s\n", tid, name_buffer, buffer);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700424
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800425 return;
426}
427
428// print time in centiseconds
429static void snprcent(char *buffer, size_t len, size_t spc,
430 unsigned long long time) {
431 static long hz; // cache discovered hz
432
433 if (hz <= 0) {
434 hz = sysconf(_SC_CLK_TCK);
435 if (hz <= 0) {
436 hz = 1000;
437 }
438 }
439
440 // convert to centiseconds
441 time = (time * 100 + (hz / 2)) / hz;
442
443 char str[16];
444
445 snprintf(str, sizeof(str), " %llu.%02u",
446 time / 100, (unsigned)(time % 100));
447 size_t offset = strlen(buffer);
448 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
449 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
450}
451
452// print permille as a percent
453static void snprdec(char *buffer, size_t len, size_t spc, unsigned permille) {
454 char str[16];
455
456 snprintf(str, sizeof(str), " %u.%u%%", permille / 10, permille % 10);
457 size_t offset = strlen(buffer);
458 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
459 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
460}
461
462void show_showtime(int pid, const char *name) {
Felipe Lemef0292972016-11-22 13:57:05 -0800463 if (PropertiesHelper::IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700464
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800465 char path[255];
466 char buffer[1023];
467 int fd, ret, save_errno;
468
469 memset(buffer, 0, sizeof(buffer));
470
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700471 snprintf(path, sizeof(path), "/proc/%d/stat", pid);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800472 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800473 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800474 return;
475 }
476
477 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
478 save_errno = errno;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700479 close(fd);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800480
481 if (ret < 0) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800482 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800483 return;
484 }
485
486 // field 14 is utime
487 // field 15 is stime
488 // field 42 is iotime
489 unsigned long long utime = 0, stime = 0, iotime = 0;
490 if (sscanf(buffer,
Mark Salyzyn791ddd32016-02-10 07:41:12 -0800491 "%*u %*s %*s %*d %*d %*d %*d %*d %*d %*d %*d "
492 "%*d %*d %llu %llu %*d %*d %*d %*d %*d %*d "
493 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %*d "
494 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %llu ",
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800495 &utime, &stime, &iotime) != 3) {
496 return;
497 }
498
499 unsigned long long total = utime + stime;
500 if (!total) {
501 return;
502 }
503
504 unsigned permille = (iotime * 1000 + (total / 2)) / total;
505 if (permille > 1000) {
506 permille = 1000;
507 }
508
509 // try to beautify and stabilize columns at <80 characters
510 snprintf(buffer, sizeof(buffer), "%-6d%s", pid, name);
511 if ((name[0] != '[') || utime) {
512 snprcent(buffer, sizeof(buffer), 57, utime);
513 }
514 snprcent(buffer, sizeof(buffer), 65, stime);
515 if ((name[0] != '[') || iotime) {
516 snprcent(buffer, sizeof(buffer), 73, iotime);
517 }
518 if (iotime) {
519 snprdec(buffer, sizeof(buffer), 79, permille);
520 }
Felipe Lemed8b94e52016-12-08 10:21:44 -0800521 puts(buffer); // adds a trailing newline
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800522
Colin Crossf45fa6b2012-03-26 12:38:26 -0700523 return;
524}
525
526void do_dmesg() {
Felipe Leme78f2c862015-12-21 09:55:22 -0800527 const char *title = "KERNEL LOG (dmesg)";
528 DurationReporter duration_reporter(title);
Felipe Lemed8b94e52016-12-08 10:21:44 -0800529 printf("------ %s ------\n", title);
Felipe Leme78f2c862015-12-21 09:55:22 -0800530
Felipe Lemef0292972016-11-22 13:57:05 -0800531 if (PropertiesHelper::IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700532
Elliott Hughes5f87b312012-09-17 11:43:40 -0700533 /* Get size of kernel buffer */
Yi Kong19d5c002018-07-20 13:39:55 -0700534 int size = klogctl(KLOG_SIZE_BUFFER, nullptr, 0);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700535 if (size <= 0) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800536 printf("Unexpected klogctl return value: %d\n\n", size);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700537 return;
538 }
539 char *buf = (char *) malloc(size + 1);
Yi Kong19d5c002018-07-20 13:39:55 -0700540 if (buf == nullptr) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800541 printf("memory allocation failed\n\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700542 return;
543 }
544 int retval = klogctl(KLOG_READ_ALL, buf, size);
545 if (retval < 0) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800546 printf("klogctl failure\n\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700547 free(buf);
548 return;
549 }
550 buf[retval] = '\0';
Felipe Lemed8b94e52016-12-08 10:21:44 -0800551 printf("%s\n\n", buf);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700552 free(buf);
553 return;
554}
555
556void do_showmap(int pid, const char *name) {
557 char title[255];
558 char arg[255];
559
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700560 snprintf(title, sizeof(title), "SHOW MAP %d (%s)", pid, name);
561 snprintf(arg, sizeof(arg), "%d", pid);
Felipe Lemef0292972016-11-22 13:57:05 -0800562 RunCommand(title, {"showmap", "-q", arg}, CommandOptions::AS_ROOT);
Felipe Lemebda15a02016-11-16 17:48:25 -0800563}
564
Felipe Leme678727a2016-09-21 17:22:11 -0700565int Dumpstate::DumpFile(const std::string& title, const std::string& path) {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700566 DurationReporter duration_reporter(title);
Felipe Leme46b85da2016-11-21 17:40:45 -0800567
Felipe Lemef0292972016-11-22 13:57:05 -0800568 int status = DumpFileToFd(STDOUT_FILENO, title, path);
Felipe Leme46b85da2016-11-21 17:40:45 -0800569
Felipe Lemef0292972016-11-22 13:57:05 -0800570 UpdateProgress(WEIGHT_FILE);
Felipe Leme46b85da2016-11-21 17:40:45 -0800571
Felipe Leme46b85da2016-11-21 17:40:45 -0800572 return status;
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800573}
574
Felipe Leme71a74ac2016-03-17 15:43:25 -0700575int read_file_as_long(const char *path, long int *output) {
576 int fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
577 if (fd < 0) {
578 int err = errno;
579 MYLOGE("Error opening file descriptor for %s: %s\n", path, strerror(err));
580 return -1;
581 }
582 char buffer[50];
583 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
584 if (bytes_read == -1) {
585 MYLOGE("Error reading file %s: %s\n", path, strerror(errno));
586 return -2;
587 }
588 if (bytes_read == 0) {
589 MYLOGE("File %s is empty\n", path);
590 return -3;
591 }
592 *output = atoi(buffer);
593 return 0;
594}
595
Mark Salyzyn326842f2015-04-30 09:49:41 -0700596/* calls skip to gate calling dump_from_fd recursively
597 * in the specified directory. dump_from_fd defaults to
598 * dump_file_from_fd above when set to NULL. skip defaults
599 * to false when set to NULL. dump_from_fd will always be
600 * called with title NULL.
601 */
Felipe Leme678727a2016-09-21 17:22:11 -0700602int dump_files(const std::string& title, const char* dir, bool (*skip)(const char* path),
603 int (*dump_from_fd)(const char* title, const char* path, int fd)) {
Felipe Leme78f2c862015-12-21 09:55:22 -0800604 DurationReporter duration_reporter(title);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700605 DIR *dirp;
606 struct dirent *d;
Yi Kong19d5c002018-07-20 13:39:55 -0700607 char *newpath = nullptr;
Felipe Leme8620bb42015-11-10 11:04:45 -0800608 const char *slash = "/";
Narayan Kamath6b9516c2017-10-27 11:15:51 +0100609 int retval = 0;
Mark Salyzyn326842f2015-04-30 09:49:41 -0700610
Felipe Leme678727a2016-09-21 17:22:11 -0700611 if (!title.empty()) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800612 printf("------ %s (%s) ------\n", title.c_str(), dir);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700613 }
Felipe Lemef0292972016-11-22 13:57:05 -0800614 if (PropertiesHelper::IsDryRun()) return 0;
Mark Salyzyn326842f2015-04-30 09:49:41 -0700615
616 if (dir[strlen(dir) - 1] == '/') {
617 ++slash;
618 }
619 dirp = opendir(dir);
Yi Kong19d5c002018-07-20 13:39:55 -0700620 if (dirp == nullptr) {
Mark Salyzyn326842f2015-04-30 09:49:41 -0700621 retval = -errno;
Felipe Leme107a05f2016-03-08 15:11:15 -0800622 MYLOGE("%s: %s\n", dir, strerror(errno));
Mark Salyzyn326842f2015-04-30 09:49:41 -0700623 return retval;
624 }
625
626 if (!dump_from_fd) {
627 dump_from_fd = dump_file_from_fd;
628 }
Yi Kong19d5c002018-07-20 13:39:55 -0700629 for (; ((d = readdir(dirp))); free(newpath), newpath = nullptr) {
Mark Salyzyn326842f2015-04-30 09:49:41 -0700630 if ((d->d_name[0] == '.')
631 && (((d->d_name[1] == '.') && (d->d_name[2] == '\0'))
632 || (d->d_name[1] == '\0'))) {
633 continue;
634 }
635 asprintf(&newpath, "%s%s%s%s", dir, slash, d->d_name,
636 (d->d_type == DT_DIR) ? "/" : "");
637 if (!newpath) {
638 retval = -errno;
639 continue;
640 }
641 if (skip && (*skip)(newpath)) {
642 continue;
643 }
644 if (d->d_type == DT_DIR) {
Felipe Leme678727a2016-09-21 17:22:11 -0700645 int ret = dump_files("", newpath, skip, dump_from_fd);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700646 if (ret < 0) {
647 retval = ret;
648 }
649 continue;
650 }
Narayan Kamath6b9516c2017-10-27 11:15:51 +0100651 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(newpath, O_RDONLY | O_NONBLOCK | O_CLOEXEC)));
652 if (fd.get() < 0) {
653 retval = -1;
Felipe Lemed8b94e52016-12-08 10:21:44 -0800654 printf("*** %s: %s\n", newpath, strerror(errno));
Mark Salyzyn326842f2015-04-30 09:49:41 -0700655 continue;
656 }
Yi Kong19d5c002018-07-20 13:39:55 -0700657 (*dump_from_fd)(nullptr, newpath, fd.get());
Mark Salyzyn326842f2015-04-30 09:49:41 -0700658 }
659 closedir(dirp);
Felipe Leme678727a2016-09-21 17:22:11 -0700660 if (!title.empty()) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800661 printf("\n");
Mark Salyzyn326842f2015-04-30 09:49:41 -0700662 }
663 return retval;
664}
665
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800666/* fd must have been opened with the flag O_NONBLOCK. With this flag set,
667 * it's possible to avoid issues where opening the file itself can get
668 * stuck.
669 */
670int dump_file_from_fd(const char *title, const char *path, int fd) {
Felipe Lemef0292972016-11-22 13:57:05 -0800671 if (PropertiesHelper::IsDryRun()) return 0;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700672
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800673 int flags = fcntl(fd, F_GETFL);
674 if (flags == -1) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800675 printf("*** %s: failed to get flags on fd %d: %s\n", path, fd, strerror(errno));
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800676 return -1;
677 } else if (!(flags & O_NONBLOCK)) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800678 printf("*** %s: fd must have O_NONBLOCK set.\n", path);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800679 return -1;
680 }
Felipe Lemef0292972016-11-22 13:57:05 -0800681 return DumpFileFromFdToFd(title, path, fd, STDOUT_FILENO, PropertiesHelper::IsDryRun());
Colin Crossf45fa6b2012-03-26 12:38:26 -0700682}
683
Felipe Leme46b85da2016-11-21 17:40:45 -0800684int Dumpstate::RunCommand(const std::string& title, const std::vector<std::string>& full_command,
685 const CommandOptions& options) {
686 DurationReporter duration_reporter(title);
687
Felipe Lemef0292972016-11-22 13:57:05 -0800688 int status = RunCommandToFd(STDOUT_FILENO, title, full_command, options);
Felipe Leme46b85da2016-11-21 17:40:45 -0800689
Felipe Lemef0292972016-11-22 13:57:05 -0800690 /* TODO: for now we're simplifying the progress calculation by using the
691 * timeout as the weight. It's a good approximation for most cases, except when calling dumpsys,
692 * where its weight should be much higher proportionally to its timeout.
693 * Ideally, it should use a options.EstimatedDuration() instead...*/
694 UpdateProgress(options.Timeout());
Felipe Leme46b85da2016-11-21 17:40:45 -0800695
Felipe Leme46b85da2016-11-21 17:40:45 -0800696 return status;
697}
698
Felipe Leme9a523ae2016-10-20 15:10:33 -0700699void Dumpstate::RunDumpsys(const std::string& title, const std::vector<std::string>& dumpsys_args,
Vishnu Nair6921f802017-11-22 09:17:23 -0800700 const CommandOptions& options, long dumpsysTimeoutMs) {
701 long timeout_ms = dumpsysTimeoutMs > 0 ? dumpsysTimeoutMs : options.TimeoutInMs();
702 std::vector<std::string> dumpsys = {"/system/bin/dumpsys", "-T", std::to_string(timeout_ms)};
Felipe Leme9a523ae2016-10-20 15:10:33 -0700703 dumpsys.insert(dumpsys.end(), dumpsys_args.begin(), dumpsys_args.end());
Felipe Leme678727a2016-09-21 17:22:11 -0700704 RunCommand(title, dumpsys, options);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700705}
706
Felipe Leme2628e9e2016-04-12 16:36:51 -0700707int open_socket(const char *service) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700708 int s = android_get_control_socket(service);
709 if (s < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800710 MYLOGE("android_get_control_socket(%s): %s\n", service, strerror(errno));
Nandana Dutta344cb62019-02-22 15:12:35 +0000711 return -1;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700712 }
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700713 fcntl(s, F_SETFD, FD_CLOEXEC);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700714 if (listen(s, 4) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800715 MYLOGE("listen(control socket): %s\n", strerror(errno));
Nandana Dutta344cb62019-02-22 15:12:35 +0000716 return -1;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700717 }
718
719 struct sockaddr addr;
720 socklen_t alen = sizeof(addr);
721 int fd = accept(s, &addr, &alen);
722 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800723 MYLOGE("accept(control socket): %s\n", strerror(errno));
Nandana Dutta344cb62019-02-22 15:12:35 +0000724 return -1;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700725 }
726
Felipe Leme2628e9e2016-04-12 16:36:51 -0700727 return fd;
728}
729
730/* redirect output to a service control socket */
Nandana Dutta344cb62019-02-22 15:12:35 +0000731bool redirect_to_socket(FILE* redirect, const char* service) {
Felipe Leme2628e9e2016-04-12 16:36:51 -0700732 int fd = open_socket(service);
Nandana Dutta344cb62019-02-22 15:12:35 +0000733 if (fd == -1) {
734 return false;
735 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700736 fflush(redirect);
Nandana Dutta344cb62019-02-22 15:12:35 +0000737 // TODO: handle dup2 failure
738 TEMP_FAILURE_RETRY(dup2(fd, fileno(redirect)));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700739 close(fd);
Nandana Dutta344cb62019-02-22 15:12:35 +0000740 return true;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700741}
742
Felipe Leme2628e9e2016-04-12 16:36:51 -0700743// TODO: should call is_valid_output_file and/or be merged into it.
Felipe Leme111b9d02016-02-03 09:28:24 -0800744void create_parent_dirs(const char *path) {
Srinath Sridharanfdf52d32016-02-01 15:50:22 -0800745 char *chp = const_cast<char *> (path);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700746
747 /* skip initial slash */
748 if (chp[0] == '/')
749 chp++;
750
751 /* create leading directories, if necessary */
Felipe Leme111b9d02016-02-03 09:28:24 -0800752 struct stat dir_stat;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700753 while (chp && chp[0]) {
754 chp = strchr(chp, '/');
755 if (chp) {
756 *chp = 0;
Felipe Leme111b9d02016-02-03 09:28:24 -0800757 if (stat(path, &dir_stat) == -1 || !S_ISDIR(dir_stat.st_mode)) {
Felipe Lemecbce55d2016-02-08 09:53:18 -0800758 MYLOGI("Creating directory %s\n", path);
Felipe Leme111b9d02016-02-03 09:28:24 -0800759 if (mkdir(path, 0770)) { /* drwxrwx--- */
Felipe Lemecbce55d2016-02-08 09:53:18 -0800760 MYLOGE("Unable to create directory %s: %s\n", path, strerror(errno));
Felipe Leme111b9d02016-02-03 09:28:24 -0800761 } else if (chown(path, AID_SHELL, AID_SHELL)) {
Felipe Lemecbce55d2016-02-08 09:53:18 -0800762 MYLOGE("Unable to change ownership of dir %s: %s\n", path, strerror(errno));
Felipe Leme111b9d02016-02-03 09:28:24 -0800763 }
764 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700765 *chp++ = '/';
766 }
767 }
Felipe Leme111b9d02016-02-03 09:28:24 -0800768}
769
Nandana Dutta344cb62019-02-22 15:12:35 +0000770bool _redirect_to_file(FILE* redirect, char* path, int truncate_flag) {
Felipe Leme111b9d02016-02-03 09:28:24 -0800771 create_parent_dirs(path);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700772
Felipe Leme0f3fb202016-06-10 17:10:53 -0700773 int fd = TEMP_FAILURE_RETRY(open(path,
774 O_WRONLY | O_CREAT | truncate_flag | O_CLOEXEC | O_NOFOLLOW,
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -0800775 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700776 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800777 MYLOGE("%s: %s\n", path, strerror(errno));
Nandana Dutta344cb62019-02-22 15:12:35 +0000778 return false;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700779 }
780
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -0800781 TEMP_FAILURE_RETRY(dup2(fd, fileno(redirect)));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700782 close(fd);
Nandana Dutta344cb62019-02-22 15:12:35 +0000783 return true;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700784}
785
Nandana Dutta344cb62019-02-22 15:12:35 +0000786bool redirect_to_file(FILE* redirect, char* path) {
787 return _redirect_to_file(redirect, path, O_TRUNC);
Felipe Leme0f3fb202016-06-10 17:10:53 -0700788}
789
Nandana Dutta344cb62019-02-22 15:12:35 +0000790bool redirect_to_existing_file(FILE* redirect, char* path) {
791 return _redirect_to_file(redirect, path, O_APPEND);
Felipe Leme0f3fb202016-06-10 17:10:53 -0700792}
793
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -0700794void dump_route_tables() {
Felipe Leme78f2c862015-12-21 09:55:22 -0800795 DurationReporter duration_reporter("DUMP ROUTE TABLES");
Felipe Lemef0292972016-11-22 13:57:05 -0800796 if (PropertiesHelper::IsDryRun()) return;
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -0700797 const char* const RT_TABLES_PATH = "/data/misc/net/rt_tables";
Felipe Lemec7fe8fe2016-09-21 18:13:20 -0700798 ds.DumpFile("RT_TABLES", RT_TABLES_PATH);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700799 FILE* fp = fopen(RT_TABLES_PATH, "re");
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -0700800 if (!fp) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800801 printf("*** %s: %s\n", RT_TABLES_PATH, strerror(errno));
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -0700802 return;
803 }
804 char table[16];
805 // Each line has an integer (the table number), a space, and a string (the table name). We only
806 // need the table number. It's a 32-bit unsigned number, so max 10 chars. Skip the table name.
807 // Add a fixed max limit so this doesn't go awry.
808 for (int i = 0; i < 64 && fscanf(fp, " %10s %*s", table) == 1; ++i) {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700809 RunCommand("ROUTE TABLE IPv4", {"ip", "-4", "route", "show", "table", table});
810 RunCommand("ROUTE TABLE IPv6", {"ip", "-6", "route", "show", "table", table});
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -0700811 }
812 fclose(fp);
813}
Felipe Leme71bbfc52015-11-23 14:14:51 -0800814
Felipe Leme71bbfc52015-11-23 14:14:51 -0800815// TODO: make this function thread safe if sections are generated in parallel.
Vishnu Nair6921f802017-11-22 09:17:23 -0800816void Dumpstate::UpdateProgress(int32_t delta_sec) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700817 if (progress_ == nullptr) {
818 MYLOGE("UpdateProgress: progress_ not set\n");
819 return;
820 }
Felipe Leme71bbfc52015-11-23 14:14:51 -0800821
Felipe Leme7447d7c2016-11-03 18:12:22 -0700822 // Always update progess so stats can be tuned...
Vishnu Nair6921f802017-11-22 09:17:23 -0800823 bool max_changed = progress_->Inc(delta_sec);
Felipe Leme7447d7c2016-11-03 18:12:22 -0700824
825 // ...but only notifiy listeners when necessary.
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100826 if (!options_->do_progress_updates) return;
Felipe Leme71bbfc52015-11-23 14:14:51 -0800827
Felipe Leme009ecbb2016-11-07 10:18:44 -0800828 int progress = progress_->Get();
829 int max = progress_->GetMax();
Felipe Lemead5f6c42015-11-30 14:26:46 -0800830
831 // adjusts max on the fly
Felipe Leme009ecbb2016-11-07 10:18:44 -0800832 if (max_changed && listener_ != nullptr) {
833 listener_->onMaxProgressUpdated(max);
Felipe Lemead5f6c42015-11-30 14:26:46 -0800834 }
835
Felipe Leme009ecbb2016-11-07 10:18:44 -0800836 int32_t last_update_delta = progress - last_updated_progress_;
837 if (last_updated_progress_ > 0 && last_update_delta < update_progress_threshold_) {
838 return;
839 }
840 last_updated_progress_ = progress;
Felipe Leme7447d7c2016-11-03 18:12:22 -0700841
Felipe Leme9a523ae2016-10-20 15:10:33 -0700842 if (control_socket_fd_ >= 0) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700843 dprintf(control_socket_fd_, "PROGRESS:%d/%d\n", progress, max);
Felipe Leme9a523ae2016-10-20 15:10:33 -0700844 fsync(control_socket_fd_);
Felipe Leme02b7e002016-07-22 12:03:20 -0700845 }
846
Nandana Duttbabf6c72019-01-15 14:11:12 +0000847 int percent = 100 * progress / max;
Felipe Leme75876a22016-10-27 16:31:27 -0700848 if (listener_ != nullptr) {
Nandana Duttbabf6c72019-01-15 14:11:12 +0000849 if (percent % 5 == 0) {
850 // We don't want to spam logcat, so only log multiples of 5.
851 MYLOGD("Setting progress (%s): %d/%d (%d%%)\n", listener_name_.c_str(), progress, max,
852 percent);
Felipe Leme75876a22016-10-27 16:31:27 -0700853 } else {
854 // stderr is ignored on normal invocations, but useful when calling
855 // /system/bin/dumpstate directly for debuggging.
Nandana Duttbabf6c72019-01-15 14:11:12 +0000856 fprintf(stderr, "Setting progress (%s): %d/%d (%d%%)\n", listener_name_.c_str(),
857 progress, max, percent);
Felipe Leme75876a22016-10-27 16:31:27 -0700858 }
Nandana Duttbabf6c72019-01-15 14:11:12 +0000859 // TODO(b/111441001): Remove in favor of onProgress
Felipe Leme7447d7c2016-11-03 18:12:22 -0700860 listener_->onProgressUpdated(progress);
Nandana Duttbabf6c72019-01-15 14:11:12 +0000861
862 listener_->onProgress(percent);
Felipe Leme71bbfc52015-11-23 14:14:51 -0800863 }
864}
Felipe Lemee338bf62015-12-07 14:03:50 -0800865
Felipe Lemebbaf3c12016-10-11 14:32:25 -0700866void Dumpstate::TakeScreenshot(const std::string& path) {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700867 const std::string& real_path = path.empty() ? screenshot_path_ : path;
Felipe Lemebbaf3c12016-10-11 14:32:25 -0700868 int status =
Felipe Leme9a523ae2016-10-20 15:10:33 -0700869 RunCommand("", {"/system/bin/screencap", "-p", real_path},
Felipe Lemebbaf3c12016-10-11 14:32:25 -0700870 CommandOptions::WithTimeout(10).Always().DropRoot().RedirectStderr().Build());
871 if (status == 0) {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700872 MYLOGD("Screenshot saved on %s\n", real_path.c_str());
Felipe Lemebbaf3c12016-10-11 14:32:25 -0700873 } else {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700874 MYLOGE("Failed to take screenshot on %s\n", real_path.c_str());
Felipe Lemebbaf3c12016-10-11 14:32:25 -0700875 }
Felipe Lemee338bf62015-12-07 14:03:50 -0800876}
Mark Salyzynf55d4022015-12-11 07:32:31 -0800877
Felipe Leme0c80cf02016-01-05 13:25:34 -0800878bool is_dir(const char* pathname) {
879 struct stat info;
880 if (stat(pathname, &info) == -1) {
881 return false;
882 }
883 return S_ISDIR(info.st_mode);
884}
885
886time_t get_mtime(int fd, time_t default_mtime) {
887 struct stat info;
888 if (fstat(fd, &info) == -1) {
889 return default_mtime;
890 }
891 return info.st_mtime;
892}
893
Mark Salyzyn8c8130e2015-12-09 11:21:28 -0800894void dump_emmc_ecsd(const char *ext_csd_path) {
Mark Salyzyn290f4b92016-05-16 08:33:59 -0700895 // List of interesting offsets
Mark Salyzyn8c8130e2015-12-09 11:21:28 -0800896 struct hex {
897 char str[2];
Mark Salyzyn8c8130e2015-12-09 11:21:28 -0800898 };
Mark Salyzyn290f4b92016-05-16 08:33:59 -0700899 static const size_t EXT_CSD_REV = 192 * sizeof(hex);
900 static const size_t EXT_PRE_EOL_INFO = 267 * sizeof(hex);
901 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_A = 268 * sizeof(hex);
902 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_B = 269 * sizeof(hex);
903
904 std::string buffer;
905 if (!android::base::ReadFileToString(ext_csd_path, &buffer)) {
906 return;
907 }
Mark Salyzyn8c8130e2015-12-09 11:21:28 -0800908
Felipe Lemed8b94e52016-12-08 10:21:44 -0800909 printf("------ %s Extended CSD ------\n", ext_csd_path);
Mark Salyzyn8c8130e2015-12-09 11:21:28 -0800910
Mark Salyzyn290f4b92016-05-16 08:33:59 -0700911 if (buffer.length() < (EXT_CSD_REV + sizeof(hex))) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800912 printf("*** %s: truncated content %zu\n\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -0800913 return;
914 }
915
Mark Salyzyn290f4b92016-05-16 08:33:59 -0700916 int ext_csd_rev = 0;
917 std::string sub = buffer.substr(EXT_CSD_REV, sizeof(hex));
918 if (sscanf(sub.c_str(), "%2x", &ext_csd_rev) != 1) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800919 printf("*** %s: EXT_CSD_REV parse error \"%s\"\n\n", ext_csd_path, sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -0800920 return;
921 }
922
Mark Salyzyn290f4b92016-05-16 08:33:59 -0700923 static const char *ver_str[] = {
924 "4.0", "4.1", "4.2", "4.3", "Obsolete", "4.41", "4.5", "5.0"
925 };
Felipe Lemed8b94e52016-12-08 10:21:44 -0800926 printf("rev 1.%d (MMC %s)\n", ext_csd_rev,
927 (ext_csd_rev < (int)(sizeof(ver_str) / sizeof(ver_str[0]))) ? ver_str[ext_csd_rev]
928 : "Unknown");
Mark Salyzyn8c8130e2015-12-09 11:21:28 -0800929 if (ext_csd_rev < 7) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800930 printf("\n");
Mark Salyzyn8c8130e2015-12-09 11:21:28 -0800931 return;
932 }
933
Mark Salyzyn290f4b92016-05-16 08:33:59 -0700934 if (buffer.length() < (EXT_PRE_EOL_INFO + sizeof(hex))) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800935 printf("*** %s: truncated content %zu\n\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -0800936 return;
937 }
938
Mark Salyzyn290f4b92016-05-16 08:33:59 -0700939 int ext_pre_eol_info = 0;
940 sub = buffer.substr(EXT_PRE_EOL_INFO, sizeof(hex));
941 if (sscanf(sub.c_str(), "%2x", &ext_pre_eol_info) != 1) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800942 printf("*** %s: PRE_EOL_INFO parse error \"%s\"\n\n", ext_csd_path, sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -0800943 return;
944 }
Mark Salyzyn290f4b92016-05-16 08:33:59 -0700945
946 static const char *eol_str[] = {
947 "Undefined",
948 "Normal",
949 "Warning (consumed 80% of reserve)",
950 "Urgent (consumed 90% of reserve)"
951 };
Felipe Lemed8b94e52016-12-08 10:21:44 -0800952 printf(
953 "PRE_EOL_INFO %d (MMC %s)\n", ext_pre_eol_info,
Felipe Leme8f00ed02016-12-07 17:42:44 -0800954 eol_str[(ext_pre_eol_info < (int)(sizeof(eol_str) / sizeof(eol_str[0]))) ? ext_pre_eol_info
955 : 0]);
Mark Salyzyn8c8130e2015-12-09 11:21:28 -0800956
957 for (size_t lifetime = EXT_DEVICE_LIFE_TIME_EST_TYP_A;
958 lifetime <= EXT_DEVICE_LIFE_TIME_EST_TYP_B;
Mark Salyzyn290f4b92016-05-16 08:33:59 -0700959 lifetime += sizeof(hex)) {
Mark Salyzyn8c8130e2015-12-09 11:21:28 -0800960 int ext_device_life_time_est;
961 static const char *est_str[] = {
962 "Undefined",
963 "0-10% of device lifetime used",
964 "10-20% of device lifetime used",
965 "20-30% of device lifetime used",
966 "30-40% of device lifetime used",
967 "40-50% of device lifetime used",
968 "50-60% of device lifetime used",
969 "60-70% of device lifetime used",
970 "70-80% of device lifetime used",
971 "80-90% of device lifetime used",
972 "90-100% of device lifetime used",
973 "Exceeded the maximum estimated device lifetime",
974 };
975
Mark Salyzyn290f4b92016-05-16 08:33:59 -0700976 if (buffer.length() < (lifetime + sizeof(hex))) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800977 printf("*** %s: truncated content %zu\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -0800978 break;
979 }
980
981 ext_device_life_time_est = 0;
Mark Salyzyn290f4b92016-05-16 08:33:59 -0700982 sub = buffer.substr(lifetime, sizeof(hex));
983 if (sscanf(sub.c_str(), "%2x", &ext_device_life_time_est) != 1) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800984 printf("*** %s: DEVICE_LIFE_TIME_EST_TYP_%c parse error \"%s\"\n", ext_csd_path,
985 (unsigned)((lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) / sizeof(hex)) + 'A',
986 sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -0800987 continue;
988 }
Felipe Lemed8b94e52016-12-08 10:21:44 -0800989 printf("DEVICE_LIFE_TIME_EST_TYP_%c %d (MMC %s)\n",
990 (unsigned)((lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) / sizeof(hex)) + 'A',
991 ext_device_life_time_est,
992 est_str[(ext_device_life_time_est < (int)(sizeof(est_str) / sizeof(est_str[0])))
993 ? ext_device_life_time_est
994 : 0]);
Mark Salyzyn8c8130e2015-12-09 11:21:28 -0800995 }
996
Felipe Lemed8b94e52016-12-08 10:21:44 -0800997 printf("\n");
Mark Salyzyn8c8130e2015-12-09 11:21:28 -0800998}