blob: fe1e4b4b1490e4bd9102fe66f6d9e7c994a97be2 [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))) {
Nandana Duttbbdb5b42019-03-12 10:52:56 +0000281 if (ds.IsUserConsentDenied()) {
282 MYLOGE(
283 "Returning early because user denied consent to share bugreport with calling app.");
284 closedir(d);
285 return;
286 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700287 int pid;
288 int fd;
289 char cmdpath[255];
290 char cmdline[255];
291
292 if (!(pid = atoi(de->d_name))) {
293 continue;
294 }
295
Colin Crossf45fa6b2012-03-26 12:38:26 -0700296 memset(cmdline, 0, sizeof(cmdline));
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800297
298 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/cmdline", pid);
299 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
300 TEMP_FAILURE_RETRY(read(fd, cmdline, sizeof(cmdline) - 2));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700301 close(fd);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800302 if (cmdline[0]) {
303 helper(pid, cmdline, arg);
304 continue;
305 }
306 }
307
308 // if no cmdline, a kernel thread has comm
309 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/comm", pid);
310 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
311 TEMP_FAILURE_RETRY(read(fd, cmdline + 1, sizeof(cmdline) - 4));
312 close(fd);
313 if (cmdline[1]) {
314 cmdline[0] = '[';
315 size_t len = strcspn(cmdline, "\f\b\r\n");
316 cmdline[len] = ']';
317 cmdline[len+1] = '\0';
318 }
319 }
320 if (!cmdline[0]) {
321 strcpy(cmdline, "N/A");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700322 }
Colin Cross0c22e8b2012-11-02 15:46:56 -0700323 helper(pid, cmdline, arg);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700324 }
325
326 closedir(d);
327}
328
Colin Cross0c22e8b2012-11-02 15:46:56 -0700329static void for_each_pid_helper(int pid, const char *cmdline, void *arg) {
Felipe Leme8620bb42015-11-10 11:04:45 -0800330 for_each_pid_func *func = (for_each_pid_func*) arg;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700331 func(pid, cmdline);
332}
333
334void for_each_pid(for_each_pid_func func, const char *header) {
Felipe Leme8f00ed02016-12-07 17:42:44 -0800335 std::string title = header == nullptr ? "for_each_pid"
336 : android::base::StringPrintf("for_each_pid(%s)", header);
337 DurationReporter duration_reporter(title);
Felipe Lemef0292972016-11-22 13:57:05 -0800338 if (PropertiesHelper::IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700339
Felipe Leme515eb0d2015-12-14 15:09:56 -0800340 __for_each_pid(for_each_pid_helper, header, (void *) func);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700341}
342
343static void for_each_tid_helper(int pid, const char *cmdline, void *arg) {
344 DIR *d;
345 struct dirent *de;
346 char taskpath[255];
Felipe Leme8620bb42015-11-10 11:04:45 -0800347 for_each_tid_func *func = (for_each_tid_func *) arg;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700348
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700349 snprintf(taskpath, sizeof(taskpath), "/proc/%d/task", pid);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700350
351 if (!(d = opendir(taskpath))) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800352 printf("Failed to open %s (%s)\n", taskpath, strerror(errno));
Colin Cross0c22e8b2012-11-02 15:46:56 -0700353 return;
354 }
355
356 func(pid, pid, cmdline);
357
358 while ((de = readdir(d))) {
Nandana Duttbbdb5b42019-03-12 10:52:56 +0000359 if (ds.IsUserConsentDenied()) {
360 MYLOGE(
361 "Returning early because user denied consent to share bugreport with calling app.");
362 closedir(d);
363 return;
364 }
Colin Cross0c22e8b2012-11-02 15:46:56 -0700365 int tid;
366 int fd;
367 char commpath[255];
368 char comm[255];
369
370 if (!(tid = atoi(de->d_name))) {
371 continue;
372 }
373
374 if (tid == pid)
375 continue;
376
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700377 snprintf(commpath, sizeof(commpath), "/proc/%d/comm", tid);
Colin Cross1493a392012-11-07 11:25:31 -0800378 memset(comm, 0, sizeof(comm));
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700379 if ((fd = TEMP_FAILURE_RETRY(open(commpath, O_RDONLY | O_CLOEXEC))) < 0) {
Colin Cross0c22e8b2012-11-02 15:46:56 -0700380 strcpy(comm, "N/A");
381 } else {
382 char *c;
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800383 TEMP_FAILURE_RETRY(read(fd, comm, sizeof(comm) - 2));
Colin Cross0c22e8b2012-11-02 15:46:56 -0700384 close(fd);
385
386 c = strrchr(comm, '\n');
387 if (c) {
388 *c = '\0';
389 }
390 }
391 func(pid, tid, comm);
392 }
393
394 closedir(d);
395}
396
397void for_each_tid(for_each_tid_func func, const char *header) {
Felipe Leme8f00ed02016-12-07 17:42:44 -0800398 std::string title = header == nullptr ? "for_each_tid"
399 : android::base::StringPrintf("for_each_tid(%s)", header);
400 DurationReporter duration_reporter(title);
Felipe Lemed8b94e52016-12-08 10:21:44 -0800401
Felipe Lemef0292972016-11-22 13:57:05 -0800402 if (PropertiesHelper::IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700403
Felipe Leme8620bb42015-11-10 11:04:45 -0800404 __for_each_pid(for_each_tid_helper, header, (void *) func);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700405}
406
407void show_wchan(int pid, int tid, const char *name) {
Felipe Lemef0292972016-11-22 13:57:05 -0800408 if (PropertiesHelper::IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700409
Colin Crossf45fa6b2012-03-26 12:38:26 -0700410 char path[255];
411 char buffer[255];
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800412 int fd, ret, save_errno;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700413 char name_buffer[255];
Colin Crossf45fa6b2012-03-26 12:38:26 -0700414
415 memset(buffer, 0, sizeof(buffer));
416
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700417 snprintf(path, sizeof(path), "/proc/%d/wchan", tid);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700418 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800419 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700420 return;
421 }
422
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800423 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
424 save_errno = errno;
425 close(fd);
426
427 if (ret < 0) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800428 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800429 return;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700430 }
431
Colin Cross0c22e8b2012-11-02 15:46:56 -0700432 snprintf(name_buffer, sizeof(name_buffer), "%*s%s",
433 pid == tid ? 0 : 3, "", name);
434
Felipe Lemed8b94e52016-12-08 10:21:44 -0800435 printf("%-7d %-32s %s\n", tid, name_buffer, buffer);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700436
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800437 return;
438}
439
440// print time in centiseconds
441static void snprcent(char *buffer, size_t len, size_t spc,
442 unsigned long long time) {
443 static long hz; // cache discovered hz
444
445 if (hz <= 0) {
446 hz = sysconf(_SC_CLK_TCK);
447 if (hz <= 0) {
448 hz = 1000;
449 }
450 }
451
452 // convert to centiseconds
453 time = (time * 100 + (hz / 2)) / hz;
454
455 char str[16];
456
457 snprintf(str, sizeof(str), " %llu.%02u",
458 time / 100, (unsigned)(time % 100));
459 size_t offset = strlen(buffer);
460 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
461 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
462}
463
464// print permille as a percent
465static void snprdec(char *buffer, size_t len, size_t spc, unsigned permille) {
466 char str[16];
467
468 snprintf(str, sizeof(str), " %u.%u%%", permille / 10, permille % 10);
469 size_t offset = strlen(buffer);
470 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
471 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
472}
473
474void show_showtime(int pid, const char *name) {
Felipe Lemef0292972016-11-22 13:57:05 -0800475 if (PropertiesHelper::IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700476
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800477 char path[255];
478 char buffer[1023];
479 int fd, ret, save_errno;
480
481 memset(buffer, 0, sizeof(buffer));
482
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700483 snprintf(path, sizeof(path), "/proc/%d/stat", pid);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800484 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800485 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800486 return;
487 }
488
489 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
490 save_errno = errno;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700491 close(fd);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800492
493 if (ret < 0) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800494 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800495 return;
496 }
497
498 // field 14 is utime
499 // field 15 is stime
500 // field 42 is iotime
501 unsigned long long utime = 0, stime = 0, iotime = 0;
502 if (sscanf(buffer,
Mark Salyzyn791ddd32016-02-10 07:41:12 -0800503 "%*u %*s %*s %*d %*d %*d %*d %*d %*d %*d %*d "
504 "%*d %*d %llu %llu %*d %*d %*d %*d %*d %*d "
505 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %*d "
506 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %llu ",
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800507 &utime, &stime, &iotime) != 3) {
508 return;
509 }
510
511 unsigned long long total = utime + stime;
512 if (!total) {
513 return;
514 }
515
516 unsigned permille = (iotime * 1000 + (total / 2)) / total;
517 if (permille > 1000) {
518 permille = 1000;
519 }
520
521 // try to beautify and stabilize columns at <80 characters
522 snprintf(buffer, sizeof(buffer), "%-6d%s", pid, name);
523 if ((name[0] != '[') || utime) {
524 snprcent(buffer, sizeof(buffer), 57, utime);
525 }
526 snprcent(buffer, sizeof(buffer), 65, stime);
527 if ((name[0] != '[') || iotime) {
528 snprcent(buffer, sizeof(buffer), 73, iotime);
529 }
530 if (iotime) {
531 snprdec(buffer, sizeof(buffer), 79, permille);
532 }
Felipe Lemed8b94e52016-12-08 10:21:44 -0800533 puts(buffer); // adds a trailing newline
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800534
Colin Crossf45fa6b2012-03-26 12:38:26 -0700535 return;
536}
537
538void do_dmesg() {
Felipe Leme78f2c862015-12-21 09:55:22 -0800539 const char *title = "KERNEL LOG (dmesg)";
540 DurationReporter duration_reporter(title);
Felipe Lemed8b94e52016-12-08 10:21:44 -0800541 printf("------ %s ------\n", title);
Felipe Leme78f2c862015-12-21 09:55:22 -0800542
Felipe Lemef0292972016-11-22 13:57:05 -0800543 if (PropertiesHelper::IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700544
Elliott Hughes5f87b312012-09-17 11:43:40 -0700545 /* Get size of kernel buffer */
Yi Kong19d5c002018-07-20 13:39:55 -0700546 int size = klogctl(KLOG_SIZE_BUFFER, nullptr, 0);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700547 if (size <= 0) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800548 printf("Unexpected klogctl return value: %d\n\n", size);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700549 return;
550 }
551 char *buf = (char *) malloc(size + 1);
Yi Kong19d5c002018-07-20 13:39:55 -0700552 if (buf == nullptr) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800553 printf("memory allocation failed\n\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700554 return;
555 }
556 int retval = klogctl(KLOG_READ_ALL, buf, size);
557 if (retval < 0) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800558 printf("klogctl failure\n\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700559 free(buf);
560 return;
561 }
562 buf[retval] = '\0';
Felipe Lemed8b94e52016-12-08 10:21:44 -0800563 printf("%s\n\n", buf);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700564 free(buf);
565 return;
566}
567
568void do_showmap(int pid, const char *name) {
569 char title[255];
570 char arg[255];
571
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700572 snprintf(title, sizeof(title), "SHOW MAP %d (%s)", pid, name);
573 snprintf(arg, sizeof(arg), "%d", pid);
Felipe Lemef0292972016-11-22 13:57:05 -0800574 RunCommand(title, {"showmap", "-q", arg}, CommandOptions::AS_ROOT);
Felipe Lemebda15a02016-11-16 17:48:25 -0800575}
576
Felipe Leme678727a2016-09-21 17:22:11 -0700577int Dumpstate::DumpFile(const std::string& title, const std::string& path) {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700578 DurationReporter duration_reporter(title);
Felipe Leme46b85da2016-11-21 17:40:45 -0800579
Felipe Lemef0292972016-11-22 13:57:05 -0800580 int status = DumpFileToFd(STDOUT_FILENO, title, path);
Felipe Leme46b85da2016-11-21 17:40:45 -0800581
Felipe Lemef0292972016-11-22 13:57:05 -0800582 UpdateProgress(WEIGHT_FILE);
Felipe Leme46b85da2016-11-21 17:40:45 -0800583
Felipe Leme46b85da2016-11-21 17:40:45 -0800584 return status;
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800585}
586
Felipe Leme71a74ac2016-03-17 15:43:25 -0700587int read_file_as_long(const char *path, long int *output) {
588 int fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
589 if (fd < 0) {
590 int err = errno;
591 MYLOGE("Error opening file descriptor for %s: %s\n", path, strerror(err));
592 return -1;
593 }
594 char buffer[50];
595 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
596 if (bytes_read == -1) {
597 MYLOGE("Error reading file %s: %s\n", path, strerror(errno));
598 return -2;
599 }
600 if (bytes_read == 0) {
601 MYLOGE("File %s is empty\n", path);
602 return -3;
603 }
604 *output = atoi(buffer);
605 return 0;
606}
607
Mark Salyzyn326842f2015-04-30 09:49:41 -0700608/* calls skip to gate calling dump_from_fd recursively
609 * in the specified directory. dump_from_fd defaults to
610 * dump_file_from_fd above when set to NULL. skip defaults
611 * to false when set to NULL. dump_from_fd will always be
612 * called with title NULL.
613 */
Felipe Leme678727a2016-09-21 17:22:11 -0700614int dump_files(const std::string& title, const char* dir, bool (*skip)(const char* path),
615 int (*dump_from_fd)(const char* title, const char* path, int fd)) {
Felipe Leme78f2c862015-12-21 09:55:22 -0800616 DurationReporter duration_reporter(title);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700617 DIR *dirp;
618 struct dirent *d;
Yi Kong19d5c002018-07-20 13:39:55 -0700619 char *newpath = nullptr;
Felipe Leme8620bb42015-11-10 11:04:45 -0800620 const char *slash = "/";
Narayan Kamath6b9516c2017-10-27 11:15:51 +0100621 int retval = 0;
Mark Salyzyn326842f2015-04-30 09:49:41 -0700622
Felipe Leme678727a2016-09-21 17:22:11 -0700623 if (!title.empty()) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800624 printf("------ %s (%s) ------\n", title.c_str(), dir);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700625 }
Felipe Lemef0292972016-11-22 13:57:05 -0800626 if (PropertiesHelper::IsDryRun()) return 0;
Mark Salyzyn326842f2015-04-30 09:49:41 -0700627
628 if (dir[strlen(dir) - 1] == '/') {
629 ++slash;
630 }
631 dirp = opendir(dir);
Yi Kong19d5c002018-07-20 13:39:55 -0700632 if (dirp == nullptr) {
Mark Salyzyn326842f2015-04-30 09:49:41 -0700633 retval = -errno;
Felipe Leme107a05f2016-03-08 15:11:15 -0800634 MYLOGE("%s: %s\n", dir, strerror(errno));
Mark Salyzyn326842f2015-04-30 09:49:41 -0700635 return retval;
636 }
637
638 if (!dump_from_fd) {
639 dump_from_fd = dump_file_from_fd;
640 }
Yi Kong19d5c002018-07-20 13:39:55 -0700641 for (; ((d = readdir(dirp))); free(newpath), newpath = nullptr) {
Mark Salyzyn326842f2015-04-30 09:49:41 -0700642 if ((d->d_name[0] == '.')
643 && (((d->d_name[1] == '.') && (d->d_name[2] == '\0'))
644 || (d->d_name[1] == '\0'))) {
645 continue;
646 }
647 asprintf(&newpath, "%s%s%s%s", dir, slash, d->d_name,
648 (d->d_type == DT_DIR) ? "/" : "");
649 if (!newpath) {
650 retval = -errno;
651 continue;
652 }
653 if (skip && (*skip)(newpath)) {
654 continue;
655 }
656 if (d->d_type == DT_DIR) {
Felipe Leme678727a2016-09-21 17:22:11 -0700657 int ret = dump_files("", newpath, skip, dump_from_fd);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700658 if (ret < 0) {
659 retval = ret;
660 }
661 continue;
662 }
Narayan Kamath6b9516c2017-10-27 11:15:51 +0100663 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(newpath, O_RDONLY | O_NONBLOCK | O_CLOEXEC)));
664 if (fd.get() < 0) {
665 retval = -1;
Felipe Lemed8b94e52016-12-08 10:21:44 -0800666 printf("*** %s: %s\n", newpath, strerror(errno));
Mark Salyzyn326842f2015-04-30 09:49:41 -0700667 continue;
668 }
Yi Kong19d5c002018-07-20 13:39:55 -0700669 (*dump_from_fd)(nullptr, newpath, fd.get());
Mark Salyzyn326842f2015-04-30 09:49:41 -0700670 }
671 closedir(dirp);
Felipe Leme678727a2016-09-21 17:22:11 -0700672 if (!title.empty()) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800673 printf("\n");
Mark Salyzyn326842f2015-04-30 09:49:41 -0700674 }
675 return retval;
676}
677
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800678/* fd must have been opened with the flag O_NONBLOCK. With this flag set,
679 * it's possible to avoid issues where opening the file itself can get
680 * stuck.
681 */
682int dump_file_from_fd(const char *title, const char *path, int fd) {
Felipe Lemef0292972016-11-22 13:57:05 -0800683 if (PropertiesHelper::IsDryRun()) return 0;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700684
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800685 int flags = fcntl(fd, F_GETFL);
686 if (flags == -1) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800687 printf("*** %s: failed to get flags on fd %d: %s\n", path, fd, strerror(errno));
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800688 return -1;
689 } else if (!(flags & O_NONBLOCK)) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800690 printf("*** %s: fd must have O_NONBLOCK set.\n", path);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800691 return -1;
692 }
Felipe Lemef0292972016-11-22 13:57:05 -0800693 return DumpFileFromFdToFd(title, path, fd, STDOUT_FILENO, PropertiesHelper::IsDryRun());
Colin Crossf45fa6b2012-03-26 12:38:26 -0700694}
695
Felipe Leme46b85da2016-11-21 17:40:45 -0800696int Dumpstate::RunCommand(const std::string& title, const std::vector<std::string>& full_command,
697 const CommandOptions& options) {
698 DurationReporter duration_reporter(title);
699
Felipe Lemef0292972016-11-22 13:57:05 -0800700 int status = RunCommandToFd(STDOUT_FILENO, title, full_command, options);
Felipe Leme46b85da2016-11-21 17:40:45 -0800701
Felipe Lemef0292972016-11-22 13:57:05 -0800702 /* TODO: for now we're simplifying the progress calculation by using the
703 * timeout as the weight. It's a good approximation for most cases, except when calling dumpsys,
704 * where its weight should be much higher proportionally to its timeout.
705 * Ideally, it should use a options.EstimatedDuration() instead...*/
706 UpdateProgress(options.Timeout());
Felipe Leme46b85da2016-11-21 17:40:45 -0800707
Felipe Leme46b85da2016-11-21 17:40:45 -0800708 return status;
709}
710
Felipe Leme9a523ae2016-10-20 15:10:33 -0700711void Dumpstate::RunDumpsys(const std::string& title, const std::vector<std::string>& dumpsys_args,
Vishnu Nair6921f802017-11-22 09:17:23 -0800712 const CommandOptions& options, long dumpsysTimeoutMs) {
713 long timeout_ms = dumpsysTimeoutMs > 0 ? dumpsysTimeoutMs : options.TimeoutInMs();
714 std::vector<std::string> dumpsys = {"/system/bin/dumpsys", "-T", std::to_string(timeout_ms)};
Felipe Leme9a523ae2016-10-20 15:10:33 -0700715 dumpsys.insert(dumpsys.end(), dumpsys_args.begin(), dumpsys_args.end());
Felipe Leme678727a2016-09-21 17:22:11 -0700716 RunCommand(title, dumpsys, options);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700717}
718
Felipe Leme2628e9e2016-04-12 16:36:51 -0700719int open_socket(const char *service) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700720 int s = android_get_control_socket(service);
721 if (s < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800722 MYLOGE("android_get_control_socket(%s): %s\n", service, strerror(errno));
Nandana Dutta344cb62019-02-22 15:12:35 +0000723 return -1;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700724 }
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700725 fcntl(s, F_SETFD, FD_CLOEXEC);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700726 if (listen(s, 4) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800727 MYLOGE("listen(control socket): %s\n", strerror(errno));
Nandana Dutta344cb62019-02-22 15:12:35 +0000728 return -1;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700729 }
730
731 struct sockaddr addr;
732 socklen_t alen = sizeof(addr);
733 int fd = accept(s, &addr, &alen);
734 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800735 MYLOGE("accept(control socket): %s\n", strerror(errno));
Nandana Dutta344cb62019-02-22 15:12:35 +0000736 return -1;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700737 }
738
Felipe Leme2628e9e2016-04-12 16:36:51 -0700739 return fd;
740}
741
742/* redirect output to a service control socket */
Nandana Dutta344cb62019-02-22 15:12:35 +0000743bool redirect_to_socket(FILE* redirect, const char* service) {
Felipe Leme2628e9e2016-04-12 16:36:51 -0700744 int fd = open_socket(service);
Nandana Dutta344cb62019-02-22 15:12:35 +0000745 if (fd == -1) {
746 return false;
747 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700748 fflush(redirect);
Nandana Dutta344cb62019-02-22 15:12:35 +0000749 // TODO: handle dup2 failure
750 TEMP_FAILURE_RETRY(dup2(fd, fileno(redirect)));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700751 close(fd);
Nandana Dutta344cb62019-02-22 15:12:35 +0000752 return true;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700753}
754
Felipe Leme2628e9e2016-04-12 16:36:51 -0700755// TODO: should call is_valid_output_file and/or be merged into it.
Felipe Leme111b9d02016-02-03 09:28:24 -0800756void create_parent_dirs(const char *path) {
Srinath Sridharanfdf52d32016-02-01 15:50:22 -0800757 char *chp = const_cast<char *> (path);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700758
759 /* skip initial slash */
760 if (chp[0] == '/')
761 chp++;
762
763 /* create leading directories, if necessary */
Felipe Leme111b9d02016-02-03 09:28:24 -0800764 struct stat dir_stat;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700765 while (chp && chp[0]) {
766 chp = strchr(chp, '/');
767 if (chp) {
768 *chp = 0;
Felipe Leme111b9d02016-02-03 09:28:24 -0800769 if (stat(path, &dir_stat) == -1 || !S_ISDIR(dir_stat.st_mode)) {
Felipe Lemecbce55d2016-02-08 09:53:18 -0800770 MYLOGI("Creating directory %s\n", path);
Felipe Leme111b9d02016-02-03 09:28:24 -0800771 if (mkdir(path, 0770)) { /* drwxrwx--- */
Felipe Lemecbce55d2016-02-08 09:53:18 -0800772 MYLOGE("Unable to create directory %s: %s\n", path, strerror(errno));
Felipe Leme111b9d02016-02-03 09:28:24 -0800773 } else if (chown(path, AID_SHELL, AID_SHELL)) {
Felipe Lemecbce55d2016-02-08 09:53:18 -0800774 MYLOGE("Unable to change ownership of dir %s: %s\n", path, strerror(errno));
Felipe Leme111b9d02016-02-03 09:28:24 -0800775 }
776 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700777 *chp++ = '/';
778 }
779 }
Felipe Leme111b9d02016-02-03 09:28:24 -0800780}
781
Nandana Dutta344cb62019-02-22 15:12:35 +0000782bool _redirect_to_file(FILE* redirect, char* path, int truncate_flag) {
Felipe Leme111b9d02016-02-03 09:28:24 -0800783 create_parent_dirs(path);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700784
Felipe Leme0f3fb202016-06-10 17:10:53 -0700785 int fd = TEMP_FAILURE_RETRY(open(path,
786 O_WRONLY | O_CREAT | truncate_flag | O_CLOEXEC | O_NOFOLLOW,
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -0800787 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700788 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -0800789 MYLOGE("%s: %s\n", path, strerror(errno));
Nandana Dutta344cb62019-02-22 15:12:35 +0000790 return false;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700791 }
792
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -0800793 TEMP_FAILURE_RETRY(dup2(fd, fileno(redirect)));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700794 close(fd);
Nandana Dutta344cb62019-02-22 15:12:35 +0000795 return true;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700796}
797
Nandana Dutta344cb62019-02-22 15:12:35 +0000798bool redirect_to_file(FILE* redirect, char* path) {
799 return _redirect_to_file(redirect, path, O_TRUNC);
Felipe Leme0f3fb202016-06-10 17:10:53 -0700800}
801
Nandana Dutta344cb62019-02-22 15:12:35 +0000802bool redirect_to_existing_file(FILE* redirect, char* path) {
803 return _redirect_to_file(redirect, path, O_APPEND);
Felipe Leme0f3fb202016-06-10 17:10:53 -0700804}
805
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -0700806void dump_route_tables() {
Felipe Leme78f2c862015-12-21 09:55:22 -0800807 DurationReporter duration_reporter("DUMP ROUTE TABLES");
Felipe Lemef0292972016-11-22 13:57:05 -0800808 if (PropertiesHelper::IsDryRun()) return;
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -0700809 const char* const RT_TABLES_PATH = "/data/misc/net/rt_tables";
Felipe Lemec7fe8fe2016-09-21 18:13:20 -0700810 ds.DumpFile("RT_TABLES", RT_TABLES_PATH);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700811 FILE* fp = fopen(RT_TABLES_PATH, "re");
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -0700812 if (!fp) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800813 printf("*** %s: %s\n", RT_TABLES_PATH, strerror(errno));
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -0700814 return;
815 }
816 char table[16];
817 // Each line has an integer (the table number), a space, and a string (the table name). We only
818 // need the table number. It's a 32-bit unsigned number, so max 10 chars. Skip the table name.
819 // Add a fixed max limit so this doesn't go awry.
820 for (int i = 0; i < 64 && fscanf(fp, " %10s %*s", table) == 1; ++i) {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700821 RunCommand("ROUTE TABLE IPv4", {"ip", "-4", "route", "show", "table", table});
822 RunCommand("ROUTE TABLE IPv6", {"ip", "-6", "route", "show", "table", table});
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -0700823 }
824 fclose(fp);
825}
Felipe Leme71bbfc52015-11-23 14:14:51 -0800826
Felipe Leme71bbfc52015-11-23 14:14:51 -0800827// TODO: make this function thread safe if sections are generated in parallel.
Vishnu Nair6921f802017-11-22 09:17:23 -0800828void Dumpstate::UpdateProgress(int32_t delta_sec) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700829 if (progress_ == nullptr) {
830 MYLOGE("UpdateProgress: progress_ not set\n");
831 return;
832 }
Felipe Leme71bbfc52015-11-23 14:14:51 -0800833
Felipe Leme7447d7c2016-11-03 18:12:22 -0700834 // Always update progess so stats can be tuned...
Vishnu Nair6921f802017-11-22 09:17:23 -0800835 bool max_changed = progress_->Inc(delta_sec);
Felipe Leme7447d7c2016-11-03 18:12:22 -0700836
837 // ...but only notifiy listeners when necessary.
Nandana Dutt5fb117b2018-09-27 09:23:36 +0100838 if (!options_->do_progress_updates) return;
Felipe Leme71bbfc52015-11-23 14:14:51 -0800839
Felipe Leme009ecbb2016-11-07 10:18:44 -0800840 int progress = progress_->Get();
841 int max = progress_->GetMax();
Felipe Lemead5f6c42015-11-30 14:26:46 -0800842
843 // adjusts max on the fly
Felipe Leme009ecbb2016-11-07 10:18:44 -0800844 if (max_changed && listener_ != nullptr) {
845 listener_->onMaxProgressUpdated(max);
Felipe Lemead5f6c42015-11-30 14:26:46 -0800846 }
847
Felipe Leme009ecbb2016-11-07 10:18:44 -0800848 int32_t last_update_delta = progress - last_updated_progress_;
849 if (last_updated_progress_ > 0 && last_update_delta < update_progress_threshold_) {
850 return;
851 }
852 last_updated_progress_ = progress;
Felipe Leme7447d7c2016-11-03 18:12:22 -0700853
Felipe Leme9a523ae2016-10-20 15:10:33 -0700854 if (control_socket_fd_ >= 0) {
Felipe Leme7447d7c2016-11-03 18:12:22 -0700855 dprintf(control_socket_fd_, "PROGRESS:%d/%d\n", progress, max);
Felipe Leme9a523ae2016-10-20 15:10:33 -0700856 fsync(control_socket_fd_);
Felipe Leme02b7e002016-07-22 12:03:20 -0700857 }
858
Nandana Duttbabf6c72019-01-15 14:11:12 +0000859 int percent = 100 * progress / max;
Felipe Leme75876a22016-10-27 16:31:27 -0700860 if (listener_ != nullptr) {
Nandana Duttbabf6c72019-01-15 14:11:12 +0000861 if (percent % 5 == 0) {
862 // We don't want to spam logcat, so only log multiples of 5.
863 MYLOGD("Setting progress (%s): %d/%d (%d%%)\n", listener_name_.c_str(), progress, max,
864 percent);
Felipe Leme75876a22016-10-27 16:31:27 -0700865 } else {
866 // stderr is ignored on normal invocations, but useful when calling
867 // /system/bin/dumpstate directly for debuggging.
Nandana Duttbabf6c72019-01-15 14:11:12 +0000868 fprintf(stderr, "Setting progress (%s): %d/%d (%d%%)\n", listener_name_.c_str(),
869 progress, max, percent);
Felipe Leme75876a22016-10-27 16:31:27 -0700870 }
Nandana Duttbabf6c72019-01-15 14:11:12 +0000871 // TODO(b/111441001): Remove in favor of onProgress
Felipe Leme7447d7c2016-11-03 18:12:22 -0700872 listener_->onProgressUpdated(progress);
Nandana Duttbabf6c72019-01-15 14:11:12 +0000873
874 listener_->onProgress(percent);
Felipe Leme71bbfc52015-11-23 14:14:51 -0800875 }
876}
Felipe Lemee338bf62015-12-07 14:03:50 -0800877
Felipe Lemebbaf3c12016-10-11 14:32:25 -0700878void Dumpstate::TakeScreenshot(const std::string& path) {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700879 const std::string& real_path = path.empty() ? screenshot_path_ : path;
Felipe Lemebbaf3c12016-10-11 14:32:25 -0700880 int status =
Felipe Leme9a523ae2016-10-20 15:10:33 -0700881 RunCommand("", {"/system/bin/screencap", "-p", real_path},
Felipe Lemebbaf3c12016-10-11 14:32:25 -0700882 CommandOptions::WithTimeout(10).Always().DropRoot().RedirectStderr().Build());
883 if (status == 0) {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700884 MYLOGD("Screenshot saved on %s\n", real_path.c_str());
Felipe Lemebbaf3c12016-10-11 14:32:25 -0700885 } else {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700886 MYLOGE("Failed to take screenshot on %s\n", real_path.c_str());
Felipe Lemebbaf3c12016-10-11 14:32:25 -0700887 }
Felipe Lemee338bf62015-12-07 14:03:50 -0800888}
Mark Salyzynf55d4022015-12-11 07:32:31 -0800889
Felipe Leme0c80cf02016-01-05 13:25:34 -0800890bool is_dir(const char* pathname) {
891 struct stat info;
892 if (stat(pathname, &info) == -1) {
893 return false;
894 }
895 return S_ISDIR(info.st_mode);
896}
897
898time_t get_mtime(int fd, time_t default_mtime) {
899 struct stat info;
900 if (fstat(fd, &info) == -1) {
901 return default_mtime;
902 }
903 return info.st_mtime;
904}
905
Mark Salyzyn8c8130e2015-12-09 11:21:28 -0800906void dump_emmc_ecsd(const char *ext_csd_path) {
Mark Salyzyn290f4b92016-05-16 08:33:59 -0700907 // List of interesting offsets
Mark Salyzyn8c8130e2015-12-09 11:21:28 -0800908 struct hex {
909 char str[2];
Mark Salyzyn8c8130e2015-12-09 11:21:28 -0800910 };
Mark Salyzyn290f4b92016-05-16 08:33:59 -0700911 static const size_t EXT_CSD_REV = 192 * sizeof(hex);
912 static const size_t EXT_PRE_EOL_INFO = 267 * sizeof(hex);
913 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_A = 268 * sizeof(hex);
914 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_B = 269 * sizeof(hex);
915
916 std::string buffer;
917 if (!android::base::ReadFileToString(ext_csd_path, &buffer)) {
918 return;
919 }
Mark Salyzyn8c8130e2015-12-09 11:21:28 -0800920
Felipe Lemed8b94e52016-12-08 10:21:44 -0800921 printf("------ %s Extended CSD ------\n", ext_csd_path);
Mark Salyzyn8c8130e2015-12-09 11:21:28 -0800922
Mark Salyzyn290f4b92016-05-16 08:33:59 -0700923 if (buffer.length() < (EXT_CSD_REV + sizeof(hex))) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800924 printf("*** %s: truncated content %zu\n\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -0800925 return;
926 }
927
Mark Salyzyn290f4b92016-05-16 08:33:59 -0700928 int ext_csd_rev = 0;
929 std::string sub = buffer.substr(EXT_CSD_REV, sizeof(hex));
930 if (sscanf(sub.c_str(), "%2x", &ext_csd_rev) != 1) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800931 printf("*** %s: EXT_CSD_REV parse error \"%s\"\n\n", ext_csd_path, sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -0800932 return;
933 }
934
Mark Salyzyn290f4b92016-05-16 08:33:59 -0700935 static const char *ver_str[] = {
936 "4.0", "4.1", "4.2", "4.3", "Obsolete", "4.41", "4.5", "5.0"
937 };
Felipe Lemed8b94e52016-12-08 10:21:44 -0800938 printf("rev 1.%d (MMC %s)\n", ext_csd_rev,
939 (ext_csd_rev < (int)(sizeof(ver_str) / sizeof(ver_str[0]))) ? ver_str[ext_csd_rev]
940 : "Unknown");
Mark Salyzyn8c8130e2015-12-09 11:21:28 -0800941 if (ext_csd_rev < 7) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800942 printf("\n");
Mark Salyzyn8c8130e2015-12-09 11:21:28 -0800943 return;
944 }
945
Mark Salyzyn290f4b92016-05-16 08:33:59 -0700946 if (buffer.length() < (EXT_PRE_EOL_INFO + sizeof(hex))) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800947 printf("*** %s: truncated content %zu\n\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -0800948 return;
949 }
950
Mark Salyzyn290f4b92016-05-16 08:33:59 -0700951 int ext_pre_eol_info = 0;
952 sub = buffer.substr(EXT_PRE_EOL_INFO, sizeof(hex));
953 if (sscanf(sub.c_str(), "%2x", &ext_pre_eol_info) != 1) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800954 printf("*** %s: PRE_EOL_INFO parse error \"%s\"\n\n", ext_csd_path, sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -0800955 return;
956 }
Mark Salyzyn290f4b92016-05-16 08:33:59 -0700957
958 static const char *eol_str[] = {
959 "Undefined",
960 "Normal",
961 "Warning (consumed 80% of reserve)",
962 "Urgent (consumed 90% of reserve)"
963 };
Felipe Lemed8b94e52016-12-08 10:21:44 -0800964 printf(
965 "PRE_EOL_INFO %d (MMC %s)\n", ext_pre_eol_info,
Felipe Leme8f00ed02016-12-07 17:42:44 -0800966 eol_str[(ext_pre_eol_info < (int)(sizeof(eol_str) / sizeof(eol_str[0]))) ? ext_pre_eol_info
967 : 0]);
Mark Salyzyn8c8130e2015-12-09 11:21:28 -0800968
969 for (size_t lifetime = EXT_DEVICE_LIFE_TIME_EST_TYP_A;
970 lifetime <= EXT_DEVICE_LIFE_TIME_EST_TYP_B;
Mark Salyzyn290f4b92016-05-16 08:33:59 -0700971 lifetime += sizeof(hex)) {
Mark Salyzyn8c8130e2015-12-09 11:21:28 -0800972 int ext_device_life_time_est;
973 static const char *est_str[] = {
974 "Undefined",
975 "0-10% of device lifetime used",
976 "10-20% of device lifetime used",
977 "20-30% of device lifetime used",
978 "30-40% of device lifetime used",
979 "40-50% of device lifetime used",
980 "50-60% of device lifetime used",
981 "60-70% of device lifetime used",
982 "70-80% of device lifetime used",
983 "80-90% of device lifetime used",
984 "90-100% of device lifetime used",
985 "Exceeded the maximum estimated device lifetime",
986 };
987
Mark Salyzyn290f4b92016-05-16 08:33:59 -0700988 if (buffer.length() < (lifetime + sizeof(hex))) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800989 printf("*** %s: truncated content %zu\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -0800990 break;
991 }
992
993 ext_device_life_time_est = 0;
Mark Salyzyn290f4b92016-05-16 08:33:59 -0700994 sub = buffer.substr(lifetime, sizeof(hex));
995 if (sscanf(sub.c_str(), "%2x", &ext_device_life_time_est) != 1) {
Felipe Lemed8b94e52016-12-08 10:21:44 -0800996 printf("*** %s: DEVICE_LIFE_TIME_EST_TYP_%c parse error \"%s\"\n", ext_csd_path,
997 (unsigned)((lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) / sizeof(hex)) + 'A',
998 sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -0800999 continue;
1000 }
Felipe Lemed8b94e52016-12-08 10:21:44 -08001001 printf("DEVICE_LIFE_TIME_EST_TYP_%c %d (MMC %s)\n",
1002 (unsigned)((lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) / sizeof(hex)) + 'A',
1003 ext_device_life_time_est,
1004 est_str[(ext_device_life_time_est < (int)(sizeof(est_str) / sizeof(est_str[0])))
1005 ? ext_device_life_time_est
1006 : 0]);
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001007 }
1008
Felipe Lemed8b94e52016-12-08 10:21:44 -08001009 printf("\n");
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001010}