utils.cpp revision 111b9d06cc0fc72438782c9234f28675e5077ef4
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
660void create_parent_dirs(const char *path) {
661    char *chp = (char*) path;
662
663    /* skip initial slash */
664    if (chp[0] == '/')
665        chp++;
666
667    /* create leading directories, if necessary */
668    struct stat dir_stat;
669    while (chp && chp[0]) {
670        chp = strchr(chp, '/');
671        if (chp) {
672            *chp = 0;
673            if (stat(path, &dir_stat) == -1 || !S_ISDIR(dir_stat.st_mode)) {
674                ALOGI("Creating directory %s\n", path);
675                if (mkdir(path, 0770)) { /* drwxrwx--- */
676                    ALOGE("Unable to create directory %s: %s\n", path, strerror(errno));
677                } else if (chown(path, AID_SHELL, AID_SHELL)) {
678                    ALOGE("Unable to change ownership of dir %s: %s\n", path, strerror(errno));
679                }
680            }
681            *chp++ = '/';
682        }
683    }
684}
685
686/* redirect output to a file */
687void redirect_to_file(FILE *redirect, char *path) {
688    create_parent_dirs(path);
689
690    int fd = TEMP_FAILURE_RETRY(open(path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW,
691                                     S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
692    if (fd < 0) {
693        fprintf(stderr, "%s: %s\n", path, strerror(errno));
694        exit(1);
695    }
696
697    TEMP_FAILURE_RETRY(dup2(fd, fileno(redirect)));
698    close(fd);
699}
700
701static bool should_dump_native_traces(const char* path) {
702    for (const char** p = native_processes_to_dump; *p; p++) {
703        if (!strcmp(*p, path)) {
704            return true;
705        }
706    }
707    return false;
708}
709
710/* dump Dalvik and native stack traces, return the trace file location (NULL if none) */
711const char *dump_traces() {
712    DurationReporter duration_reporter("DUMP TRACES", NULL);
713    ON_DRY_RUN_RETURN(NULL);
714    const char* result = NULL;
715
716    char traces_path[PROPERTY_VALUE_MAX] = "";
717    property_get("dalvik.vm.stack-trace-file", traces_path, "");
718    if (!traces_path[0]) return NULL;
719
720    /* move the old traces.txt (if any) out of the way temporarily */
721    char anr_traces_path[PATH_MAX];
722    strlcpy(anr_traces_path, traces_path, sizeof(anr_traces_path));
723    strlcat(anr_traces_path, ".anr", sizeof(anr_traces_path));
724    if (rename(traces_path, anr_traces_path) && errno != ENOENT) {
725        fprintf(stderr, "rename(%s, %s): %s\n", traces_path, anr_traces_path, strerror(errno));
726        return NULL;  // Can't rename old traces.txt -- no permission? -- leave it alone instead
727    }
728
729    /* create a new, empty traces.txt file to receive stack dumps */
730    int fd = TEMP_FAILURE_RETRY(open(traces_path, O_CREAT | O_WRONLY | O_TRUNC | O_NOFOLLOW | O_CLOEXEC,
731                                     0666));  /* -rw-rw-rw- */
732    if (fd < 0) {
733        fprintf(stderr, "%s: %s\n", traces_path, strerror(errno));
734        return NULL;
735    }
736    int chmod_ret = fchmod(fd, 0666);
737    if (chmod_ret < 0) {
738        fprintf(stderr, "fchmod on %s failed: %s\n", traces_path, strerror(errno));
739        close(fd);
740        return NULL;
741    }
742
743    /* Variables below must be initialized before 'goto' statements */
744    int dalvik_found = 0;
745    int ifd, wfd = -1;
746
747    /* walk /proc and kill -QUIT all Dalvik processes */
748    DIR *proc = opendir("/proc");
749    if (proc == NULL) {
750        fprintf(stderr, "/proc: %s\n", strerror(errno));
751        goto error_close_fd;
752    }
753
754    /* use inotify to find when processes are done dumping */
755    ifd = inotify_init();
756    if (ifd < 0) {
757        fprintf(stderr, "inotify_init: %s\n", strerror(errno));
758        goto error_close_fd;
759    }
760
761    wfd = inotify_add_watch(ifd, traces_path, IN_CLOSE_WRITE);
762    if (wfd < 0) {
763        fprintf(stderr, "inotify_add_watch(%s): %s\n", traces_path, strerror(errno));
764        goto error_close_ifd;
765    }
766
767    struct dirent *d;
768    while ((d = readdir(proc))) {
769        int pid = atoi(d->d_name);
770        if (pid <= 0) continue;
771
772        char path[PATH_MAX];
773        char data[PATH_MAX];
774        snprintf(path, sizeof(path), "/proc/%d/exe", pid);
775        ssize_t len = readlink(path, data, sizeof(data) - 1);
776        if (len <= 0) {
777            continue;
778        }
779        data[len] = '\0';
780
781        if (!strncmp(data, "/system/bin/app_process", strlen("/system/bin/app_process"))) {
782            /* skip zygote -- it won't dump its stack anyway */
783            snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
784            int cfd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC));
785            len = read(cfd, data, sizeof(data) - 1);
786            close(cfd);
787            if (len <= 0) {
788                continue;
789            }
790            data[len] = '\0';
791            if (!strncmp(data, "zygote", strlen("zygote"))) {
792                continue;
793            }
794
795            ++dalvik_found;
796            uint64_t start = DurationReporter::nanotime();
797            if (kill(pid, SIGQUIT)) {
798                fprintf(stderr, "kill(%d, SIGQUIT): %s\n", pid, strerror(errno));
799                continue;
800            }
801
802            /* wait for the writable-close notification from inotify */
803            struct pollfd pfd = { ifd, POLLIN, 0 };
804            int ret = poll(&pfd, 1, 5000);  /* 5 sec timeout */
805            if (ret < 0) {
806                fprintf(stderr, "poll: %s\n", strerror(errno));
807            } else if (ret == 0) {
808                fprintf(stderr, "warning: timed out dumping pid %d\n", pid);
809            } else {
810                struct inotify_event ie;
811                read(ifd, &ie, sizeof(ie));
812            }
813
814            if (lseek(fd, 0, SEEK_END) < 0) {
815                fprintf(stderr, "lseek: %s\n", strerror(errno));
816            } else {
817                dprintf(fd, "[dump dalvik stack %d: %.3fs elapsed]\n",
818                        pid, (float)(DurationReporter::nanotime() - start) / NANOS_PER_SEC);
819            }
820        } else if (should_dump_native_traces(data)) {
821            /* dump native process if appropriate */
822            if (lseek(fd, 0, SEEK_END) < 0) {
823                fprintf(stderr, "lseek: %s\n", strerror(errno));
824            } else {
825                static uint16_t timeout_failures = 0;
826                uint64_t start = DurationReporter::nanotime();
827
828                /* If 3 backtrace dumps fail in a row, consider debuggerd dead. */
829                if (timeout_failures == 3) {
830                    dprintf(fd, "too many stack dump failures, skipping...\n");
831                } else if (dump_backtrace_to_file_timeout(pid, fd, 20) == -1) {
832                    dprintf(fd, "dumping failed, likely due to a timeout\n");
833                    timeout_failures++;
834                } else {
835                    timeout_failures = 0;
836                }
837                dprintf(fd, "[dump native stack %d: %.3fs elapsed]\n",
838                        pid, (float)(DurationReporter::nanotime() - start) / NANOS_PER_SEC);
839            }
840        }
841    }
842
843    if (dalvik_found == 0) {
844        fprintf(stderr, "Warning: no Dalvik processes found to dump stacks\n");
845    }
846
847    static char dump_traces_path[PATH_MAX];
848    strlcpy(dump_traces_path, traces_path, sizeof(dump_traces_path));
849    strlcat(dump_traces_path, ".bugreport", sizeof(dump_traces_path));
850    if (rename(traces_path, dump_traces_path)) {
851        fprintf(stderr, "rename(%s, %s): %s\n", traces_path, dump_traces_path, strerror(errno));
852        goto error_close_ifd;
853    }
854    result = dump_traces_path;
855
856    /* replace the saved [ANR] traces.txt file */
857    rename(anr_traces_path, traces_path);
858
859error_close_ifd:
860    close(ifd);
861error_close_fd:
862    close(fd);
863    return result;
864}
865
866void dump_route_tables() {
867    DurationReporter duration_reporter("DUMP ROUTE TABLES");
868    ON_DRY_RUN_RETURN();
869    const char* const RT_TABLES_PATH = "/data/misc/net/rt_tables";
870    dump_file("RT_TABLES", RT_TABLES_PATH);
871    FILE* fp = fopen(RT_TABLES_PATH, "re");
872    if (!fp) {
873        printf("*** %s: %s\n", RT_TABLES_PATH, strerror(errno));
874        return;
875    }
876    char table[16];
877    // Each line has an integer (the table number), a space, and a string (the table name). We only
878    // need the table number. It's a 32-bit unsigned number, so max 10 chars. Skip the table name.
879    // Add a fixed max limit so this doesn't go awry.
880    for (int i = 0; i < 64 && fscanf(fp, " %10s %*s", table) == 1; ++i) {
881        run_command("ROUTE TABLE IPv4", 10, "ip", "-4", "route", "show", "table", table, NULL);
882        run_command("ROUTE TABLE IPv6", 10, "ip", "-6", "route", "show", "table", table, NULL);
883    }
884    fclose(fp);
885}
886
887/* overall progress */
888int progress = 0;
889int do_update_progress = 0; // Set by dumpstate.cpp
890int weight_total = WEIGHT_TOTAL;
891
892// TODO: make this function thread safe if sections are generated in parallel.
893void update_progress(int delta) {
894    if (!do_update_progress) return;
895
896    progress += delta;
897
898    char key[PROPERTY_KEY_MAX];
899    char value[PROPERTY_VALUE_MAX];
900
901    // adjusts max on the fly
902    if (progress > weight_total) {
903        int new_total = weight_total * 1.2;
904        fprintf(stderr, "Adjusting total weight from %d to %d\n", weight_total, new_total);
905        weight_total = new_total;
906        sprintf(key, "dumpstate.%d.max", getpid());
907        sprintf(value, "%d", weight_total);
908        int status = property_set(key, value);
909        if (status) {
910            ALOGW("Could not update max weight by setting system property %s to %s: %d\n",
911                    key, value, status);
912        }
913    }
914
915    sprintf(key, "dumpstate.%d.progress", getpid());
916    sprintf(value, "%d", progress);
917
918    // stderr is ignored on normal invocations, but useful when calling /system/bin/dumpstate
919    // directly for debuggging.
920    fprintf(stderr, "Setting progress (%s): %s/%d\n", key, value, weight_total);
921
922    int status = property_set(key, value);
923    if (status) {
924        ALOGW("Could not update progress by setting system property %s to %s: %d\n",
925                key, value, status);
926    }
927}
928
929void take_screenshot(const std::string& path) {
930    const char *args[] = { "/system/bin/screencap", "-p", path.c_str(), NULL };
931    run_command_always(NULL, 10, args);
932}
933
934void vibrate(FILE* vibrator, int ms) {
935    fprintf(vibrator, "%d\n", ms);
936    fflush(vibrator);
937}
938
939bool is_dir(const char* pathname) {
940    struct stat info;
941    if (stat(pathname, &info) == -1) {
942        return false;
943    }
944    return S_ISDIR(info.st_mode);
945}
946
947time_t get_mtime(int fd, time_t default_mtime) {
948    struct stat info;
949    if (fstat(fd, &info) == -1) {
950        return default_mtime;
951    }
952    return info.st_mtime;
953}
954
955void dump_emmc_ecsd(const char *ext_csd_path) {
956    static const size_t EXT_CSD_REV = 192;
957    static const size_t EXT_PRE_EOL_INFO = 267;
958    static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_A = 268;
959    static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_B = 269;
960    struct hex {
961        char str[2];
962    } buffer[512];
963    int fd, ext_csd_rev, ext_pre_eol_info;
964    ssize_t bytes_read;
965    static const char *ver_str[] = {
966        "4.0", "4.1", "4.2", "4.3", "Obsolete", "4.41", "4.5", "5.0"
967    };
968    static const char *eol_str[] = {
969        "Undefined",
970        "Normal",
971        "Warning (consumed 80% of reserve)",
972        "Urgent (consumed 90% of reserve)"
973    };
974
975    printf("------ %s Extended CSD ------\n", ext_csd_path);
976
977    fd = TEMP_FAILURE_RETRY(open(ext_csd_path,
978                                 O_RDONLY | O_NONBLOCK | O_CLOEXEC));
979    if (fd < 0) {
980        printf("*** %s: %s\n\n", ext_csd_path, strerror(errno));
981        return;
982    }
983
984    bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
985    close(fd);
986    if (bytes_read < 0) {
987        printf("*** %s: %s\n\n", ext_csd_path, strerror(errno));
988        return;
989    }
990    if (bytes_read < (ssize_t)(EXT_CSD_REV * sizeof(struct hex))) {
991        printf("*** %s: truncated content %zd\n\n", ext_csd_path, bytes_read);
992        return;
993    }
994
995    ext_csd_rev = 0;
996    if (sscanf(buffer[EXT_CSD_REV].str, "%02x", &ext_csd_rev) != 1) {
997        printf("*** %s: EXT_CSD_REV parse error \"%.2s\"\n\n",
998               ext_csd_path, buffer[EXT_CSD_REV].str);
999        return;
1000    }
1001
1002    printf("rev 1.%d (MMC %s)\n",
1003           ext_csd_rev,
1004           (ext_csd_rev < (int)(sizeof(ver_str) / sizeof(ver_str[0]))) ?
1005               ver_str[ext_csd_rev] :
1006               "Unknown");
1007    if (ext_csd_rev < 7) {
1008        printf("\n");
1009        return;
1010    }
1011
1012    if (bytes_read < (ssize_t)(EXT_PRE_EOL_INFO * sizeof(struct hex))) {
1013        printf("*** %s: truncated content %zd\n\n", ext_csd_path, bytes_read);
1014        return;
1015    }
1016
1017    ext_pre_eol_info = 0;
1018    if (sscanf(buffer[EXT_PRE_EOL_INFO].str, "%02x", &ext_pre_eol_info) != 1) {
1019        printf("*** %s: PRE_EOL_INFO parse error \"%.2s\"\n\n",
1020               ext_csd_path, buffer[EXT_PRE_EOL_INFO].str);
1021        return;
1022    }
1023    printf("PRE_EOL_INFO %d (MMC %s)\n",
1024           ext_pre_eol_info,
1025           eol_str[(ext_pre_eol_info < (int)
1026                       (sizeof(eol_str) / sizeof(eol_str[0]))) ?
1027                           ext_pre_eol_info : 0]);
1028
1029    for (size_t lifetime = EXT_DEVICE_LIFE_TIME_EST_TYP_A;
1030            lifetime <= EXT_DEVICE_LIFE_TIME_EST_TYP_B;
1031            ++lifetime) {
1032        int ext_device_life_time_est;
1033        static const char *est_str[] = {
1034            "Undefined",
1035            "0-10% of device lifetime used",
1036            "10-20% of device lifetime used",
1037            "20-30% of device lifetime used",
1038            "30-40% of device lifetime used",
1039            "40-50% of device lifetime used",
1040            "50-60% of device lifetime used",
1041            "60-70% of device lifetime used",
1042            "70-80% of device lifetime used",
1043            "80-90% of device lifetime used",
1044            "90-100% of device lifetime used",
1045            "Exceeded the maximum estimated device lifetime",
1046        };
1047
1048        if (bytes_read < (ssize_t)(lifetime * sizeof(struct hex))) {
1049            printf("*** %s: truncated content %zd\n", ext_csd_path, bytes_read);
1050            break;
1051        }
1052
1053        ext_device_life_time_est = 0;
1054        if (sscanf(buffer[lifetime].str, "%02x", &ext_device_life_time_est) != 1) {
1055            printf("*** %s: DEVICE_LIFE_TIME_EST_TYP_%c parse error \"%.2s\"\n",
1056                   ext_csd_path,
1057                   (unsigned)(lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) + 'A',
1058                   buffer[lifetime].str);
1059            continue;
1060        }
1061        printf("DEVICE_LIFE_TIME_EST_TYP_%c %d (MMC %s)\n",
1062               (unsigned)(lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) + 'A',
1063               ext_device_life_time_est,
1064               est_str[(ext_device_life_time_est < (int)
1065                           (sizeof(est_str) / sizeof(est_str[0]))) ?
1066                               ext_device_life_time_est : 0]);
1067    }
1068
1069    printf("\n");
1070}
1071