utils.cpp revision 608385dd151e36a93f3e3f4a7514b1e720d20ae9
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#include <dirent.h>
18#include <errno.h>
19#include <fcntl.h>
20#include <limits.h>
21#include <poll.h>
22#include <signal.h>
23#include <stdarg.h>
24#include <stdio.h>
25#include <stdlib.h>
26#include <string>
27#include <string.h>
28#include <sys/inotify.h>
29#include <sys/stat.h>
30#include <sys/time.h>
31#include <sys/wait.h>
32#include <sys/klog.h>
33#include <time.h>
34#include <unistd.h>
35#include <vector>
36#include <sys/prctl.h>
37
38#define LOG_TAG "dumpstate"
39#include <cutils/debugger.h>
40#include <cutils/log.h>
41#include <cutils/properties.h>
42#include <cutils/sockets.h>
43#include <private/android_filesystem_config.h>
44
45#include <selinux/android.h>
46
47#include "dumpstate.h"
48
49static const int64_t NANOS_PER_SEC = 1000000000;
50
51/* list of native processes to include in the native dumps */
52static const char* native_processes_to_dump[] = {
53        "/system/bin/audioserver",
54        "/system/bin/cameraserver",
55        "/system/bin/drmserver",
56        "/system/bin/mediaserver",
57        "/system/bin/sdcard",
58        "/system/bin/surfaceflinger",
59        "/system/bin/vehicle_network_service",
60        NULL,
61};
62
63DurationReporter::DurationReporter(const char *title) : DurationReporter(title, stdout) {}
64
65DurationReporter::DurationReporter(const char *title, FILE *out) {
66    title_ = title;
67    if (title) {
68        started_ = DurationReporter::nanotime();
69    }
70    out_ = out;
71}
72
73DurationReporter::~DurationReporter() {
74    if (title_) {
75        uint64_t elapsed = DurationReporter::nanotime() - started_;
76        // Use "Yoda grammar" to make it easier to grep|sort sections.
77        if (out_) {
78            fprintf(out_, "------ %.3fs was the duration of '%s' ------\n",
79                   (float) elapsed / NANOS_PER_SEC, title_);
80        } else {
81            ALOGD("Duration of '%s': %.3fs\n", title_, (float) elapsed / NANOS_PER_SEC);
82        }
83    }
84}
85
86uint64_t DurationReporter::DurationReporter::nanotime() {
87    struct timespec ts;
88    clock_gettime(CLOCK_MONOTONIC, &ts);
89    return (uint64_t) ts.tv_sec * NANOS_PER_SEC + ts.tv_nsec;
90}
91
92void for_each_userid(void (*func)(int), const char *header) {
93    ON_DRY_RUN_RETURN();
94    DIR *d;
95    struct dirent *de;
96
97    if (header) printf("\n------ %s ------\n", header);
98    func(0);
99
100    if (!(d = opendir("/data/system/users"))) {
101        printf("Failed to open /data/system/users (%s)\n", strerror(errno));
102        return;
103    }
104
105    while ((de = readdir(d))) {
106        int userid;
107        if (de->d_type != DT_DIR || !(userid = atoi(de->d_name))) {
108            continue;
109        }
110        func(userid);
111    }
112
113    closedir(d);
114}
115
116static void __for_each_pid(void (*helper)(int, const char *, void *), const char *header, void *arg) {
117    DIR *d;
118    struct dirent *de;
119
120    if (!(d = opendir("/proc"))) {
121        printf("Failed to open /proc (%s)\n", strerror(errno));
122        return;
123    }
124
125    if (header) printf("\n------ %s ------\n", header);
126    while ((de = readdir(d))) {
127        int pid;
128        int fd;
129        char cmdpath[255];
130        char cmdline[255];
131
132        if (!(pid = atoi(de->d_name))) {
133            continue;
134        }
135
136        sprintf(cmdpath,"/proc/%d/cmdline", pid);
137        memset(cmdline, 0, sizeof(cmdline));
138        if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) < 0) {
139            strcpy(cmdline, "N/A");
140        } else {
141            read(fd, cmdline, sizeof(cmdline) - 1);
142            close(fd);
143        }
144        helper(pid, cmdline, arg);
145    }
146
147    closedir(d);
148}
149
150static void for_each_pid_helper(int pid, const char *cmdline, void *arg) {
151    for_each_pid_func *func = (for_each_pid_func*) arg;
152    func(pid, cmdline);
153}
154
155void for_each_pid(for_each_pid_func func, const char *header) {
156    ON_DRY_RUN_RETURN();
157  __for_each_pid(for_each_pid_helper, header, (void *)func);
158}
159
160static void for_each_tid_helper(int pid, const char *cmdline, void *arg) {
161    DIR *d;
162    struct dirent *de;
163    char taskpath[255];
164    for_each_tid_func *func = (for_each_tid_func *) arg;
165
166    sprintf(taskpath, "/proc/%d/task", pid);
167
168    if (!(d = opendir(taskpath))) {
169        printf("Failed to open %s (%s)\n", taskpath, strerror(errno));
170        return;
171    }
172
173    func(pid, pid, cmdline);
174
175    while ((de = readdir(d))) {
176        int tid;
177        int fd;
178        char commpath[255];
179        char comm[255];
180
181        if (!(tid = atoi(de->d_name))) {
182            continue;
183        }
184
185        if (tid == pid)
186            continue;
187
188        sprintf(commpath,"/proc/%d/comm", tid);
189        memset(comm, 0, sizeof(comm));
190        if ((fd = TEMP_FAILURE_RETRY(open(commpath, O_RDONLY | O_CLOEXEC))) < 0) {
191            strcpy(comm, "N/A");
192        } else {
193            char *c;
194            read(fd, comm, sizeof(comm) - 1);
195            close(fd);
196
197            c = strrchr(comm, '\n');
198            if (c) {
199                *c = '\0';
200            }
201        }
202        func(pid, tid, comm);
203    }
204
205    closedir(d);
206}
207
208void for_each_tid(for_each_tid_func func, const char *header) {
209    ON_DRY_RUN_RETURN();
210    __for_each_pid(for_each_tid_helper, header, (void *) func);
211}
212
213void show_wchan(int pid, int tid, const char *name) {
214    ON_DRY_RUN_RETURN();
215    char path[255];
216    char buffer[255];
217    int fd;
218    char name_buffer[255];
219
220    memset(buffer, 0, sizeof(buffer));
221
222    sprintf(path, "/proc/%d/wchan", tid);
223    if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
224        printf("Failed to open '%s' (%s)\n", path, strerror(errno));
225        return;
226    }
227
228    if (read(fd, buffer, sizeof(buffer)) < 0) {
229        printf("Failed to read '%s' (%s)\n", path, strerror(errno));
230        goto out_close;
231    }
232
233    snprintf(name_buffer, sizeof(name_buffer), "%*s%s",
234             pid == tid ? 0 : 3, "", name);
235
236    printf("%-7d %-32s %s\n", tid, name_buffer, buffer);
237
238out_close:
239    close(fd);
240    return;
241}
242
243void do_dmesg() {
244    const char *title = "KERNEL LOG (dmesg)";
245    DurationReporter duration_reporter(title);
246    printf("------ %s ------\n", title);
247
248    ON_DRY_RUN_RETURN();
249    /* Get size of kernel buffer */
250    int size = klogctl(KLOG_SIZE_BUFFER, NULL, 0);
251    if (size <= 0) {
252        printf("Unexpected klogctl return value: %d\n\n", size);
253        return;
254    }
255    char *buf = (char *) malloc(size + 1);
256    if (buf == NULL) {
257        printf("memory allocation failed\n\n");
258        return;
259    }
260    int retval = klogctl(KLOG_READ_ALL, buf, size);
261    if (retval < 0) {
262        printf("klogctl failure\n\n");
263        free(buf);
264        return;
265    }
266    buf[retval] = '\0';
267    printf("%s\n\n", buf);
268    free(buf);
269    return;
270}
271
272void do_showmap(int pid, const char *name) {
273    char title[255];
274    char arg[255];
275
276    sprintf(title, "SHOW MAP %d (%s)", pid, name);
277    sprintf(arg, "%d", pid);
278    run_command(title, 10, SU_PATH, "root", "showmap", arg, NULL);
279}
280
281static int _dump_file_from_fd(const char *title, const char *path, int fd) {
282    if (title) {
283        printf("------ %s (%s", title, path);
284
285        struct stat st;
286        // Only show the modification time of non-device files.
287        size_t path_len = strlen(path);
288        if ((path_len < 6 || memcmp(path, "/proc/", 6)) &&
289                (path_len < 5 || memcmp(path, "/sys/", 5)) &&
290                (path_len < 3 || memcmp(path, "/d/", 3)) &&
291                !fstat(fd, &st)) {
292            char stamp[80];
293            time_t mtime = st.st_mtime;
294            strftime(stamp, sizeof(stamp), "%Y-%m-%d %H:%M:%S", localtime(&mtime));
295            printf(": %s", stamp);
296        }
297        printf(") ------\n");
298    }
299    ON_DRY_RUN({ update_progress(WEIGHT_FILE); close(fd); return 0; });
300
301    bool newline = false;
302    fd_set read_set;
303    struct timeval tm;
304    while (1) {
305        FD_ZERO(&read_set);
306        FD_SET(fd, &read_set);
307        /* Timeout if no data is read for 30 seconds. */
308        tm.tv_sec = 30;
309        tm.tv_usec = 0;
310        uint64_t elapsed = DurationReporter::nanotime();
311        int ret = TEMP_FAILURE_RETRY(select(fd + 1, &read_set, NULL, NULL, &tm));
312        if (ret == -1) {
313            printf("*** %s: select failed: %s\n", path, strerror(errno));
314            newline = true;
315            break;
316        } else if (ret == 0) {
317            elapsed = DurationReporter::nanotime() - elapsed;
318            printf("*** %s: Timed out after %.3fs\n", path,
319                   (float) elapsed / NANOS_PER_SEC);
320            newline = true;
321            break;
322        } else {
323            char buffer[65536];
324            ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
325            if (bytes_read > 0) {
326                fwrite(buffer, bytes_read, 1, stdout);
327                newline = (buffer[bytes_read-1] == '\n');
328            } else {
329                if (bytes_read == -1) {
330                    printf("*** %s: Failed to read from fd: %s", path, strerror(errno));
331                    newline = true;
332                }
333                break;
334            }
335        }
336    }
337    update_progress(WEIGHT_FILE);
338    close(fd);
339
340    if (!newline) printf("\n");
341    if (title) printf("\n");
342    return 0;
343}
344
345/* prints the contents of a file */
346int dump_file(const char *title, const char *path) {
347    DurationReporter duration_reporter(title);
348    int fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
349    if (fd < 0) {
350        int err = errno;
351        printf("*** %s: %s\n", path, strerror(err));
352        if (title) printf("\n");
353        return -1;
354    }
355    return _dump_file_from_fd(title, path, fd);
356}
357
358/* calls skip to gate calling dump_from_fd recursively
359 * in the specified directory. dump_from_fd defaults to
360 * dump_file_from_fd above when set to NULL. skip defaults
361 * to false when set to NULL. dump_from_fd will always be
362 * called with title NULL.
363 */
364int dump_files(const char *title, const char *dir,
365        bool (*skip)(const char *path),
366        int (*dump_from_fd)(const char *title, const char *path, int fd)) {
367    DurationReporter duration_reporter(title);
368    DIR *dirp;
369    struct dirent *d;
370    char *newpath = NULL;
371    const char *slash = "/";
372    int fd, retval = 0;
373
374    if (title) {
375        printf("------ %s (%s) ------\n", title, dir);
376    }
377    ON_DRY_RUN_RETURN(0);
378
379    if (dir[strlen(dir) - 1] == '/') {
380        ++slash;
381    }
382    dirp = opendir(dir);
383    if (dirp == NULL) {
384        retval = -errno;
385        fprintf(stderr, "%s: %s\n", dir, strerror(errno));
386        return retval;
387    }
388
389    if (!dump_from_fd) {
390        dump_from_fd = dump_file_from_fd;
391    }
392    for (; ((d = readdir(dirp))); free(newpath), newpath = NULL) {
393        if ((d->d_name[0] == '.')
394         && (((d->d_name[1] == '.') && (d->d_name[2] == '\0'))
395          || (d->d_name[1] == '\0'))) {
396            continue;
397        }
398        asprintf(&newpath, "%s%s%s%s", dir, slash, d->d_name,
399                 (d->d_type == DT_DIR) ? "/" : "");
400        if (!newpath) {
401            retval = -errno;
402            continue;
403        }
404        if (skip && (*skip)(newpath)) {
405            continue;
406        }
407        if (d->d_type == DT_DIR) {
408            int ret = dump_files(NULL, newpath, skip, dump_from_fd);
409            if (ret < 0) {
410                retval = ret;
411            }
412            continue;
413        }
414        fd = TEMP_FAILURE_RETRY(open(newpath, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
415        if (fd < 0) {
416            retval = fd;
417            printf("*** %s: %s\n", newpath, strerror(errno));
418            continue;
419        }
420        (*dump_from_fd)(NULL, newpath, fd);
421    }
422    closedir(dirp);
423    if (title) {
424        printf("\n");
425    }
426    return retval;
427}
428
429/* fd must have been opened with the flag O_NONBLOCK. With this flag set,
430 * it's possible to avoid issues where opening the file itself can get
431 * stuck.
432 */
433int dump_file_from_fd(const char *title, const char *path, int fd) {
434    int flags = fcntl(fd, F_GETFL);
435    if (flags == -1) {
436        printf("*** %s: failed to get flags on fd %d: %s\n", path, fd, strerror(errno));
437        close(fd);
438        return -1;
439    } else if (!(flags & O_NONBLOCK)) {
440        printf("*** %s: fd must have O_NONBLOCK set.\n", path);
441        close(fd);
442        return -1;
443    }
444    return _dump_file_from_fd(title, path, fd);
445}
446
447bool waitpid_with_timeout(pid_t pid, int timeout_seconds, int* status) {
448    sigset_t child_mask, old_mask;
449    sigemptyset(&child_mask);
450    sigaddset(&child_mask, SIGCHLD);
451
452    if (sigprocmask(SIG_BLOCK, &child_mask, &old_mask) == -1) {
453        printf("*** sigprocmask failed: %s\n", strerror(errno));
454        return false;
455    }
456
457    struct timespec ts;
458    ts.tv_sec = timeout_seconds;
459    ts.tv_nsec = 0;
460    int ret = TEMP_FAILURE_RETRY(sigtimedwait(&child_mask, NULL, &ts));
461    int saved_errno = errno;
462    // Set the signals back the way they were.
463    if (sigprocmask(SIG_SETMASK, &old_mask, NULL) == -1) {
464        printf("*** sigprocmask failed: %s\n", strerror(errno));
465        if (ret == 0) {
466            return false;
467        }
468    }
469    if (ret == -1) {
470        errno = saved_errno;
471        if (errno == EAGAIN) {
472            errno = ETIMEDOUT;
473        } else {
474            printf("*** sigtimedwait failed: %s\n", strerror(errno));
475        }
476        return false;
477    }
478
479    pid_t child_pid = waitpid(pid, status, WNOHANG);
480    if (child_pid != pid) {
481        if (child_pid != -1) {
482            printf("*** Waiting for pid %d, got pid %d instead\n", pid, child_pid);
483        } else {
484            printf("*** waitpid failed: %s\n", strerror(errno));
485        }
486        return false;
487    }
488    return true;
489}
490
491int run_command(const char *title, int timeout_seconds, const char *command, ...) {
492    DurationReporter duration_reporter(title);
493    fflush(stdout);
494
495    const char *args[1024] = {command};
496    size_t arg;
497    va_list ap;
498    va_start(ap, command);
499    if (title) printf("------ %s (%s", title, command);
500    for (arg = 1; arg < sizeof(args) / sizeof(args[0]); ++arg) {
501        args[arg] = va_arg(ap, const char *);
502        if (args[arg] == NULL) break;
503        if (title) printf(" %s", args[arg]);
504    }
505    if (title) printf(") ------\n");
506    fflush(stdout);
507
508    ON_DRY_RUN({ update_progress(timeout_seconds); va_end(ap); return 0; });
509
510    int status = run_command_always(title, timeout_seconds, args);
511    va_end(ap);
512    return status;
513}
514
515/* forks a command and waits for it to finish */
516int run_command_always(const char *title, int timeout_seconds, const char *args[]) {
517    /* TODO: for now we're simplifying the progress calculation by using the timeout as the weight.
518     * It's a good approximation for most cases, except when calling dumpsys, where its weight
519     * should be much higher proportionally to its timeout. */
520    int weight = timeout_seconds;
521
522    const char *command = args[0];
523    uint64_t start = DurationReporter::nanotime();
524    pid_t pid = fork();
525
526    /* handle error case */
527    if (pid < 0) {
528        printf("*** fork: %s\n", strerror(errno));
529        return pid;
530    }
531
532    /* handle child case */
533    if (pid == 0) {
534
535        /* make sure the child dies when dumpstate dies */
536        prctl(PR_SET_PDEATHSIG, SIGKILL);
537
538        /* just ignore SIGPIPE, will go down with parent's */
539        struct sigaction sigact;
540        memset(&sigact, 0, sizeof(sigact));
541        sigact.sa_handler = SIG_IGN;
542        sigaction(SIGPIPE, &sigact, NULL);
543
544        execvp(command, (char**) args);
545        printf("*** exec(%s): %s\n", command, strerror(errno));
546        fflush(stdout);
547        _exit(-1);
548    }
549
550    /* handle parent case */
551    int status;
552    bool ret = waitpid_with_timeout(pid, timeout_seconds, &status);
553    uint64_t elapsed = DurationReporter::nanotime() - start;
554    if (!ret) {
555        if (errno == ETIMEDOUT) {
556            printf("*** %s: Timed out after %.3fs (killing pid %d)\n", command,
557                   (float) elapsed / NANOS_PER_SEC, pid);
558        } else {
559            printf("*** %s: Error after %.4fs (killing pid %d)\n", command,
560                   (float) elapsed / NANOS_PER_SEC, pid);
561        }
562        kill(pid, SIGTERM);
563        if (!waitpid_with_timeout(pid, 5, NULL)) {
564            kill(pid, SIGKILL);
565            if (!waitpid_with_timeout(pid, 5, NULL)) {
566                printf("*** %s: Cannot kill %d even with SIGKILL.\n", command, pid);
567            }
568        }
569        return -1;
570    }
571
572    if (WIFSIGNALED(status)) {
573        printf("*** %s: Killed by signal %d\n", command, WTERMSIG(status));
574    } else if (WIFEXITED(status) && WEXITSTATUS(status) > 0) {
575        printf("*** %s: Exit code %d\n", command, WEXITSTATUS(status));
576    }
577
578    if (weight > 0) {
579        update_progress(weight);
580    }
581    return status;
582}
583
584void send_broadcast(const std::string& action, const std::vector<std::string>& args) {
585    if (args.size() > 1000) {
586        fprintf(stderr, "send_broadcast: too many arguments (%d)\n", (int) args.size());
587        return;
588    }
589    const char *am_args[1024] = { "/system/bin/am", "broadcast",
590                                  "--user", "0", "-a", action.c_str() };
591    size_t am_index = 5; // Starts at the index of last initial value above.
592    for (const std::string& arg : args) {
593        am_args[++am_index] = arg.c_str();
594    }
595    // Always terminate with NULL.
596    am_args[am_index + 1] = NULL;
597    run_command_always(NULL, 5, am_args);
598}
599
600size_t num_props = 0;
601static char* props[2000];
602
603static void print_prop(const char *key, const char *name, void *user) {
604    (void) user;
605    if (num_props < sizeof(props) / sizeof(props[0])) {
606        char buf[PROPERTY_KEY_MAX + PROPERTY_VALUE_MAX + 10];
607        snprintf(buf, sizeof(buf), "[%s]: [%s]\n", key, name);
608        props[num_props++] = strdup(buf);
609    }
610}
611
612static int compare_prop(const void *a, const void *b) {
613    return strcmp(*(char * const *) a, *(char * const *) b);
614}
615
616/* prints all the system properties */
617void print_properties() {
618    const char* title = "SYSTEM PROPERTIES";
619    DurationReporter duration_reporter(title);
620    printf("------ %s ------\n", title);
621    ON_DRY_RUN_RETURN();
622    size_t i;
623    num_props = 0;
624    property_list(print_prop, NULL);
625    qsort(&props, num_props, sizeof(props[0]), compare_prop);
626
627    for (i = 0; i < num_props; ++i) {
628        fputs(props[i], stdout);
629        free(props[i]);
630    }
631    printf("\n");
632}
633
634/* redirect output to a service control socket */
635void redirect_to_socket(FILE *redirect, const char *service) {
636    int s = android_get_control_socket(service);
637    if (s < 0) {
638        fprintf(stderr, "android_get_control_socket(%s): %s\n", service, strerror(errno));
639        exit(1);
640    }
641    fcntl(s, F_SETFD, FD_CLOEXEC);
642    if (listen(s, 4) < 0) {
643        fprintf(stderr, "listen(control socket): %s\n", strerror(errno));
644        exit(1);
645    }
646
647    struct sockaddr addr;
648    socklen_t alen = sizeof(addr);
649    int fd = accept(s, &addr, &alen);
650    if (fd < 0) {
651        fprintf(stderr, "accept(control socket): %s\n", strerror(errno));
652        exit(1);
653    }
654
655    fflush(redirect);
656    dup2(fd, fileno(redirect));
657    close(fd);
658}
659
660/* redirect output to a file */
661void redirect_to_file(FILE *redirect, char *path) {
662    char *chp = path;
663
664    /* skip initial slash */
665    if (chp[0] == '/')
666        chp++;
667
668    /* create leading directories, if necessary */
669    while (chp && chp[0]) {
670        chp = strchr(chp, '/');
671        if (chp) {
672            *chp = 0;
673            mkdir(path, 0770);  /* drwxrwx--- */
674            *chp++ = '/';
675        }
676    }
677
678    int fd = TEMP_FAILURE_RETRY(open(path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW,
679                                     S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
680    if (fd < 0) {
681        fprintf(stderr, "%s: %s\n", path, strerror(errno));
682        exit(1);
683    }
684
685    TEMP_FAILURE_RETRY(dup2(fd, fileno(redirect)));
686    close(fd);
687}
688
689static bool should_dump_native_traces(const char* path) {
690    for (const char** p = native_processes_to_dump; *p; p++) {
691        if (!strcmp(*p, path)) {
692            return true;
693        }
694    }
695    return false;
696}
697
698/* dump Dalvik and native stack traces, return the trace file location (NULL if none) */
699const char *dump_traces() {
700    DurationReporter duration_reporter("DUMP TRACES", NULL);
701    ON_DRY_RUN_RETURN(NULL);
702    const char* result = NULL;
703
704    char traces_path[PROPERTY_VALUE_MAX] = "";
705    property_get("dalvik.vm.stack-trace-file", traces_path, "");
706    if (!traces_path[0]) return NULL;
707
708    /* move the old traces.txt (if any) out of the way temporarily */
709    char anr_traces_path[PATH_MAX];
710    strlcpy(anr_traces_path, traces_path, sizeof(anr_traces_path));
711    strlcat(anr_traces_path, ".anr", sizeof(anr_traces_path));
712    if (rename(traces_path, anr_traces_path) && errno != ENOENT) {
713        fprintf(stderr, "rename(%s, %s): %s\n", traces_path, anr_traces_path, strerror(errno));
714        return NULL;  // Can't rename old traces.txt -- no permission? -- leave it alone instead
715    }
716
717    /* create a new, empty traces.txt file to receive stack dumps */
718    int fd = TEMP_FAILURE_RETRY(open(traces_path, O_CREAT | O_WRONLY | O_TRUNC | O_NOFOLLOW | O_CLOEXEC,
719                                     0666));  /* -rw-rw-rw- */
720    if (fd < 0) {
721        fprintf(stderr, "%s: %s\n", traces_path, strerror(errno));
722        return NULL;
723    }
724    int chmod_ret = fchmod(fd, 0666);
725    if (chmod_ret < 0) {
726        fprintf(stderr, "fchmod on %s failed: %s\n", traces_path, strerror(errno));
727        close(fd);
728        return NULL;
729    }
730
731    /* Variables below must be initialized before 'goto' statements */
732    int dalvik_found = 0;
733    int ifd, wfd = -1;
734
735    /* walk /proc and kill -QUIT all Dalvik processes */
736    DIR *proc = opendir("/proc");
737    if (proc == NULL) {
738        fprintf(stderr, "/proc: %s\n", strerror(errno));
739        goto error_close_fd;
740    }
741
742    /* use inotify to find when processes are done dumping */
743    ifd = inotify_init();
744    if (ifd < 0) {
745        fprintf(stderr, "inotify_init: %s\n", strerror(errno));
746        goto error_close_fd;
747    }
748
749    wfd = inotify_add_watch(ifd, traces_path, IN_CLOSE_WRITE);
750    if (wfd < 0) {
751        fprintf(stderr, "inotify_add_watch(%s): %s\n", traces_path, strerror(errno));
752        goto error_close_ifd;
753    }
754
755    struct dirent *d;
756    while ((d = readdir(proc))) {
757        int pid = atoi(d->d_name);
758        if (pid <= 0) continue;
759
760        char path[PATH_MAX];
761        char data[PATH_MAX];
762        snprintf(path, sizeof(path), "/proc/%d/exe", pid);
763        ssize_t len = readlink(path, data, sizeof(data) - 1);
764        if (len <= 0) {
765            continue;
766        }
767        data[len] = '\0';
768
769        if (!strncmp(data, "/system/bin/app_process", strlen("/system/bin/app_process"))) {
770            /* skip zygote -- it won't dump its stack anyway */
771            snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
772            int cfd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC));
773            len = read(cfd, data, sizeof(data) - 1);
774            close(cfd);
775            if (len <= 0) {
776                continue;
777            }
778            data[len] = '\0';
779            if (!strncmp(data, "zygote", strlen("zygote"))) {
780                continue;
781            }
782
783            ++dalvik_found;
784            uint64_t start = DurationReporter::nanotime();
785            if (kill(pid, SIGQUIT)) {
786                fprintf(stderr, "kill(%d, SIGQUIT): %s\n", pid, strerror(errno));
787                continue;
788            }
789
790            /* wait for the writable-close notification from inotify */
791            struct pollfd pfd = { ifd, POLLIN, 0 };
792            int ret = poll(&pfd, 1, 5000);  /* 5 sec timeout */
793            if (ret < 0) {
794                fprintf(stderr, "poll: %s\n", strerror(errno));
795            } else if (ret == 0) {
796                fprintf(stderr, "warning: timed out dumping pid %d\n", pid);
797            } else {
798                struct inotify_event ie;
799                read(ifd, &ie, sizeof(ie));
800            }
801
802            if (lseek(fd, 0, SEEK_END) < 0) {
803                fprintf(stderr, "lseek: %s\n", strerror(errno));
804            } else {
805                dprintf(fd, "[dump dalvik stack %d: %.3fs elapsed]\n",
806                        pid, (float)(DurationReporter::nanotime() - start) / NANOS_PER_SEC);
807            }
808        } else if (should_dump_native_traces(data)) {
809            /* dump native process if appropriate */
810            if (lseek(fd, 0, SEEK_END) < 0) {
811                fprintf(stderr, "lseek: %s\n", strerror(errno));
812            } else {
813                static uint16_t timeout_failures = 0;
814                uint64_t start = DurationReporter::nanotime();
815
816                /* If 3 backtrace dumps fail in a row, consider debuggerd dead. */
817                if (timeout_failures == 3) {
818                    dprintf(fd, "too many stack dump failures, skipping...\n");
819                } else if (dump_backtrace_to_file_timeout(pid, fd, 20) == -1) {
820                    dprintf(fd, "dumping failed, likely due to a timeout\n");
821                    timeout_failures++;
822                } else {
823                    timeout_failures = 0;
824                }
825                dprintf(fd, "[dump native stack %d: %.3fs elapsed]\n",
826                        pid, (float)(DurationReporter::nanotime() - start) / NANOS_PER_SEC);
827            }
828        }
829    }
830
831    if (dalvik_found == 0) {
832        fprintf(stderr, "Warning: no Dalvik processes found to dump stacks\n");
833    }
834
835    static char dump_traces_path[PATH_MAX];
836    strlcpy(dump_traces_path, traces_path, sizeof(dump_traces_path));
837    strlcat(dump_traces_path, ".bugreport", sizeof(dump_traces_path));
838    if (rename(traces_path, dump_traces_path)) {
839        fprintf(stderr, "rename(%s, %s): %s\n", traces_path, dump_traces_path, strerror(errno));
840        goto error_close_ifd;
841    }
842    result = dump_traces_path;
843
844    /* replace the saved [ANR] traces.txt file */
845    rename(anr_traces_path, traces_path);
846
847error_close_ifd:
848    close(ifd);
849error_close_fd:
850    close(fd);
851    return result;
852}
853
854void dump_route_tables() {
855    DurationReporter duration_reporter("DUMP ROUTE TABLES");
856    ON_DRY_RUN_RETURN();
857    const char* const RT_TABLES_PATH = "/data/misc/net/rt_tables";
858    dump_file("RT_TABLES", RT_TABLES_PATH);
859    FILE* fp = fopen(RT_TABLES_PATH, "re");
860    if (!fp) {
861        printf("*** %s: %s\n", RT_TABLES_PATH, strerror(errno));
862        return;
863    }
864    char table[16];
865    // Each line has an integer (the table number), a space, and a string (the table name). We only
866    // need the table number. It's a 32-bit unsigned number, so max 10 chars. Skip the table name.
867    // Add a fixed max limit so this doesn't go awry.
868    for (int i = 0; i < 64 && fscanf(fp, " %10s %*s", table) == 1; ++i) {
869        run_command("ROUTE TABLE IPv4", 10, "ip", "-4", "route", "show", "table", table, NULL);
870        run_command("ROUTE TABLE IPv6", 10, "ip", "-6", "route", "show", "table", table, NULL);
871    }
872    fclose(fp);
873}
874
875/* overall progress */
876int progress = 0;
877int do_update_progress = 0; // Set by dumpstate.cpp
878int weight_total = WEIGHT_TOTAL;
879
880// TODO: make this function thread safe if sections are generated in parallel.
881void update_progress(int delta) {
882    if (!do_update_progress) return;
883
884    progress += delta;
885
886    char key[PROPERTY_KEY_MAX];
887    char value[PROPERTY_VALUE_MAX];
888
889    // adjusts max on the fly
890    if (progress > weight_total) {
891        int new_total = weight_total * 1.2;
892        fprintf(stderr, "Adjusting total weight from %d to %d\n", weight_total, new_total);
893        weight_total = new_total;
894        sprintf(key, "dumpstate.%d.max", getpid());
895        sprintf(value, "%d", weight_total);
896        int status = property_set(key, value);
897        if (status) {
898            ALOGW("Could not update max weight by setting system property %s to %s: %d\n",
899                    key, value, status);
900        }
901    }
902
903    sprintf(key, "dumpstate.%d.progress", getpid());
904    sprintf(value, "%d", progress);
905
906    // stderr is ignored on normal invocations, but useful when calling /system/bin/dumpstate
907    // directly for debuggging.
908    fprintf(stderr, "Setting progress (%s): %s/%d\n", key, value, weight_total);
909
910    int status = property_set(key, value);
911    if (status) {
912        ALOGW("Could not update progress by setting system property %s to %s: %d\n",
913                key, value, status);
914    }
915}
916
917void take_screenshot(const std::string& path) {
918    const char *args[] = { "/system/bin/screencap", "-p", path.c_str(), NULL };
919    run_command_always(NULL, 10, args);
920}
921
922void vibrate(FILE* vibrator, int ms) {
923    fprintf(vibrator, "%d\n", ms);
924    fflush(vibrator);
925}
926
927bool is_dir(const char* pathname) {
928    struct stat info;
929    if (stat(pathname, &info) == -1) {
930        return false;
931    }
932    return S_ISDIR(info.st_mode);
933}
934
935time_t get_mtime(int fd, time_t default_mtime) {
936    struct stat info;
937    if (fstat(fd, &info) == -1) {
938        return default_mtime;
939    }
940    return info.st_mtime;
941}
942
943void dump_emmc_ecsd(const char *ext_csd_path) {
944    static const size_t EXT_CSD_REV = 192;
945    static const size_t EXT_PRE_EOL_INFO = 267;
946    static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_A = 268;
947    static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_B = 269;
948    struct hex {
949        char str[2];
950    } buffer[512];
951    int fd, ext_csd_rev, ext_pre_eol_info;
952    ssize_t bytes_read;
953    static const char *ver_str[] = {
954        "4.0", "4.1", "4.2", "4.3", "Obsolete", "4.41", "4.5", "5.0"
955    };
956    static const char *eol_str[] = {
957        "Undefined",
958        "Normal",
959        "Warning (consumed 80% of reserve)",
960        "Urgent (consumed 90% of reserve)"
961    };
962
963    printf("------ %s Extended CSD ------\n", ext_csd_path);
964
965    fd = TEMP_FAILURE_RETRY(open(ext_csd_path,
966                                 O_RDONLY | O_NONBLOCK | O_CLOEXEC));
967    if (fd < 0) {
968        printf("*** %s: %s\n\n", ext_csd_path, strerror(errno));
969        return;
970    }
971
972    bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
973    close(fd);
974    if (bytes_read < 0) {
975        printf("*** %s: %s\n\n", ext_csd_path, strerror(errno));
976        return;
977    }
978    if (bytes_read < (ssize_t)(EXT_CSD_REV * sizeof(struct hex))) {
979        printf("*** %s: truncated content %zd\n\n", ext_csd_path, bytes_read);
980        return;
981    }
982
983    ext_csd_rev = 0;
984    if (sscanf(buffer[EXT_CSD_REV].str, "%02x", &ext_csd_rev) != 1) {
985        printf("*** %s: EXT_CSD_REV parse error \"%.2s\"\n\n",
986               ext_csd_path, buffer[EXT_CSD_REV].str);
987        return;
988    }
989
990    printf("rev 1.%d (MMC %s)\n",
991           ext_csd_rev,
992           (ext_csd_rev < (int)(sizeof(ver_str) / sizeof(ver_str[0]))) ?
993               ver_str[ext_csd_rev] :
994               "Unknown");
995    if (ext_csd_rev < 7) {
996        printf("\n");
997        return;
998    }
999
1000    if (bytes_read < (ssize_t)(EXT_PRE_EOL_INFO * sizeof(struct hex))) {
1001        printf("*** %s: truncated content %zd\n\n", ext_csd_path, bytes_read);
1002        return;
1003    }
1004
1005    ext_pre_eol_info = 0;
1006    if (sscanf(buffer[EXT_PRE_EOL_INFO].str, "%02x", &ext_pre_eol_info) != 1) {
1007        printf("*** %s: PRE_EOL_INFO parse error \"%.2s\"\n\n",
1008               ext_csd_path, buffer[EXT_PRE_EOL_INFO].str);
1009        return;
1010    }
1011    printf("PRE_EOL_INFO %d (MMC %s)\n",
1012           ext_pre_eol_info,
1013           eol_str[(ext_pre_eol_info < (int)
1014                       (sizeof(eol_str) / sizeof(eol_str[0]))) ?
1015                           ext_pre_eol_info : 0]);
1016
1017    for (size_t lifetime = EXT_DEVICE_LIFE_TIME_EST_TYP_A;
1018            lifetime <= EXT_DEVICE_LIFE_TIME_EST_TYP_B;
1019            ++lifetime) {
1020        int ext_device_life_time_est;
1021        static const char *est_str[] = {
1022            "Undefined",
1023            "0-10% of device lifetime used",
1024            "10-20% of device lifetime used",
1025            "20-30% of device lifetime used",
1026            "30-40% of device lifetime used",
1027            "40-50% of device lifetime used",
1028            "50-60% of device lifetime used",
1029            "60-70% of device lifetime used",
1030            "70-80% of device lifetime used",
1031            "80-90% of device lifetime used",
1032            "90-100% of device lifetime used",
1033            "Exceeded the maximum estimated device lifetime",
1034        };
1035
1036        if (bytes_read < (ssize_t)(lifetime * sizeof(struct hex))) {
1037            printf("*** %s: truncated content %zd\n", ext_csd_path, bytes_read);
1038            break;
1039        }
1040
1041        ext_device_life_time_est = 0;
1042        if (sscanf(buffer[lifetime].str, "%02x", &ext_device_life_time_est) != 1) {
1043            printf("*** %s: DEVICE_LIFE_TIME_EST_TYP_%c parse error \"%.2s\"\n",
1044                   ext_csd_path,
1045                   (unsigned)(lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) + 'A',
1046                   buffer[lifetime].str);
1047            continue;
1048        }
1049        printf("DEVICE_LIFE_TIME_EST_TYP_%c %d (MMC %s)\n",
1050               (unsigned)(lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) + 'A',
1051               ext_device_life_time_est,
1052               est_str[(ext_device_life_time_est < (int)
1053                           (sizeof(est_str) / sizeof(est_str[0]))) ?
1054                               ext_device_life_time_est : 0]);
1055    }
1056
1057    printf("\n");
1058}
1059