1 /*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #define LOG_TAG "dumpstate"
18
19 #include "dumpstate.h"
20
21 #include <dirent.h>
22 #include <fcntl.h>
23 #include <libgen.h>
24 #include <math.h>
25 #include <poll.h>
26 #include <signal.h>
27 #include <stdarg.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <sys/capability.h>
32 #include <sys/inotify.h>
33 #include <sys/klog.h>
34 #include <sys/prctl.h>
35 #include <sys/stat.h>
36 #include <sys/time.h>
37 #include <sys/wait.h>
38 #include <time.h>
39 #include <unistd.h>
40
41 #include <memory>
42 #include <set>
43 #include <string>
44 #include <vector>
45
46 #include <android-base/file.h>
47 #include <android-base/properties.h>
48 #include <android-base/stringprintf.h>
49 #include <android-base/strings.h>
50 #include <android-base/unique_fd.h>
51 #include <cutils/properties.h>
52 #include <cutils/sockets.h>
53 #include <log/log.h>
54 #include <private/android_filesystem_config.h>
55
56 #include "DumpstateInternal.h"
57
58 // TODO: remove once moved to namespace
59 using android::os::dumpstate::CommandOptions;
60 using android::os::dumpstate::DumpFileToFd;
61 using android::os::dumpstate::PropertiesHelper;
62
63 // Keep in sync with
64 // frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
65 static const int TRACE_DUMP_TIMEOUT_MS = 10000; // 10 seconds
66
67 /* Most simple commands have 10 as timeout, so 5 is a good estimate */
68 static const int32_t WEIGHT_FILE = 5;
69
70 // TODO: temporary variables and functions used during C++ refactoring
71 static Dumpstate& ds = Dumpstate::GetInstance();
RunCommand(const std::string & title,const std::vector<std::string> & full_command,const CommandOptions & options=CommandOptions::DEFAULT)72 static int RunCommand(const std::string& title, const std::vector<std::string>& full_command,
73 const CommandOptions& options = CommandOptions::DEFAULT) {
74 return ds.RunCommand(title, full_command, options);
75 }
76
77 // Reasonable value for max stats.
78 static const int STATS_MAX_N_RUNS = 1000;
79 static const long STATS_MAX_AVERAGE = 100000;
80
81 CommandOptions Dumpstate::DEFAULT_DUMPSYS = CommandOptions::WithTimeout(30).Build();
82
83 // TODO(111441001): Default DumpOptions to sensible values.
Dumpstate(const std::string & version)84 Dumpstate::Dumpstate(const std::string& version)
85 : pid_(getpid()),
86 options_(new Dumpstate::DumpOptions()),
87 version_(version),
88 now_(time(nullptr)) {
89 }
90
GetInstance()91 Dumpstate& Dumpstate::GetInstance() {
92 static Dumpstate singleton_(android::base::GetProperty("dumpstate.version", VERSION_CURRENT));
93 return singleton_;
94 }
95
DurationReporter(const std::string & title,bool logcat_only)96 DurationReporter::DurationReporter(const std::string& title, bool logcat_only)
97 : title_(title), logcat_only_(logcat_only) {
98 if (!title_.empty()) {
99 started_ = Nanotime();
100 }
101 }
102
~DurationReporter()103 DurationReporter::~DurationReporter() {
104 if (!title_.empty()) {
105 float elapsed = (float)(Nanotime() - started_) / NANOS_PER_SEC;
106 if (elapsed < .5f) {
107 return;
108 }
109 MYLOGD("Duration of '%s': %.2fs\n", title_.c_str(), elapsed);
110 if (logcat_only_) {
111 return;
112 }
113 // Use "Yoda grammar" to make it easier to grep|sort sections.
114 printf("------ %.3fs was the duration of '%s' ------\n", elapsed, title_.c_str());
115 }
116 }
117
118 const int32_t Progress::kDefaultMax = 5000;
119
Progress(const std::string & path)120 Progress::Progress(const std::string& path) : Progress(Progress::kDefaultMax, 1.1, path) {
121 }
122
Progress(int32_t initial_max,int32_t progress,float growth_factor)123 Progress::Progress(int32_t initial_max, int32_t progress, float growth_factor)
124 : Progress(initial_max, growth_factor, "") {
125 progress_ = progress;
126 }
127
Progress(int32_t initial_max,float growth_factor,const std::string & path)128 Progress::Progress(int32_t initial_max, float growth_factor, const std::string& path)
129 : initial_max_(initial_max),
130 progress_(0),
131 max_(initial_max),
132 growth_factor_(growth_factor),
133 n_runs_(0),
134 average_max_(0),
135 path_(path) {
136 if (!path_.empty()) {
137 Load();
138 }
139 }
140
Load()141 void Progress::Load() {
142 MYLOGD("Loading stats from %s\n", path_.c_str());
143 std::string content;
144 if (!android::base::ReadFileToString(path_, &content)) {
145 MYLOGI("Could not read stats from %s; using max of %d\n", path_.c_str(), max_);
146 return;
147 }
148 if (content.empty()) {
149 MYLOGE("No stats (empty file) on %s; using max of %d\n", path_.c_str(), max_);
150 return;
151 }
152 std::vector<std::string> lines = android::base::Split(content, "\n");
153
154 if (lines.size() < 1) {
155 MYLOGE("Invalid stats on file %s: not enough lines (%d). Using max of %d\n", path_.c_str(),
156 (int)lines.size(), max_);
157 return;
158 }
159 char* ptr;
160 n_runs_ = strtol(lines[0].c_str(), &ptr, 10);
161 average_max_ = strtol(ptr, nullptr, 10);
162 if (n_runs_ <= 0 || average_max_ <= 0 || n_runs_ > STATS_MAX_N_RUNS ||
163 average_max_ > STATS_MAX_AVERAGE) {
164 MYLOGE("Invalid stats line on file %s: %s\n", path_.c_str(), lines[0].c_str());
165 initial_max_ = Progress::kDefaultMax;
166 } else {
167 initial_max_ = average_max_;
168 }
169 max_ = initial_max_;
170
171 MYLOGI("Average max progress: %d in %d runs; estimated max: %d\n", average_max_, n_runs_, max_);
172 }
173
Save()174 void Progress::Save() {
175 int32_t total = n_runs_ * average_max_ + progress_;
176 int32_t runs = n_runs_ + 1;
177 int32_t average = floor(((float)total) / runs);
178 MYLOGI("Saving stats (total=%d, runs=%d, average=%d) on %s\n", total, runs, average,
179 path_.c_str());
180 if (path_.empty()) {
181 return;
182 }
183
184 std::string content = android::base::StringPrintf("%d %d\n", runs, average);
185 if (!android::base::WriteStringToFile(content, path_)) {
186 MYLOGE("Could not save stats on %s\n", path_.c_str());
187 }
188 }
189
Get() const190 int32_t Progress::Get() const {
191 return progress_;
192 }
193
Inc(int32_t delta_sec)194 bool Progress::Inc(int32_t delta_sec) {
195 bool changed = false;
196 if (delta_sec >= 0) {
197 progress_ += delta_sec;
198 if (progress_ > max_) {
199 int32_t old_max = max_;
200 max_ = floor((float)progress_ * growth_factor_);
201 MYLOGD("Adjusting max progress from %d to %d\n", old_max, max_);
202 changed = true;
203 }
204 }
205 return changed;
206 }
207
GetMax() const208 int32_t Progress::GetMax() const {
209 return max_;
210 }
211
GetInitialMax() const212 int32_t Progress::GetInitialMax() const {
213 return initial_max_;
214 }
215
Dump(int fd,const std::string & prefix) const216 void Progress::Dump(int fd, const std::string& prefix) const {
217 const char* pr = prefix.c_str();
218 dprintf(fd, "%sprogress: %d\n", pr, progress_);
219 dprintf(fd, "%smax: %d\n", pr, max_);
220 dprintf(fd, "%sinitial_max: %d\n", pr, initial_max_);
221 dprintf(fd, "%sgrowth_factor: %0.2f\n", pr, growth_factor_);
222 dprintf(fd, "%spath: %s\n", pr, path_.c_str());
223 dprintf(fd, "%sn_runs: %d\n", pr, n_runs_);
224 dprintf(fd, "%saverage_max: %d\n", pr, average_max_);
225 }
226
IsZipping() const227 bool Dumpstate::IsZipping() const {
228 return zip_writer_ != nullptr;
229 }
230
GetPath(const std::string & suffix) const231 std::string Dumpstate::GetPath(const std::string& suffix) const {
232 return GetPath(bugreport_internal_dir_, suffix);
233 }
234
GetPath(const std::string & directory,const std::string & suffix) const235 std::string Dumpstate::GetPath(const std::string& directory, const std::string& suffix) const {
236 return android::base::StringPrintf("%s/%s-%s%s", directory.c_str(), base_name_.c_str(),
237 name_.c_str(), suffix.c_str());
238 }
239
SetProgress(std::unique_ptr<Progress> progress)240 void Dumpstate::SetProgress(std::unique_ptr<Progress> progress) {
241 progress_ = std::move(progress);
242 }
243
for_each_userid(void (* func)(int),const char * header)244 void for_each_userid(void (*func)(int), const char *header) {
245 std::string title = header == nullptr ? "for_each_userid" : android::base::StringPrintf(
246 "for_each_userid(%s)", header);
247 DurationReporter duration_reporter(title);
248 if (PropertiesHelper::IsDryRun()) return;
249
250 DIR *d;
251 struct dirent *de;
252
253 if (header) printf("\n------ %s ------\n", header);
254 func(0);
255
256 if (!(d = opendir("/data/system/users"))) {
257 printf("Failed to open /data/system/users (%s)\n", strerror(errno));
258 return;
259 }
260
261 while ((de = readdir(d))) {
262 int userid;
263 if (de->d_type != DT_DIR || !(userid = atoi(de->d_name))) {
264 continue;
265 }
266 func(userid);
267 }
268
269 closedir(d);
270 }
271
__for_each_pid(void (* helper)(int,const char *,void *),const char * header,void * arg)272 static void __for_each_pid(void (*helper)(int, const char *, void *), const char *header, void *arg) {
273 DIR *d;
274 struct dirent *de;
275
276 if (!(d = opendir("/proc"))) {
277 printf("Failed to open /proc (%s)\n", strerror(errno));
278 return;
279 }
280
281 if (header) printf("\n------ %s ------\n", header);
282 while ((de = readdir(d))) {
283 if (ds.IsUserConsentDenied()) {
284 MYLOGE(
285 "Returning early because user denied consent to share bugreport with calling app.");
286 closedir(d);
287 return;
288 }
289 int pid;
290 int fd;
291 char cmdpath[255];
292 char cmdline[255];
293
294 if (!(pid = atoi(de->d_name))) {
295 continue;
296 }
297
298 memset(cmdline, 0, sizeof(cmdline));
299
300 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/cmdline", pid);
301 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
302 TEMP_FAILURE_RETRY(read(fd, cmdline, sizeof(cmdline) - 2));
303 close(fd);
304 if (cmdline[0]) {
305 helper(pid, cmdline, arg);
306 continue;
307 }
308 }
309
310 // if no cmdline, a kernel thread has comm
311 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/comm", pid);
312 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
313 TEMP_FAILURE_RETRY(read(fd, cmdline + 1, sizeof(cmdline) - 4));
314 close(fd);
315 if (cmdline[1]) {
316 cmdline[0] = '[';
317 size_t len = strcspn(cmdline, "\f\b\r\n");
318 cmdline[len] = ']';
319 cmdline[len+1] = '\0';
320 }
321 }
322 if (!cmdline[0]) {
323 strcpy(cmdline, "N/A");
324 }
325 helper(pid, cmdline, arg);
326 }
327
328 closedir(d);
329 }
330
for_each_pid_helper(int pid,const char * cmdline,void * arg)331 static void for_each_pid_helper(int pid, const char *cmdline, void *arg) {
332 for_each_pid_func *func = (for_each_pid_func*) arg;
333 func(pid, cmdline);
334 }
335
for_each_pid(for_each_pid_func func,const char * header)336 void for_each_pid(for_each_pid_func func, const char *header) {
337 std::string title = header == nullptr ? "for_each_pid"
338 : android::base::StringPrintf("for_each_pid(%s)", header);
339 DurationReporter duration_reporter(title);
340 if (PropertiesHelper::IsDryRun()) return;
341
342 __for_each_pid(for_each_pid_helper, header, (void *) func);
343 }
344
for_each_tid_helper(int pid,const char * cmdline,void * arg)345 static void for_each_tid_helper(int pid, const char *cmdline, void *arg) {
346 DIR *d;
347 struct dirent *de;
348 char taskpath[255];
349 for_each_tid_func *func = (for_each_tid_func *) arg;
350
351 snprintf(taskpath, sizeof(taskpath), "/proc/%d/task", pid);
352
353 if (!(d = opendir(taskpath))) {
354 printf("Failed to open %s (%s)\n", taskpath, strerror(errno));
355 return;
356 }
357
358 func(pid, pid, cmdline);
359
360 while ((de = readdir(d))) {
361 if (ds.IsUserConsentDenied()) {
362 MYLOGE(
363 "Returning early because user denied consent to share bugreport with calling app.");
364 closedir(d);
365 return;
366 }
367 int tid;
368 int fd;
369 char commpath[255];
370 char comm[255];
371
372 if (!(tid = atoi(de->d_name))) {
373 continue;
374 }
375
376 if (tid == pid)
377 continue;
378
379 snprintf(commpath, sizeof(commpath), "/proc/%d/comm", tid);
380 memset(comm, 0, sizeof(comm));
381 if ((fd = TEMP_FAILURE_RETRY(open(commpath, O_RDONLY | O_CLOEXEC))) < 0) {
382 strcpy(comm, "N/A");
383 } else {
384 char *c;
385 TEMP_FAILURE_RETRY(read(fd, comm, sizeof(comm) - 2));
386 close(fd);
387
388 c = strrchr(comm, '\n');
389 if (c) {
390 *c = '\0';
391 }
392 }
393 func(pid, tid, comm);
394 }
395
396 closedir(d);
397 }
398
for_each_tid(for_each_tid_func func,const char * header)399 void for_each_tid(for_each_tid_func func, const char *header) {
400 std::string title = header == nullptr ? "for_each_tid"
401 : android::base::StringPrintf("for_each_tid(%s)", header);
402 DurationReporter duration_reporter(title);
403
404 if (PropertiesHelper::IsDryRun()) return;
405
406 __for_each_pid(for_each_tid_helper, header, (void *) func);
407 }
408
show_wchan(int pid,int tid,const char * name)409 void show_wchan(int pid, int tid, const char *name) {
410 if (PropertiesHelper::IsDryRun()) return;
411
412 char path[255];
413 char buffer[255];
414 int fd, ret, save_errno;
415 char name_buffer[255];
416
417 memset(buffer, 0, sizeof(buffer));
418
419 snprintf(path, sizeof(path), "/proc/%d/wchan", tid);
420 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
421 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
422 return;
423 }
424
425 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
426 save_errno = errno;
427 close(fd);
428
429 if (ret < 0) {
430 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
431 return;
432 }
433
434 snprintf(name_buffer, sizeof(name_buffer), "%*s%s",
435 pid == tid ? 0 : 3, "", name);
436
437 printf("%-7d %-32s %s\n", tid, name_buffer, buffer);
438
439 return;
440 }
441
442 // print time in centiseconds
snprcent(char * buffer,size_t len,size_t spc,unsigned long long time)443 static void snprcent(char *buffer, size_t len, size_t spc,
444 unsigned long long time) {
445 static long hz; // cache discovered hz
446
447 if (hz <= 0) {
448 hz = sysconf(_SC_CLK_TCK);
449 if (hz <= 0) {
450 hz = 1000;
451 }
452 }
453
454 // convert to centiseconds
455 time = (time * 100 + (hz / 2)) / hz;
456
457 char str[16];
458
459 snprintf(str, sizeof(str), " %llu.%02u",
460 time / 100, (unsigned)(time % 100));
461 size_t offset = strlen(buffer);
462 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
463 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
464 }
465
466 // print permille as a percent
snprdec(char * buffer,size_t len,size_t spc,unsigned permille)467 static void snprdec(char *buffer, size_t len, size_t spc, unsigned permille) {
468 char str[16];
469
470 snprintf(str, sizeof(str), " %u.%u%%", permille / 10, permille % 10);
471 size_t offset = strlen(buffer);
472 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
473 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
474 }
475
show_showtime(int pid,const char * name)476 void show_showtime(int pid, const char *name) {
477 if (PropertiesHelper::IsDryRun()) return;
478
479 char path[255];
480 char buffer[1023];
481 int fd, ret, save_errno;
482
483 memset(buffer, 0, sizeof(buffer));
484
485 snprintf(path, sizeof(path), "/proc/%d/stat", pid);
486 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
487 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
488 return;
489 }
490
491 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
492 save_errno = errno;
493 close(fd);
494
495 if (ret < 0) {
496 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
497 return;
498 }
499
500 // field 14 is utime
501 // field 15 is stime
502 // field 42 is iotime
503 unsigned long long utime = 0, stime = 0, iotime = 0;
504 if (sscanf(buffer,
505 "%*u %*s %*s %*d %*d %*d %*d %*d %*d %*d %*d "
506 "%*d %*d %llu %llu %*d %*d %*d %*d %*d %*d "
507 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %*d "
508 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %llu ",
509 &utime, &stime, &iotime) != 3) {
510 return;
511 }
512
513 unsigned long long total = utime + stime;
514 if (!total) {
515 return;
516 }
517
518 unsigned permille = (iotime * 1000 + (total / 2)) / total;
519 if (permille > 1000) {
520 permille = 1000;
521 }
522
523 // try to beautify and stabilize columns at <80 characters
524 snprintf(buffer, sizeof(buffer), "%-6d%s", pid, name);
525 if ((name[0] != '[') || utime) {
526 snprcent(buffer, sizeof(buffer), 57, utime);
527 }
528 snprcent(buffer, sizeof(buffer), 65, stime);
529 if ((name[0] != '[') || iotime) {
530 snprcent(buffer, sizeof(buffer), 73, iotime);
531 }
532 if (iotime) {
533 snprdec(buffer, sizeof(buffer), 79, permille);
534 }
535 puts(buffer); // adds a trailing newline
536
537 return;
538 }
539
do_dmesg()540 void do_dmesg() {
541 const char *title = "KERNEL LOG (dmesg)";
542 DurationReporter duration_reporter(title);
543 printf("------ %s ------\n", title);
544
545 if (PropertiesHelper::IsDryRun()) return;
546
547 /* Get size of kernel buffer */
548 int size = klogctl(KLOG_SIZE_BUFFER, nullptr, 0);
549 if (size <= 0) {
550 printf("Unexpected klogctl return value: %d\n\n", size);
551 return;
552 }
553 char *buf = (char *) malloc(size + 1);
554 if (buf == nullptr) {
555 printf("memory allocation failed\n\n");
556 return;
557 }
558 int retval = klogctl(KLOG_READ_ALL, buf, size);
559 if (retval < 0) {
560 printf("klogctl failure\n\n");
561 free(buf);
562 return;
563 }
564 buf[retval] = '\0';
565 printf("%s\n\n", buf);
566 free(buf);
567 return;
568 }
569
do_showmap(int pid,const char * name)570 void do_showmap(int pid, const char *name) {
571 char title[255];
572 char arg[255];
573
574 snprintf(title, sizeof(title), "SHOW MAP %d (%s)", pid, name);
575 snprintf(arg, sizeof(arg), "%d", pid);
576 RunCommand(title, {"showmap", "-q", arg}, CommandOptions::AS_ROOT);
577 }
578
DumpFile(const std::string & title,const std::string & path)579 int Dumpstate::DumpFile(const std::string& title, const std::string& path) {
580 DurationReporter duration_reporter(title);
581
582 int status = DumpFileToFd(STDOUT_FILENO, title, path);
583
584 UpdateProgress(WEIGHT_FILE);
585
586 return status;
587 }
588
read_file_as_long(const char * path,long int * output)589 int read_file_as_long(const char *path, long int *output) {
590 int fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
591 if (fd < 0) {
592 int err = errno;
593 MYLOGE("Error opening file descriptor for %s: %s\n", path, strerror(err));
594 return -1;
595 }
596 char buffer[50];
597 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
598 if (bytes_read == -1) {
599 MYLOGE("Error reading file %s: %s\n", path, strerror(errno));
600 return -2;
601 }
602 if (bytes_read == 0) {
603 MYLOGE("File %s is empty\n", path);
604 return -3;
605 }
606 *output = atoi(buffer);
607 return 0;
608 }
609
610 /* calls skip to gate calling dump_from_fd recursively
611 * in the specified directory. dump_from_fd defaults to
612 * dump_file_from_fd above when set to NULL. skip defaults
613 * to false when set to NULL. dump_from_fd will always be
614 * called with title NULL.
615 */
dump_files(const std::string & title,const char * dir,bool (* skip)(const char * path),int (* dump_from_fd)(const char * title,const char * path,int fd))616 int dump_files(const std::string& title, const char* dir, bool (*skip)(const char* path),
617 int (*dump_from_fd)(const char* title, const char* path, int fd)) {
618 DurationReporter duration_reporter(title);
619 DIR *dirp;
620 struct dirent *d;
621 char *newpath = nullptr;
622 const char *slash = "/";
623 int retval = 0;
624
625 if (!title.empty()) {
626 printf("------ %s (%s) ------\n", title.c_str(), dir);
627 }
628 if (PropertiesHelper::IsDryRun()) return 0;
629
630 if (dir[strlen(dir) - 1] == '/') {
631 ++slash;
632 }
633 dirp = opendir(dir);
634 if (dirp == nullptr) {
635 retval = -errno;
636 MYLOGE("%s: %s\n", dir, strerror(errno));
637 return retval;
638 }
639
640 if (!dump_from_fd) {
641 dump_from_fd = dump_file_from_fd;
642 }
643 for (; ((d = readdir(dirp))); free(newpath), newpath = nullptr) {
644 if ((d->d_name[0] == '.')
645 && (((d->d_name[1] == '.') && (d->d_name[2] == '\0'))
646 || (d->d_name[1] == '\0'))) {
647 continue;
648 }
649 asprintf(&newpath, "%s%s%s%s", dir, slash, d->d_name,
650 (d->d_type == DT_DIR) ? "/" : "");
651 if (!newpath) {
652 retval = -errno;
653 continue;
654 }
655 if (skip && (*skip)(newpath)) {
656 continue;
657 }
658 if (d->d_type == DT_DIR) {
659 int ret = dump_files("", newpath, skip, dump_from_fd);
660 if (ret < 0) {
661 retval = ret;
662 }
663 continue;
664 }
665 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(newpath, O_RDONLY | O_NONBLOCK | O_CLOEXEC)));
666 if (fd.get() < 0) {
667 retval = -1;
668 printf("*** %s: %s\n", newpath, strerror(errno));
669 continue;
670 }
671 (*dump_from_fd)(nullptr, newpath, fd.get());
672 }
673 closedir(dirp);
674 if (!title.empty()) {
675 printf("\n");
676 }
677 return retval;
678 }
679
680 /* fd must have been opened with the flag O_NONBLOCK. With this flag set,
681 * it's possible to avoid issues where opening the file itself can get
682 * stuck.
683 */
dump_file_from_fd(const char * title,const char * path,int fd)684 int dump_file_from_fd(const char *title, const char *path, int fd) {
685 if (PropertiesHelper::IsDryRun()) return 0;
686
687 int flags = fcntl(fd, F_GETFL);
688 if (flags == -1) {
689 printf("*** %s: failed to get flags on fd %d: %s\n", path, fd, strerror(errno));
690 return -1;
691 } else if (!(flags & O_NONBLOCK)) {
692 printf("*** %s: fd must have O_NONBLOCK set.\n", path);
693 return -1;
694 }
695 return DumpFileFromFdToFd(title, path, fd, STDOUT_FILENO, PropertiesHelper::IsDryRun());
696 }
697
RunCommand(const std::string & title,const std::vector<std::string> & full_command,const CommandOptions & options)698 int Dumpstate::RunCommand(const std::string& title, const std::vector<std::string>& full_command,
699 const CommandOptions& options) {
700 DurationReporter duration_reporter(title);
701
702 int status = RunCommandToFd(STDOUT_FILENO, title, full_command, options);
703
704 /* TODO: for now we're simplifying the progress calculation by using the
705 * timeout as the weight. It's a good approximation for most cases, except when calling dumpsys,
706 * where its weight should be much higher proportionally to its timeout.
707 * Ideally, it should use a options.EstimatedDuration() instead...*/
708 UpdateProgress(options.Timeout());
709
710 return status;
711 }
712
RunDumpsys(const std::string & title,const std::vector<std::string> & dumpsys_args,const CommandOptions & options,long dumpsysTimeoutMs)713 void Dumpstate::RunDumpsys(const std::string& title, const std::vector<std::string>& dumpsys_args,
714 const CommandOptions& options, long dumpsysTimeoutMs) {
715 long timeout_ms = dumpsysTimeoutMs > 0 ? dumpsysTimeoutMs : options.TimeoutInMs();
716 std::vector<std::string> dumpsys = {"/system/bin/dumpsys", "-T", std::to_string(timeout_ms)};
717 dumpsys.insert(dumpsys.end(), dumpsys_args.begin(), dumpsys_args.end());
718 RunCommand(title, dumpsys, options);
719 }
720
open_socket(const char * service)721 int open_socket(const char *service) {
722 int s = android_get_control_socket(service);
723 if (s < 0) {
724 MYLOGE("android_get_control_socket(%s): %s\n", service, strerror(errno));
725 return -1;
726 }
727 fcntl(s, F_SETFD, FD_CLOEXEC);
728 if (listen(s, 4) < 0) {
729 MYLOGE("listen(control socket): %s\n", strerror(errno));
730 return -1;
731 }
732
733 struct sockaddr addr;
734 socklen_t alen = sizeof(addr);
735 int fd = accept(s, &addr, &alen);
736 if (fd < 0) {
737 MYLOGE("accept(control socket): %s\n", strerror(errno));
738 return -1;
739 }
740
741 return fd;
742 }
743
744 /* redirect output to a service control socket */
redirect_to_socket(FILE * redirect,const char * service)745 bool redirect_to_socket(FILE* redirect, const char* service) {
746 int fd = open_socket(service);
747 if (fd == -1) {
748 return false;
749 }
750 fflush(redirect);
751 // TODO: handle dup2 failure
752 TEMP_FAILURE_RETRY(dup2(fd, fileno(redirect)));
753 close(fd);
754 return true;
755 }
756
757 // TODO: should call is_valid_output_file and/or be merged into it.
create_parent_dirs(const char * path)758 void create_parent_dirs(const char *path) {
759 char *chp = const_cast<char *> (path);
760
761 /* skip initial slash */
762 if (chp[0] == '/')
763 chp++;
764
765 /* create leading directories, if necessary */
766 struct stat dir_stat;
767 while (chp && chp[0]) {
768 chp = strchr(chp, '/');
769 if (chp) {
770 *chp = 0;
771 if (stat(path, &dir_stat) == -1 || !S_ISDIR(dir_stat.st_mode)) {
772 MYLOGI("Creating directory %s\n", path);
773 if (mkdir(path, 0770)) { /* drwxrwx--- */
774 MYLOGE("Unable to create directory %s: %s\n", path, strerror(errno));
775 } else if (chown(path, AID_SHELL, AID_SHELL)) {
776 MYLOGE("Unable to change ownership of dir %s: %s\n", path, strerror(errno));
777 }
778 }
779 *chp++ = '/';
780 }
781 }
782 }
783
_redirect_to_file(FILE * redirect,char * path,int truncate_flag)784 bool _redirect_to_file(FILE* redirect, char* path, int truncate_flag) {
785 create_parent_dirs(path);
786
787 int fd = TEMP_FAILURE_RETRY(open(path,
788 O_WRONLY | O_CREAT | truncate_flag | O_CLOEXEC | O_NOFOLLOW,
789 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
790 if (fd < 0) {
791 MYLOGE("%s: %s\n", path, strerror(errno));
792 return false;
793 }
794
795 TEMP_FAILURE_RETRY(dup2(fd, fileno(redirect)));
796 close(fd);
797 return true;
798 }
799
redirect_to_file(FILE * redirect,char * path)800 bool redirect_to_file(FILE* redirect, char* path) {
801 return _redirect_to_file(redirect, path, O_TRUNC);
802 }
803
redirect_to_existing_file(FILE * redirect,char * path)804 bool redirect_to_existing_file(FILE* redirect, char* path) {
805 return _redirect_to_file(redirect, path, O_APPEND);
806 }
807
dump_route_tables()808 void dump_route_tables() {
809 DurationReporter duration_reporter("DUMP ROUTE TABLES");
810 if (PropertiesHelper::IsDryRun()) return;
811 const char* const RT_TABLES_PATH = "/data/misc/net/rt_tables";
812 ds.DumpFile("RT_TABLES", RT_TABLES_PATH);
813 FILE* fp = fopen(RT_TABLES_PATH, "re");
814 if (!fp) {
815 printf("*** %s: %s\n", RT_TABLES_PATH, strerror(errno));
816 return;
817 }
818 char table[16];
819 // Each line has an integer (the table number), a space, and a string (the table name). We only
820 // need the table number. It's a 32-bit unsigned number, so max 10 chars. Skip the table name.
821 // Add a fixed max limit so this doesn't go awry.
822 for (int i = 0; i < 64 && fscanf(fp, " %10s %*s", table) == 1; ++i) {
823 RunCommand("ROUTE TABLE IPv4", {"ip", "-4", "route", "show", "table", table});
824 RunCommand("ROUTE TABLE IPv6", {"ip", "-6", "route", "show", "table", table});
825 }
826 fclose(fp);
827 }
828
829 // TODO: make this function thread safe if sections are generated in parallel.
UpdateProgress(int32_t delta_sec)830 void Dumpstate::UpdateProgress(int32_t delta_sec) {
831 if (progress_ == nullptr) {
832 MYLOGE("UpdateProgress: progress_ not set\n");
833 return;
834 }
835
836 // Always update progess so stats can be tuned...
837 bool max_changed = progress_->Inc(delta_sec);
838
839 // ...but only notifiy listeners when necessary.
840 if (!options_->do_progress_updates) return;
841
842 int progress = progress_->Get();
843 int max = progress_->GetMax();
844
845 // adjusts max on the fly
846 if (max_changed && listener_ != nullptr) {
847 listener_->onMaxProgressUpdated(max);
848 }
849
850 int32_t last_update_delta = progress - last_updated_progress_;
851 if (last_updated_progress_ > 0 && last_update_delta < update_progress_threshold_) {
852 return;
853 }
854 last_updated_progress_ = progress;
855
856 if (control_socket_fd_ >= 0) {
857 dprintf(control_socket_fd_, "PROGRESS:%d/%d\n", progress, max);
858 fsync(control_socket_fd_);
859 }
860
861 int percent = 100 * progress / max;
862 if (listener_ != nullptr) {
863 if (percent % 5 == 0) {
864 // We don't want to spam logcat, so only log multiples of 5.
865 MYLOGD("Setting progress (%s): %d/%d (%d%%)\n", listener_name_.c_str(), progress, max,
866 percent);
867 } else {
868 // stderr is ignored on normal invocations, but useful when calling
869 // /system/bin/dumpstate directly for debuggging.
870 fprintf(stderr, "Setting progress (%s): %d/%d (%d%%)\n", listener_name_.c_str(),
871 progress, max, percent);
872 }
873 // TODO(b/111441001): Remove in favor of onProgress
874 listener_->onProgressUpdated(progress);
875
876 listener_->onProgress(percent);
877 }
878 }
879
TakeScreenshot(const std::string & path)880 void Dumpstate::TakeScreenshot(const std::string& path) {
881 const std::string& real_path = path.empty() ? screenshot_path_ : path;
882 int status =
883 RunCommand("", {"/system/bin/screencap", "-p", real_path},
884 CommandOptions::WithTimeout(10).Always().DropRoot().RedirectStderr().Build());
885 if (status == 0) {
886 MYLOGD("Screenshot saved on %s\n", real_path.c_str());
887 } else {
888 MYLOGE("Failed to take screenshot on %s\n", real_path.c_str());
889 }
890 }
891
is_dir(const char * pathname)892 bool is_dir(const char* pathname) {
893 struct stat info;
894 if (stat(pathname, &info) == -1) {
895 return false;
896 }
897 return S_ISDIR(info.st_mode);
898 }
899
get_mtime(int fd,time_t default_mtime)900 time_t get_mtime(int fd, time_t default_mtime) {
901 struct stat info;
902 if (fstat(fd, &info) == -1) {
903 return default_mtime;
904 }
905 return info.st_mtime;
906 }
907
dump_emmc_ecsd(const char * ext_csd_path)908 void dump_emmc_ecsd(const char *ext_csd_path) {
909 // List of interesting offsets
910 struct hex {
911 char str[2];
912 };
913 static const size_t EXT_CSD_REV = 192 * sizeof(hex);
914 static const size_t EXT_PRE_EOL_INFO = 267 * sizeof(hex);
915 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_A = 268 * sizeof(hex);
916 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_B = 269 * sizeof(hex);
917
918 std::string buffer;
919 if (!android::base::ReadFileToString(ext_csd_path, &buffer)) {
920 return;
921 }
922
923 printf("------ %s Extended CSD ------\n", ext_csd_path);
924
925 if (buffer.length() < (EXT_CSD_REV + sizeof(hex))) {
926 printf("*** %s: truncated content %zu\n\n", ext_csd_path, buffer.length());
927 return;
928 }
929
930 int ext_csd_rev = 0;
931 std::string sub = buffer.substr(EXT_CSD_REV, sizeof(hex));
932 if (sscanf(sub.c_str(), "%2x", &ext_csd_rev) != 1) {
933 printf("*** %s: EXT_CSD_REV parse error \"%s\"\n\n", ext_csd_path, sub.c_str());
934 return;
935 }
936
937 static const char *ver_str[] = {
938 "4.0", "4.1", "4.2", "4.3", "Obsolete", "4.41", "4.5", "5.0"
939 };
940 printf("rev 1.%d (MMC %s)\n", ext_csd_rev,
941 (ext_csd_rev < (int)(sizeof(ver_str) / sizeof(ver_str[0]))) ? ver_str[ext_csd_rev]
942 : "Unknown");
943 if (ext_csd_rev < 7) {
944 printf("\n");
945 return;
946 }
947
948 if (buffer.length() < (EXT_PRE_EOL_INFO + sizeof(hex))) {
949 printf("*** %s: truncated content %zu\n\n", ext_csd_path, buffer.length());
950 return;
951 }
952
953 int ext_pre_eol_info = 0;
954 sub = buffer.substr(EXT_PRE_EOL_INFO, sizeof(hex));
955 if (sscanf(sub.c_str(), "%2x", &ext_pre_eol_info) != 1) {
956 printf("*** %s: PRE_EOL_INFO parse error \"%s\"\n\n", ext_csd_path, sub.c_str());
957 return;
958 }
959
960 static const char *eol_str[] = {
961 "Undefined",
962 "Normal",
963 "Warning (consumed 80% of reserve)",
964 "Urgent (consumed 90% of reserve)"
965 };
966 printf(
967 "PRE_EOL_INFO %d (MMC %s)\n", ext_pre_eol_info,
968 eol_str[(ext_pre_eol_info < (int)(sizeof(eol_str) / sizeof(eol_str[0]))) ? ext_pre_eol_info
969 : 0]);
970
971 for (size_t lifetime = EXT_DEVICE_LIFE_TIME_EST_TYP_A;
972 lifetime <= EXT_DEVICE_LIFE_TIME_EST_TYP_B;
973 lifetime += sizeof(hex)) {
974 int ext_device_life_time_est;
975 static const char *est_str[] = {
976 "Undefined",
977 "0-10% of device lifetime used",
978 "10-20% of device lifetime used",
979 "20-30% of device lifetime used",
980 "30-40% of device lifetime used",
981 "40-50% of device lifetime used",
982 "50-60% of device lifetime used",
983 "60-70% of device lifetime used",
984 "70-80% of device lifetime used",
985 "80-90% of device lifetime used",
986 "90-100% of device lifetime used",
987 "Exceeded the maximum estimated device lifetime",
988 };
989
990 if (buffer.length() < (lifetime + sizeof(hex))) {
991 printf("*** %s: truncated content %zu\n", ext_csd_path, buffer.length());
992 break;
993 }
994
995 ext_device_life_time_est = 0;
996 sub = buffer.substr(lifetime, sizeof(hex));
997 if (sscanf(sub.c_str(), "%2x", &ext_device_life_time_est) != 1) {
998 printf("*** %s: DEVICE_LIFE_TIME_EST_TYP_%c parse error \"%s\"\n", ext_csd_path,
999 (unsigned)((lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) / sizeof(hex)) + 'A',
1000 sub.c_str());
1001 continue;
1002 }
1003 printf("DEVICE_LIFE_TIME_EST_TYP_%c %d (MMC %s)\n",
1004 (unsigned)((lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) / sizeof(hex)) + 'A',
1005 ext_device_life_time_est,
1006 est_str[(ext_device_life_time_est < (int)(sizeof(est_str) / sizeof(est_str[0])))
1007 ? ext_device_life_time_est
1008 : 0]);
1009 }
1010
1011 printf("\n");
1012 }
1013