2 * Copyright (C) 2008 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #define LOG_TAG "dumpstate"
19 #include "dumpstate.h"
31 #include <sys/capability.h>
32 #include <sys/inotify.h>
34 #include <sys/prctl.h>
44 #include <android-base/file.h>
45 #include <android-base/properties.h>
46 #include <android-base/stringprintf.h>
47 #include <android-base/strings.h>
48 #include <cutils/properties.h>
49 #include <cutils/sockets.h>
50 #include <debuggerd/client.h>
52 #include <private/android_filesystem_config.h>
54 #include "DumpstateInternal.h"
56 // TODO: remove once moved to namespace
57 using android::os::dumpstate::CommandOptions;
58 using android::os::dumpstate::DumpFileToFd;
59 using android::os::dumpstate::PropertiesHelper;
61 static const int TRACE_DUMP_TIMEOUT_MS = 10000; // 10 seconds
63 /* Most simple commands have 10 as timeout, so 5 is a good estimate */
64 static const int32_t WEIGHT_FILE = 5;
66 // TODO: temporary variables and functions used during C++ refactoring
67 static Dumpstate& ds = Dumpstate::GetInstance();
68 static int RunCommand(const std::string& title, const std::vector<std::string>& full_command,
69 const CommandOptions& options = CommandOptions::DEFAULT) {
70 return ds.RunCommand(title, full_command, options);
73 /* list of native processes to include in the native dumps */
74 // This matches the /proc/pid/exe link instead of /proc/pid/cmdline.
75 static const char* native_processes_to_dump[] = {
76 "/system/bin/audioserver",
77 "/system/bin/cameraserver",
78 "/system/bin/drmserver",
79 "/system/bin/mediacodec", // media.codec
80 "/system/bin/mediadrmserver",
81 "/system/bin/mediaextractor", // media.extractor
82 "/system/bin/mediaserver",
84 "/system/bin/surfaceflinger",
85 "/system/bin/vehicle_network_service",
89 // Reasonable value for max stats.
90 static const int STATS_MAX_N_RUNS = 1000;
91 static const long STATS_MAX_AVERAGE = 100000;
93 CommandOptions Dumpstate::DEFAULT_DUMPSYS = CommandOptions::WithTimeout(30).Build();
95 Dumpstate::Dumpstate(const std::string& version)
96 : pid_(getpid()), version_(version), now_(time(nullptr)) {
99 Dumpstate& Dumpstate::GetInstance() {
100 static Dumpstate singleton_(android::base::GetProperty("dumpstate.version", VERSION_CURRENT));
104 DurationReporter::DurationReporter(const std::string& title, bool log_only)
105 : title_(title), log_only_(log_only) {
106 if (!title_.empty()) {
107 started_ = Nanotime();
111 DurationReporter::~DurationReporter() {
112 if (!title_.empty()) {
113 uint64_t elapsed = Nanotime() - started_;
115 MYLOGD("Duration of '%s': %.3fs\n", title_.c_str(), (float)elapsed / NANOS_PER_SEC);
117 // Use "Yoda grammar" to make it easier to grep|sort sections.
118 printf("------ %.3fs was the duration of '%s' ------\n", (float)elapsed / NANOS_PER_SEC,
124 const int32_t Progress::kDefaultMax = 5000;
126 Progress::Progress(const std::string& path) : Progress(Progress::kDefaultMax, 1.1, path) {
129 Progress::Progress(int32_t initial_max, int32_t progress, float growth_factor)
130 : Progress(initial_max, growth_factor, "") {
131 progress_ = progress;
134 Progress::Progress(int32_t initial_max, float growth_factor, const std::string& path)
135 : initial_max_(initial_max),
138 growth_factor_(growth_factor),
142 if (!path_.empty()) {
147 void Progress::Load() {
148 MYLOGD("Loading stats from %s\n", path_.c_str());
150 if (!android::base::ReadFileToString(path_, &content)) {
151 MYLOGI("Could not read stats from %s; using max of %d\n", path_.c_str(), max_);
154 if (content.empty()) {
155 MYLOGE("No stats (empty file) on %s; using max of %d\n", path_.c_str(), max_);
158 std::vector<std::string> lines = android::base::Split(content, "\n");
160 if (lines.size() < 1) {
161 MYLOGE("Invalid stats on file %s: not enough lines (%d). Using max of %d\n", path_.c_str(),
162 (int)lines.size(), max_);
166 n_runs_ = strtol(lines[0].c_str(), &ptr, 10);
167 average_max_ = strtol(ptr, nullptr, 10);
168 if (n_runs_ <= 0 || average_max_ <= 0 || n_runs_ > STATS_MAX_N_RUNS ||
169 average_max_ > STATS_MAX_AVERAGE) {
170 MYLOGE("Invalid stats line on file %s: %s\n", path_.c_str(), lines[0].c_str());
171 initial_max_ = Progress::kDefaultMax;
173 initial_max_ = average_max_;
177 MYLOGI("Average max progress: %d in %d runs; estimated max: %d\n", average_max_, n_runs_, max_);
180 void Progress::Save() {
181 int32_t total = n_runs_ * average_max_ + progress_;
182 int32_t runs = n_runs_ + 1;
183 int32_t average = floor(((float)total) / runs);
184 MYLOGI("Saving stats (total=%d, runs=%d, average=%d) on %s\n", total, runs, average,
190 std::string content = android::base::StringPrintf("%d %d\n", runs, average);
191 if (!android::base::WriteStringToFile(content, path_)) {
192 MYLOGE("Could not save stats on %s\n", path_.c_str());
196 int32_t Progress::Get() const {
200 bool Progress::Inc(int32_t delta) {
201 bool changed = false;
204 if (progress_ > max_) {
205 int32_t old_max = max_;
206 max_ = floor((float)progress_ * growth_factor_);
207 MYLOGD("Adjusting max progress from %d to %d\n", old_max, max_);
214 int32_t Progress::GetMax() const {
218 int32_t Progress::GetInitialMax() const {
222 void Progress::Dump(int fd, const std::string& prefix) const {
223 const char* pr = prefix.c_str();
224 dprintf(fd, "%sprogress: %d\n", pr, progress_);
225 dprintf(fd, "%smax: %d\n", pr, max_);
226 dprintf(fd, "%sinitial_max: %d\n", pr, initial_max_);
227 dprintf(fd, "%sgrowth_factor: %0.2f\n", pr, growth_factor_);
228 dprintf(fd, "%spath: %s\n", pr, path_.c_str());
229 dprintf(fd, "%sn_runs: %d\n", pr, n_runs_);
230 dprintf(fd, "%saverage_max: %d\n", pr, average_max_);
233 bool Dumpstate::IsZipping() const {
234 return zip_writer_ != nullptr;
237 std::string Dumpstate::GetPath(const std::string& suffix) const {
238 return android::base::StringPrintf("%s/%s-%s%s", bugreport_dir_.c_str(), base_name_.c_str(),
239 name_.c_str(), suffix.c_str());
242 void Dumpstate::SetProgress(std::unique_ptr<Progress> progress) {
243 progress_ = std::move(progress);
246 void for_each_userid(void (*func)(int), const char *header) {
247 std::string title = header == nullptr ? "for_each_userid" : android::base::StringPrintf(
248 "for_each_userid(%s)", header);
249 DurationReporter duration_reporter(title);
250 if (PropertiesHelper::IsDryRun()) return;
255 if (header) printf("\n------ %s ------\n", header);
258 if (!(d = opendir("/data/system/users"))) {
259 printf("Failed to open /data/system/users (%s)\n", strerror(errno));
263 while ((de = readdir(d))) {
265 if (de->d_type != DT_DIR || !(userid = atoi(de->d_name))) {
274 static void __for_each_pid(void (*helper)(int, const char *, void *), const char *header, void *arg) {
278 if (!(d = opendir("/proc"))) {
279 printf("Failed to open /proc (%s)\n", strerror(errno));
283 if (header) printf("\n------ %s ------\n", header);
284 while ((de = readdir(d))) {
290 if (!(pid = atoi(de->d_name))) {
294 memset(cmdline, 0, sizeof(cmdline));
296 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/cmdline", pid);
297 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
298 TEMP_FAILURE_RETRY(read(fd, cmdline, sizeof(cmdline) - 2));
301 helper(pid, cmdline, arg);
306 // if no cmdline, a kernel thread has comm
307 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/comm", pid);
308 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
309 TEMP_FAILURE_RETRY(read(fd, cmdline + 1, sizeof(cmdline) - 4));
313 size_t len = strcspn(cmdline, "\f\b\r\n");
315 cmdline[len+1] = '\0';
319 strcpy(cmdline, "N/A");
321 helper(pid, cmdline, arg);
327 static void for_each_pid_helper(int pid, const char *cmdline, void *arg) {
328 for_each_pid_func *func = (for_each_pid_func*) arg;
332 void for_each_pid(for_each_pid_func func, const char *header) {
333 std::string title = header == nullptr ? "for_each_pid"
334 : android::base::StringPrintf("for_each_pid(%s)", header);
335 DurationReporter duration_reporter(title);
336 if (PropertiesHelper::IsDryRun()) return;
338 __for_each_pid(for_each_pid_helper, header, (void *) func);
341 static void for_each_tid_helper(int pid, const char *cmdline, void *arg) {
345 for_each_tid_func *func = (for_each_tid_func *) arg;
347 snprintf(taskpath, sizeof(taskpath), "/proc/%d/task", pid);
349 if (!(d = opendir(taskpath))) {
350 printf("Failed to open %s (%s)\n", taskpath, strerror(errno));
354 func(pid, pid, cmdline);
356 while ((de = readdir(d))) {
362 if (!(tid = atoi(de->d_name))) {
369 snprintf(commpath, sizeof(commpath), "/proc/%d/comm", tid);
370 memset(comm, 0, sizeof(comm));
371 if ((fd = TEMP_FAILURE_RETRY(open(commpath, O_RDONLY | O_CLOEXEC))) < 0) {
375 TEMP_FAILURE_RETRY(read(fd, comm, sizeof(comm) - 2));
378 c = strrchr(comm, '\n');
383 func(pid, tid, comm);
389 void for_each_tid(for_each_tid_func func, const char *header) {
390 std::string title = header == nullptr ? "for_each_tid"
391 : android::base::StringPrintf("for_each_tid(%s)", header);
392 DurationReporter duration_reporter(title);
394 if (PropertiesHelper::IsDryRun()) return;
396 __for_each_pid(for_each_tid_helper, header, (void *) func);
399 void show_wchan(int pid, int tid, const char *name) {
400 if (PropertiesHelper::IsDryRun()) return;
404 int fd, ret, save_errno;
405 char name_buffer[255];
407 memset(buffer, 0, sizeof(buffer));
409 snprintf(path, sizeof(path), "/proc/%d/wchan", tid);
410 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
411 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
415 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
420 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
424 snprintf(name_buffer, sizeof(name_buffer), "%*s%s",
425 pid == tid ? 0 : 3, "", name);
427 printf("%-7d %-32s %s\n", tid, name_buffer, buffer);
432 // print time in centiseconds
433 static void snprcent(char *buffer, size_t len, size_t spc,
434 unsigned long long time) {
435 static long hz; // cache discovered hz
438 hz = sysconf(_SC_CLK_TCK);
444 // convert to centiseconds
445 time = (time * 100 + (hz / 2)) / hz;
449 snprintf(str, sizeof(str), " %llu.%02u",
450 time / 100, (unsigned)(time % 100));
451 size_t offset = strlen(buffer);
452 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
453 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
456 // print permille as a percent
457 static void snprdec(char *buffer, size_t len, size_t spc, unsigned permille) {
460 snprintf(str, sizeof(str), " %u.%u%%", permille / 10, permille % 10);
461 size_t offset = strlen(buffer);
462 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
463 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
466 void show_showtime(int pid, const char *name) {
467 if (PropertiesHelper::IsDryRun()) return;
471 int fd, ret, save_errno;
473 memset(buffer, 0, sizeof(buffer));
475 snprintf(path, sizeof(path), "/proc/%d/stat", pid);
476 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
477 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
481 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
486 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
492 // field 42 is iotime
493 unsigned long long utime = 0, stime = 0, iotime = 0;
495 "%*u %*s %*s %*d %*d %*d %*d %*d %*d %*d %*d "
496 "%*d %*d %llu %llu %*d %*d %*d %*d %*d %*d "
497 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %*d "
498 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %llu ",
499 &utime, &stime, &iotime) != 3) {
503 unsigned long long total = utime + stime;
508 unsigned permille = (iotime * 1000 + (total / 2)) / total;
509 if (permille > 1000) {
513 // try to beautify and stabilize columns at <80 characters
514 snprintf(buffer, sizeof(buffer), "%-6d%s", pid, name);
515 if ((name[0] != '[') || utime) {
516 snprcent(buffer, sizeof(buffer), 57, utime);
518 snprcent(buffer, sizeof(buffer), 65, stime);
519 if ((name[0] != '[') || iotime) {
520 snprcent(buffer, sizeof(buffer), 73, iotime);
523 snprdec(buffer, sizeof(buffer), 79, permille);
525 puts(buffer); // adds a trailing newline
531 const char *title = "KERNEL LOG (dmesg)";
532 DurationReporter duration_reporter(title);
533 printf("------ %s ------\n", title);
535 if (PropertiesHelper::IsDryRun()) return;
537 /* Get size of kernel buffer */
538 int size = klogctl(KLOG_SIZE_BUFFER, NULL, 0);
540 printf("Unexpected klogctl return value: %d\n\n", size);
543 char *buf = (char *) malloc(size + 1);
545 printf("memory allocation failed\n\n");
548 int retval = klogctl(KLOG_READ_ALL, buf, size);
550 printf("klogctl failure\n\n");
555 printf("%s\n\n", buf);
560 void do_showmap(int pid, const char *name) {
564 snprintf(title, sizeof(title), "SHOW MAP %d (%s)", pid, name);
565 snprintf(arg, sizeof(arg), "%d", pid);
566 RunCommand(title, {"showmap", "-q", arg}, CommandOptions::AS_ROOT);
569 int Dumpstate::DumpFile(const std::string& title, const std::string& path) {
570 DurationReporter duration_reporter(title);
572 int status = DumpFileToFd(STDOUT_FILENO, title, path);
574 UpdateProgress(WEIGHT_FILE);
579 int read_file_as_long(const char *path, long int *output) {
580 int fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
583 MYLOGE("Error opening file descriptor for %s: %s\n", path, strerror(err));
587 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
588 if (bytes_read == -1) {
589 MYLOGE("Error reading file %s: %s\n", path, strerror(errno));
592 if (bytes_read == 0) {
593 MYLOGE("File %s is empty\n", path);
596 *output = atoi(buffer);
600 /* calls skip to gate calling dump_from_fd recursively
601 * in the specified directory. dump_from_fd defaults to
602 * dump_file_from_fd above when set to NULL. skip defaults
603 * to false when set to NULL. dump_from_fd will always be
604 * called with title NULL.
606 int dump_files(const std::string& title, const char* dir, bool (*skip)(const char* path),
607 int (*dump_from_fd)(const char* title, const char* path, int fd)) {
608 DurationReporter duration_reporter(title);
611 char *newpath = NULL;
612 const char *slash = "/";
615 if (!title.empty()) {
616 printf("------ %s (%s) ------\n", title.c_str(), dir);
618 if (PropertiesHelper::IsDryRun()) return 0;
620 if (dir[strlen(dir) - 1] == '/') {
626 MYLOGE("%s: %s\n", dir, strerror(errno));
631 dump_from_fd = dump_file_from_fd;
633 for (; ((d = readdir(dirp))); free(newpath), newpath = NULL) {
634 if ((d->d_name[0] == '.')
635 && (((d->d_name[1] == '.') && (d->d_name[2] == '\0'))
636 || (d->d_name[1] == '\0'))) {
639 asprintf(&newpath, "%s%s%s%s", dir, slash, d->d_name,
640 (d->d_type == DT_DIR) ? "/" : "");
645 if (skip && (*skip)(newpath)) {
648 if (d->d_type == DT_DIR) {
649 int ret = dump_files("", newpath, skip, dump_from_fd);
655 fd = TEMP_FAILURE_RETRY(open(newpath, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
658 printf("*** %s: %s\n", newpath, strerror(errno));
661 (*dump_from_fd)(NULL, newpath, fd);
664 if (!title.empty()) {
670 /* fd must have been opened with the flag O_NONBLOCK. With this flag set,
671 * it's possible to avoid issues where opening the file itself can get
674 int dump_file_from_fd(const char *title, const char *path, int fd) {
675 if (PropertiesHelper::IsDryRun()) return 0;
677 int flags = fcntl(fd, F_GETFL);
679 printf("*** %s: failed to get flags on fd %d: %s\n", path, fd, strerror(errno));
682 } else if (!(flags & O_NONBLOCK)) {
683 printf("*** %s: fd must have O_NONBLOCK set.\n", path);
687 return DumpFileFromFdToFd(title, path, fd, STDOUT_FILENO, PropertiesHelper::IsDryRun());
690 int Dumpstate::RunCommand(const std::string& title, const std::vector<std::string>& full_command,
691 const CommandOptions& options) {
692 DurationReporter duration_reporter(title);
694 int status = RunCommandToFd(STDOUT_FILENO, title, full_command, options);
696 /* TODO: for now we're simplifying the progress calculation by using the
697 * timeout as the weight. It's a good approximation for most cases, except when calling dumpsys,
698 * where its weight should be much higher proportionally to its timeout.
699 * Ideally, it should use a options.EstimatedDuration() instead...*/
700 UpdateProgress(options.Timeout());
705 void Dumpstate::RunDumpsys(const std::string& title, const std::vector<std::string>& dumpsys_args,
706 const CommandOptions& options, long dumpsysTimeout) {
707 long timeout = dumpsysTimeout > 0 ? dumpsysTimeout : options.Timeout();
708 std::vector<std::string> dumpsys = {"/system/bin/dumpsys", "-t", std::to_string(timeout)};
709 dumpsys.insert(dumpsys.end(), dumpsys_args.begin(), dumpsys_args.end());
710 RunCommand(title, dumpsys, options);
713 int open_socket(const char *service) {
714 int s = android_get_control_socket(service);
716 MYLOGE("android_get_control_socket(%s): %s\n", service, strerror(errno));
719 fcntl(s, F_SETFD, FD_CLOEXEC);
720 if (listen(s, 4) < 0) {
721 MYLOGE("listen(control socket): %s\n", strerror(errno));
725 struct sockaddr addr;
726 socklen_t alen = sizeof(addr);
727 int fd = accept(s, &addr, &alen);
729 MYLOGE("accept(control socket): %s\n", strerror(errno));
736 /* redirect output to a service control socket */
737 void redirect_to_socket(FILE *redirect, const char *service) {
738 int fd = open_socket(service);
740 dup2(fd, fileno(redirect));
744 // TODO: should call is_valid_output_file and/or be merged into it.
745 void create_parent_dirs(const char *path) {
746 char *chp = const_cast<char *> (path);
748 /* skip initial slash */
752 /* create leading directories, if necessary */
753 struct stat dir_stat;
754 while (chp && chp[0]) {
755 chp = strchr(chp, '/');
758 if (stat(path, &dir_stat) == -1 || !S_ISDIR(dir_stat.st_mode)) {
759 MYLOGI("Creating directory %s\n", path);
760 if (mkdir(path, 0770)) { /* drwxrwx--- */
761 MYLOGE("Unable to create directory %s: %s\n", path, strerror(errno));
762 } else if (chown(path, AID_SHELL, AID_SHELL)) {
763 MYLOGE("Unable to change ownership of dir %s: %s\n", path, strerror(errno));
771 void _redirect_to_file(FILE *redirect, char *path, int truncate_flag) {
772 create_parent_dirs(path);
774 int fd = TEMP_FAILURE_RETRY(open(path,
775 O_WRONLY | O_CREAT | truncate_flag | O_CLOEXEC | O_NOFOLLOW,
776 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
778 MYLOGE("%s: %s\n", path, strerror(errno));
782 TEMP_FAILURE_RETRY(dup2(fd, fileno(redirect)));
786 void redirect_to_file(FILE *redirect, char *path) {
787 _redirect_to_file(redirect, path, O_TRUNC);
790 void redirect_to_existing_file(FILE *redirect, char *path) {
791 _redirect_to_file(redirect, path, O_APPEND);
794 static bool should_dump_native_traces(const char* path) {
795 for (const char** p = native_processes_to_dump; *p; p++) {
796 if (!strcmp(*p, path)) {
803 /* dump Dalvik and native stack traces, return the trace file location (NULL if none) */
804 const char *dump_traces() {
805 DurationReporter duration_reporter("DUMP TRACES");
807 const char* result = nullptr;
809 std::string traces_path = android::base::GetProperty("dalvik.vm.stack-trace-file", "");
810 if (traces_path.empty()) return nullptr;
812 /* move the old traces.txt (if any) out of the way temporarily */
813 std::string anrtraces_path = traces_path + ".anr";
814 if (rename(traces_path.c_str(), anrtraces_path.c_str()) && errno != ENOENT) {
815 MYLOGE("rename(%s, %s): %s\n", traces_path.c_str(), anrtraces_path.c_str(), strerror(errno));
816 return nullptr; // Can't rename old traces.txt -- no permission? -- leave it alone instead
819 /* create a new, empty traces.txt file to receive stack dumps */
820 int fd = TEMP_FAILURE_RETRY(
821 open(traces_path.c_str(), O_CREAT | O_WRONLY | O_APPEND | O_TRUNC | O_NOFOLLOW | O_CLOEXEC,
822 0666)); /* -rw-rw-rw- */
824 MYLOGE("%s: %s\n", traces_path.c_str(), strerror(errno));
827 int chmod_ret = fchmod(fd, 0666);
829 MYLOGE("fchmod on %s failed: %s\n", traces_path.c_str(), strerror(errno));
834 /* Variables below must be initialized before 'goto' statements */
835 int dalvik_found = 0;
838 /* walk /proc and kill -QUIT all Dalvik processes */
839 DIR *proc = opendir("/proc");
841 MYLOGE("/proc: %s\n", strerror(errno));
845 /* use inotify to find when processes are done dumping */
846 ifd = inotify_init();
848 MYLOGE("inotify_init: %s\n", strerror(errno));
852 wfd = inotify_add_watch(ifd, traces_path.c_str(), IN_CLOSE_WRITE);
854 MYLOGE("inotify_add_watch(%s): %s\n", traces_path.c_str(), strerror(errno));
855 goto error_close_ifd;
859 while ((d = readdir(proc))) {
860 int pid = atoi(d->d_name);
861 if (pid <= 0) continue;
865 snprintf(path, sizeof(path), "/proc/%d/exe", pid);
866 ssize_t len = readlink(path, data, sizeof(data) - 1);
872 if (!strncmp(data, "/system/bin/app_process", strlen("/system/bin/app_process"))) {
873 /* skip zygote -- it won't dump its stack anyway */
874 snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
875 int cfd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC));
876 len = read(cfd, data, sizeof(data) - 1);
882 if (!strncmp(data, "zygote", strlen("zygote"))) {
887 uint64_t start = Nanotime();
888 if (kill(pid, SIGQUIT)) {
889 MYLOGE("kill(%d, SIGQUIT): %s\n", pid, strerror(errno));
893 /* wait for the writable-close notification from inotify */
894 struct pollfd pfd = { ifd, POLLIN, 0 };
895 int ret = poll(&pfd, 1, TRACE_DUMP_TIMEOUT_MS);
897 MYLOGE("poll: %s\n", strerror(errno));
898 } else if (ret == 0) {
899 MYLOGE("warning: timed out dumping pid %d\n", pid);
901 struct inotify_event ie;
902 read(ifd, &ie, sizeof(ie));
905 if (lseek(fd, 0, SEEK_END) < 0) {
906 MYLOGE("lseek: %s\n", strerror(errno));
908 dprintf(fd, "[dump dalvik stack %d: %.3fs elapsed]\n", pid,
909 (float)(Nanotime() - start) / NANOS_PER_SEC);
911 } else if (should_dump_native_traces(data)) {
912 /* dump native process if appropriate */
913 if (lseek(fd, 0, SEEK_END) < 0) {
914 MYLOGE("lseek: %s\n", strerror(errno));
916 static uint16_t timeout_failures = 0;
917 uint64_t start = Nanotime();
919 /* If 3 backtrace dumps fail in a row, consider debuggerd dead. */
920 if (timeout_failures == 3) {
921 dprintf(fd, "too many stack dump failures, skipping...\n");
922 } else if (dump_backtrace_to_file_timeout(pid, fd, 20) == -1) {
923 dprintf(fd, "dumping failed, likely due to a timeout\n");
926 timeout_failures = 0;
928 dprintf(fd, "[dump native stack %d: %.3fs elapsed]\n", pid,
929 (float)(Nanotime() - start) / NANOS_PER_SEC);
934 if (dalvik_found == 0) {
935 MYLOGE("Warning: no Dalvik processes found to dump stacks\n");
938 static std::string dumptraces_path = android::base::StringPrintf(
939 "%s/bugreport-%s", dirname(traces_path.c_str()), basename(traces_path.c_str()));
940 if (rename(traces_path.c_str(), dumptraces_path.c_str())) {
941 MYLOGE("rename(%s, %s): %s\n", traces_path.c_str(), dumptraces_path.c_str(),
943 goto error_close_ifd;
945 result = dumptraces_path.c_str();
947 /* replace the saved [ANR] traces.txt file */
948 rename(anrtraces_path.c_str(), traces_path.c_str());
957 void dump_route_tables() {
958 DurationReporter duration_reporter("DUMP ROUTE TABLES");
959 if (PropertiesHelper::IsDryRun()) return;
960 const char* const RT_TABLES_PATH = "/data/misc/net/rt_tables";
961 ds.DumpFile("RT_TABLES", RT_TABLES_PATH);
962 FILE* fp = fopen(RT_TABLES_PATH, "re");
964 printf("*** %s: %s\n", RT_TABLES_PATH, strerror(errno));
968 // Each line has an integer (the table number), a space, and a string (the table name). We only
969 // need the table number. It's a 32-bit unsigned number, so max 10 chars. Skip the table name.
970 // Add a fixed max limit so this doesn't go awry.
971 for (int i = 0; i < 64 && fscanf(fp, " %10s %*s", table) == 1; ++i) {
972 RunCommand("ROUTE TABLE IPv4", {"ip", "-4", "route", "show", "table", table});
973 RunCommand("ROUTE TABLE IPv6", {"ip", "-6", "route", "show", "table", table});
978 // TODO: make this function thread safe if sections are generated in parallel.
979 void Dumpstate::UpdateProgress(int32_t delta) {
980 if (progress_ == nullptr) {
981 MYLOGE("UpdateProgress: progress_ not set\n");
985 // Always update progess so stats can be tuned...
986 bool max_changed = progress_->Inc(delta);
988 // ...but only notifiy listeners when necessary.
989 if (!update_progress_) return;
991 int progress = progress_->Get();
992 int max = progress_->GetMax();
994 // adjusts max on the fly
995 if (max_changed && listener_ != nullptr) {
996 listener_->onMaxProgressUpdated(max);
999 int32_t last_update_delta = progress - last_updated_progress_;
1000 if (last_updated_progress_ > 0 && last_update_delta < update_progress_threshold_) {
1003 last_updated_progress_ = progress;
1005 if (control_socket_fd_ >= 0) {
1006 dprintf(control_socket_fd_, "PROGRESS:%d/%d\n", progress, max);
1007 fsync(control_socket_fd_);
1010 if (listener_ != nullptr) {
1011 if (progress % 100 == 0) {
1012 // We don't want to spam logcat, so only log multiples of 100.
1013 MYLOGD("Setting progress (%s): %d/%d\n", listener_name_.c_str(), progress, max);
1015 // stderr is ignored on normal invocations, but useful when calling
1016 // /system/bin/dumpstate directly for debuggging.
1017 fprintf(stderr, "Setting progress (%s): %d/%d\n", listener_name_.c_str(), progress, max);
1019 listener_->onProgressUpdated(progress);
1023 void Dumpstate::TakeScreenshot(const std::string& path) {
1024 const std::string& real_path = path.empty() ? screenshot_path_ : path;
1026 RunCommand("", {"/system/bin/screencap", "-p", real_path},
1027 CommandOptions::WithTimeout(10).Always().DropRoot().RedirectStderr().Build());
1029 MYLOGD("Screenshot saved on %s\n", real_path.c_str());
1031 MYLOGE("Failed to take screenshot on %s\n", real_path.c_str());
1035 bool is_dir(const char* pathname) {
1037 if (stat(pathname, &info) == -1) {
1040 return S_ISDIR(info.st_mode);
1043 time_t get_mtime(int fd, time_t default_mtime) {
1045 if (fstat(fd, &info) == -1) {
1046 return default_mtime;
1048 return info.st_mtime;
1051 void dump_emmc_ecsd(const char *ext_csd_path) {
1052 // List of interesting offsets
1056 static const size_t EXT_CSD_REV = 192 * sizeof(hex);
1057 static const size_t EXT_PRE_EOL_INFO = 267 * sizeof(hex);
1058 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_A = 268 * sizeof(hex);
1059 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_B = 269 * sizeof(hex);
1062 if (!android::base::ReadFileToString(ext_csd_path, &buffer)) {
1066 printf("------ %s Extended CSD ------\n", ext_csd_path);
1068 if (buffer.length() < (EXT_CSD_REV + sizeof(hex))) {
1069 printf("*** %s: truncated content %zu\n\n", ext_csd_path, buffer.length());
1073 int ext_csd_rev = 0;
1074 std::string sub = buffer.substr(EXT_CSD_REV, sizeof(hex));
1075 if (sscanf(sub.c_str(), "%2x", &ext_csd_rev) != 1) {
1076 printf("*** %s: EXT_CSD_REV parse error \"%s\"\n\n", ext_csd_path, sub.c_str());
1080 static const char *ver_str[] = {
1081 "4.0", "4.1", "4.2", "4.3", "Obsolete", "4.41", "4.5", "5.0"
1083 printf("rev 1.%d (MMC %s)\n", ext_csd_rev,
1084 (ext_csd_rev < (int)(sizeof(ver_str) / sizeof(ver_str[0]))) ? ver_str[ext_csd_rev]
1086 if (ext_csd_rev < 7) {
1091 if (buffer.length() < (EXT_PRE_EOL_INFO + sizeof(hex))) {
1092 printf("*** %s: truncated content %zu\n\n", ext_csd_path, buffer.length());
1096 int ext_pre_eol_info = 0;
1097 sub = buffer.substr(EXT_PRE_EOL_INFO, sizeof(hex));
1098 if (sscanf(sub.c_str(), "%2x", &ext_pre_eol_info) != 1) {
1099 printf("*** %s: PRE_EOL_INFO parse error \"%s\"\n\n", ext_csd_path, sub.c_str());
1103 static const char *eol_str[] = {
1106 "Warning (consumed 80% of reserve)",
1107 "Urgent (consumed 90% of reserve)"
1110 "PRE_EOL_INFO %d (MMC %s)\n", ext_pre_eol_info,
1111 eol_str[(ext_pre_eol_info < (int)(sizeof(eol_str) / sizeof(eol_str[0]))) ? ext_pre_eol_info
1114 for (size_t lifetime = EXT_DEVICE_LIFE_TIME_EST_TYP_A;
1115 lifetime <= EXT_DEVICE_LIFE_TIME_EST_TYP_B;
1116 lifetime += sizeof(hex)) {
1117 int ext_device_life_time_est;
1118 static const char *est_str[] = {
1120 "0-10% of device lifetime used",
1121 "10-20% of device lifetime used",
1122 "20-30% of device lifetime used",
1123 "30-40% of device lifetime used",
1124 "40-50% of device lifetime used",
1125 "50-60% of device lifetime used",
1126 "60-70% of device lifetime used",
1127 "70-80% of device lifetime used",
1128 "80-90% of device lifetime used",
1129 "90-100% of device lifetime used",
1130 "Exceeded the maximum estimated device lifetime",
1133 if (buffer.length() < (lifetime + sizeof(hex))) {
1134 printf("*** %s: truncated content %zu\n", ext_csd_path, buffer.length());
1138 ext_device_life_time_est = 0;
1139 sub = buffer.substr(lifetime, sizeof(hex));
1140 if (sscanf(sub.c_str(), "%2x", &ext_device_life_time_est) != 1) {
1141 printf("*** %s: DEVICE_LIFE_TIME_EST_TYP_%c parse error \"%s\"\n", ext_csd_path,
1142 (unsigned)((lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) / sizeof(hex)) + 'A',
1146 printf("DEVICE_LIFE_TIME_EST_TYP_%c %d (MMC %s)\n",
1147 (unsigned)((lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) / sizeof(hex)) + 'A',
1148 ext_device_life_time_est,
1149 est_str[(ext_device_life_time_est < (int)(sizeof(est_str) / sizeof(est_str[0])))
1150 ? ext_device_life_time_est