utils.c revision 7dc7f3221f26b771c266a26ec785eb74287922f1
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.h>
27#include <sys/inotify.h>
28#include <sys/stat.h>
29#include <sys/time.h>
30#include <sys/wait.h>
31#include <sys/klog.h>
32#include <time.h>
33#include <unistd.h>
34#include <sys/prctl.h>
35
36#include <cutils/debugger.h>
37#include <cutils/properties.h>
38#include <cutils/sockets.h>
39#include <private/android_filesystem_config.h>
40
41#include <selinux/android.h>
42
43#include "dumpstate.h"
44
45/* list of native processes to include in the native dumps */
46static const char* native_processes_to_dump[] = {
47        "/system/bin/drmserver",
48        "/system/bin/mediaserver",
49        "/system/bin/sdcard",
50        "/system/bin/surfaceflinger",
51        NULL,
52};
53
54void for_each_userid(void (*func)(int), const char *header) {
55    DIR *d;
56    struct dirent *de;
57
58    if (header) printf("\n------ %s ------\n", header);
59    func(0);
60
61    if (!(d = opendir("/data/system/users"))) {
62        printf("Failed to open /data/system/users (%s)\n", strerror(errno));
63        return;
64    }
65
66    while ((de = readdir(d))) {
67        int userid;
68        if (de->d_type != DT_DIR || !(userid = atoi(de->d_name))) {
69            continue;
70        }
71        func(userid);
72    }
73
74    closedir(d);
75}
76
77static void __for_each_pid(void (*helper)(int, const char *, void *), const char *header, void *arg) {
78    DIR *d;
79    struct dirent *de;
80
81    if (!(d = opendir("/proc"))) {
82        printf("Failed to open /proc (%s)\n", strerror(errno));
83        return;
84    }
85
86    printf("\n------ %s ------\n", header);
87    while ((de = readdir(d))) {
88        int pid;
89        int fd;
90        char cmdpath[255];
91        char cmdline[255];
92
93        if (!(pid = atoi(de->d_name))) {
94            continue;
95        }
96
97        sprintf(cmdpath,"/proc/%d/cmdline", pid);
98        memset(cmdline, 0, sizeof(cmdline));
99        if ((fd = open(cmdpath, O_RDONLY)) < 0) {
100            strcpy(cmdline, "N/A");
101        } else {
102            read(fd, cmdline, sizeof(cmdline) - 1);
103            close(fd);
104        }
105        helper(pid, cmdline, arg);
106    }
107
108    closedir(d);
109}
110
111static void for_each_pid_helper(int pid, const char *cmdline, void *arg) {
112    for_each_pid_func *func = arg;
113    func(pid, cmdline);
114}
115
116void for_each_pid(for_each_pid_func func, const char *header) {
117    __for_each_pid(for_each_pid_helper, header, func);
118}
119
120static void for_each_tid_helper(int pid, const char *cmdline, void *arg) {
121    DIR *d;
122    struct dirent *de;
123    char taskpath[255];
124    for_each_tid_func *func = arg;
125
126    sprintf(taskpath, "/proc/%d/task", pid);
127
128    if (!(d = opendir(taskpath))) {
129        printf("Failed to open %s (%s)\n", taskpath, strerror(errno));
130        return;
131    }
132
133    func(pid, pid, cmdline);
134
135    while ((de = readdir(d))) {
136        int tid;
137        int fd;
138        char commpath[255];
139        char comm[255];
140
141        if (!(tid = atoi(de->d_name))) {
142            continue;
143        }
144
145        if (tid == pid)
146            continue;
147
148        sprintf(commpath,"/proc/%d/comm", tid);
149        memset(comm, 0, sizeof(comm));
150        if ((fd = open(commpath, O_RDONLY)) < 0) {
151            strcpy(comm, "N/A");
152        } else {
153            char *c;
154            read(fd, comm, sizeof(comm) - 1);
155            close(fd);
156
157            c = strrchr(comm, '\n');
158            if (c) {
159                *c = '\0';
160            }
161        }
162        func(pid, tid, comm);
163    }
164
165    closedir(d);
166}
167
168void for_each_tid(for_each_tid_func func, const char *header) {
169    __for_each_pid(for_each_tid_helper, header, func);
170}
171
172void show_wchan(int pid, int tid, const char *name) {
173    char path[255];
174    char buffer[255];
175    int fd;
176    char name_buffer[255];
177
178    memset(buffer, 0, sizeof(buffer));
179
180    sprintf(path, "/proc/%d/wchan", tid);
181    if ((fd = open(path, O_RDONLY)) < 0) {
182        printf("Failed to open '%s' (%s)\n", path, strerror(errno));
183        return;
184    }
185
186    if (read(fd, buffer, sizeof(buffer)) < 0) {
187        printf("Failed to read '%s' (%s)\n", path, strerror(errno));
188        goto out_close;
189    }
190
191    snprintf(name_buffer, sizeof(name_buffer), "%*s%s",
192             pid == tid ? 0 : 3, "", name);
193
194    printf("%-7d %-32s %s\n", tid, name_buffer, buffer);
195
196out_close:
197    close(fd);
198    return;
199}
200
201void do_dump_settings(int userid) {
202    char title[255];
203    char dbpath[255];
204    char sql[255];
205    sprintf(title, "SYSTEM SETTINGS (user %d)", userid);
206    if (userid == 0) {
207        strcpy(dbpath, "/data/data/com.android.providers.settings/databases/settings.db");
208        strcpy(sql, "pragma user_version; select * from system; select * from secure; select * from global;");
209    } else {
210        sprintf(dbpath, "/data/system/users/%d/settings.db", userid);
211        strcpy(sql, "pragma user_version; select * from system; select * from secure;");
212    }
213    run_command(title, 20, SU_PATH, "root", "sqlite3", dbpath, sql, NULL);
214    return;
215}
216
217void do_dmesg() {
218    printf("------ KERNEL LOG (dmesg) ------\n");
219    /* Get size of kernel buffer */
220    int size = klogctl(KLOG_SIZE_BUFFER, NULL, 0);
221    if (size <= 0) {
222        printf("Unexpected klogctl return value: %d\n\n", size);
223        return;
224    }
225    char *buf = (char *) malloc(size + 1);
226    if (buf == NULL) {
227        printf("memory allocation failed\n\n");
228        return;
229    }
230    int retval = klogctl(KLOG_READ_ALL, buf, size);
231    if (retval < 0) {
232        printf("klogctl failure\n\n");
233        free(buf);
234        return;
235    }
236    buf[retval] = '\0';
237    printf("%s\n\n", buf);
238    free(buf);
239    return;
240}
241
242void do_showmap(int pid, const char *name) {
243    char title[255];
244    char arg[255];
245
246    sprintf(title, "SHOW MAP %d (%s)", pid, name);
247    sprintf(arg, "%d", pid);
248    run_command(title, 10, SU_PATH, "root", "showmap", arg, NULL);
249}
250
251/* prints the contents of a file */
252int dump_file(const char *title, const char *path) {
253    int fd = open(path, O_RDONLY);
254    if (fd < 0) {
255        int err = errno;
256        if (title) printf("------ %s (%s) ------\n", title, path);
257        printf("*** %s: %s\n", path, strerror(err));
258        if (title) printf("\n");
259        return -1;
260    }
261    return dump_file_from_fd(title, path, fd);
262}
263
264int dump_file_from_fd(const char *title, const char *path, int fd) {
265    char buffer[32768];
266
267    if (title) printf("------ %s (%s", title, path);
268
269    if (title) {
270        struct stat st;
271        if (memcmp(path, "/proc/", 6) && memcmp(path, "/sys/", 5) && !fstat(fd, &st)) {
272            char stamp[80];
273            time_t mtime = st.st_mtime;
274            strftime(stamp, sizeof(stamp), "%Y-%m-%d %H:%M:%S", localtime(&mtime));
275            printf(": %s", stamp);
276        }
277        printf(") ------\n");
278    }
279
280    int newline = 0;
281    for (;;) {
282        int ret = read(fd, buffer, sizeof(buffer));
283        if (ret > 0) {
284            newline = (buffer[ret - 1] == '\n');
285            ret = fwrite(buffer, ret, 1, stdout);
286        }
287        if (ret <= 0) break;
288    }
289    close(fd);
290
291    if (!newline) printf("\n");
292    if (title) printf("\n");
293    return 0;
294}
295
296/* forks a command and waits for it to finish */
297int run_command(const char *title, int timeout_seconds, const char *command, ...) {
298    fflush(stdout);
299    clock_t start = clock();
300    pid_t pid = fork();
301
302    /* handle error case */
303    if (pid < 0) {
304        printf("*** fork: %s\n", strerror(errno));
305        return pid;
306    }
307
308    /* handle child case */
309    if (pid == 0) {
310        const char *args[1024] = {command};
311        size_t arg;
312
313        /* make sure the child dies when dumpstate dies */
314        prctl(PR_SET_PDEATHSIG, SIGKILL);
315
316        va_list ap;
317        va_start(ap, command);
318        if (title) printf("------ %s (%s", title, command);
319        for (arg = 1; arg < sizeof(args) / sizeof(args[0]); ++arg) {
320            args[arg] = va_arg(ap, const char *);
321            if (args[arg] == NULL) break;
322            if (title) printf(" %s", args[arg]);
323        }
324        if (title) printf(") ------\n");
325        fflush(stdout);
326
327        execvp(command, (char**) args);
328        printf("*** exec(%s): %s\n", command, strerror(errno));
329        fflush(stdout);
330        _exit(-1);
331    }
332
333    /* handle parent case */
334    for (;;) {
335        int status;
336        pid_t p = waitpid(pid, &status, WNOHANG);
337        float elapsed = (float) (clock() - start) / CLOCKS_PER_SEC;
338        if (p == pid) {
339            if (WIFSIGNALED(status)) {
340                printf("*** %s: Killed by signal %d\n", command, WTERMSIG(status));
341            } else if (WIFEXITED(status) && WEXITSTATUS(status) > 0) {
342                printf("*** %s: Exit code %d\n", command, WEXITSTATUS(status));
343            }
344            if (title) printf("[%s: %.1fs elapsed]\n\n", command, elapsed);
345            return status;
346        }
347
348        if (timeout_seconds && elapsed > timeout_seconds) {
349            printf("*** %s: Timed out after %.1fs (killing pid %d)\n", command, elapsed, pid);
350            kill(pid, SIGTERM);
351            return -1;
352        }
353
354        usleep(100000);  // poll every 0.1 sec
355    }
356}
357
358size_t num_props = 0;
359static char* props[2000];
360
361static void print_prop(const char *key, const char *name, void *user) {
362    (void) user;
363    if (num_props < sizeof(props) / sizeof(props[0])) {
364        char buf[PROPERTY_KEY_MAX + PROPERTY_VALUE_MAX + 10];
365        snprintf(buf, sizeof(buf), "[%s]: [%s]\n", key, name);
366        props[num_props++] = strdup(buf);
367    }
368}
369
370static int compare_prop(const void *a, const void *b) {
371    return strcmp(*(char * const *) a, *(char * const *) b);
372}
373
374/* prints all the system properties */
375void print_properties() {
376    size_t i;
377    num_props = 0;
378    property_list(print_prop, NULL);
379    qsort(&props, num_props, sizeof(props[0]), compare_prop);
380
381    printf("------ SYSTEM PROPERTIES ------\n");
382    for (i = 0; i < num_props; ++i) {
383        fputs(props[i], stdout);
384        free(props[i]);
385    }
386    printf("\n");
387}
388
389/* redirect output to a service control socket */
390void redirect_to_socket(FILE *redirect, const char *service) {
391    int s = android_get_control_socket(service);
392    if (s < 0) {
393        fprintf(stderr, "android_get_control_socket(%s): %s\n", service, strerror(errno));
394        exit(1);
395    }
396    if (listen(s, 4) < 0) {
397        fprintf(stderr, "listen(control socket): %s\n", strerror(errno));
398        exit(1);
399    }
400
401    struct sockaddr addr;
402    socklen_t alen = sizeof(addr);
403    int fd = accept(s, &addr, &alen);
404    if (fd < 0) {
405        fprintf(stderr, "accept(control socket): %s\n", strerror(errno));
406        exit(1);
407    }
408
409    fflush(redirect);
410    dup2(fd, fileno(redirect));
411    close(fd);
412}
413
414/* redirect output to a file, optionally gzipping; returns gzip pid (or -1) */
415pid_t redirect_to_file(FILE *redirect, char *path, int gzip_level) {
416    char *chp = path;
417
418    /* skip initial slash */
419    if (chp[0] == '/')
420        chp++;
421
422    /* create leading directories, if necessary */
423    while (chp && chp[0]) {
424        chp = strchr(chp, '/');
425        if (chp) {
426            *chp = 0;
427            mkdir(path, 0770);  /* drwxrwx--- */
428            *chp++ = '/';
429        }
430    }
431
432    int fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
433    if (fd < 0) {
434        fprintf(stderr, "%s: %s\n", path, strerror(errno));
435        exit(1);
436    }
437
438    pid_t gzip_pid = -1;
439    if (gzip_level > 0) {
440        int fds[2];
441        if (pipe(fds)) {
442            fprintf(stderr, "pipe: %s\n", strerror(errno));
443            exit(1);
444        }
445
446        fflush(redirect);
447        fflush(stdout);
448
449        gzip_pid = fork();
450        if (gzip_pid < 0) {
451            fprintf(stderr, "fork: %s\n", strerror(errno));
452            exit(1);
453        }
454
455        if (gzip_pid == 0) {
456            dup2(fds[0], STDIN_FILENO);
457            dup2(fd, STDOUT_FILENO);
458
459            close(fd);
460            close(fds[0]);
461            close(fds[1]);
462
463            char level[10];
464            snprintf(level, sizeof(level), "-%d", gzip_level);
465            execlp("gzip", "gzip", level, NULL);
466            fprintf(stderr, "exec(gzip): %s\n", strerror(errno));
467            _exit(-1);
468        }
469
470        close(fd);
471        close(fds[0]);
472        fd = fds[1];
473    }
474
475    dup2(fd, fileno(redirect));
476    close(fd);
477    return gzip_pid;
478}
479
480static bool should_dump_native_traces(const char* path) {
481    for (const char** p = native_processes_to_dump; *p; p++) {
482        if (!strcmp(*p, path)) {
483            return true;
484        }
485    }
486    return false;
487}
488
489/* dump Dalvik and native stack traces, return the trace file location (NULL if none) */
490const char *dump_traces() {
491    const char* result = NULL;
492
493    char traces_path[PROPERTY_VALUE_MAX] = "";
494    property_get("dalvik.vm.stack-trace-file", traces_path, "");
495    if (!traces_path[0]) return NULL;
496
497    /* move the old traces.txt (if any) out of the way temporarily */
498    char anr_traces_path[PATH_MAX];
499    strlcpy(anr_traces_path, traces_path, sizeof(anr_traces_path));
500    strlcat(anr_traces_path, ".anr", sizeof(anr_traces_path));
501    if (rename(traces_path, anr_traces_path) && errno != ENOENT) {
502        fprintf(stderr, "rename(%s, %s): %s\n", traces_path, anr_traces_path, strerror(errno));
503        return NULL;  // Can't rename old traces.txt -- no permission? -- leave it alone instead
504    }
505
506    /* make the directory if necessary */
507    char anr_traces_dir[PATH_MAX];
508    strlcpy(anr_traces_dir, traces_path, sizeof(anr_traces_dir));
509    char *slash = strrchr(anr_traces_dir, '/');
510    if (slash != NULL) {
511        *slash = '\0';
512        if (!mkdir(anr_traces_dir, 0775)) {
513            chown(anr_traces_dir, AID_SYSTEM, AID_SYSTEM);
514            chmod(anr_traces_dir, 0775);
515            if (selinux_android_restorecon(anr_traces_dir, 0) == -1) {
516                fprintf(stderr, "restorecon failed for %s: %s\n", anr_traces_dir, strerror(errno));
517            }
518        } else if (errno != EEXIST) {
519            fprintf(stderr, "mkdir(%s): %s\n", anr_traces_dir, strerror(errno));
520            return NULL;
521        }
522    }
523
524    /* create a new, empty traces.txt file to receive stack dumps */
525    int fd = open(traces_path, O_CREAT | O_WRONLY | O_TRUNC | O_NOFOLLOW, 0666);  /* -rw-rw-rw- */
526    if (fd < 0) {
527        fprintf(stderr, "%s: %s\n", traces_path, strerror(errno));
528        return NULL;
529    }
530    int chmod_ret = fchmod(fd, 0666);
531    if (chmod_ret < 0) {
532        fprintf(stderr, "fchmod on %s failed: %s\n", traces_path, strerror(errno));
533        close(fd);
534        return NULL;
535    }
536
537    /* walk /proc and kill -QUIT all Dalvik processes */
538    DIR *proc = opendir("/proc");
539    if (proc == NULL) {
540        fprintf(stderr, "/proc: %s\n", strerror(errno));
541        goto error_close_fd;
542    }
543
544    /* use inotify to find when processes are done dumping */
545    int ifd = inotify_init();
546    if (ifd < 0) {
547        fprintf(stderr, "inotify_init: %s\n", strerror(errno));
548        goto error_close_fd;
549    }
550
551    int wfd = inotify_add_watch(ifd, traces_path, IN_CLOSE_WRITE);
552    if (wfd < 0) {
553        fprintf(stderr, "inotify_add_watch(%s): %s\n", traces_path, strerror(errno));
554        goto error_close_ifd;
555    }
556
557    struct dirent *d;
558    int dalvik_found = 0;
559    while ((d = readdir(proc))) {
560        int pid = atoi(d->d_name);
561        if (pid <= 0) continue;
562
563        char path[PATH_MAX];
564        char data[PATH_MAX];
565        snprintf(path, sizeof(path), "/proc/%d/exe", pid);
566        ssize_t len = readlink(path, data, sizeof(data) - 1);
567        if (len <= 0) {
568            continue;
569        }
570        data[len] = '\0';
571
572        if (!strncmp(data, "/system/bin/app_process", strlen("/system/bin/app_process"))) {
573            /* skip zygote -- it won't dump its stack anyway */
574            snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
575            int fd = open(path, O_RDONLY);
576            len = read(fd, data, sizeof(data) - 1);
577            close(fd);
578            if (len <= 0) {
579                continue;
580            }
581            data[len] = '\0';
582            if (!strncmp(data, "zygote", strlen("zygote"))) {
583                continue;
584            }
585
586            ++dalvik_found;
587            if (kill(pid, SIGQUIT)) {
588                fprintf(stderr, "kill(%d, SIGQUIT): %s\n", pid, strerror(errno));
589                continue;
590            }
591
592            /* wait for the writable-close notification from inotify */
593            struct pollfd pfd = { ifd, POLLIN, 0 };
594            int ret = poll(&pfd, 1, 5000);  /* 5 sec timeout */
595            if (ret < 0) {
596                fprintf(stderr, "poll: %s\n", strerror(errno));
597            } else if (ret == 0) {
598                fprintf(stderr, "warning: timed out dumping pid %d\n", pid);
599            } else {
600                struct inotify_event ie;
601                read(ifd, &ie, sizeof(ie));
602            }
603        } else if (should_dump_native_traces(data)) {
604            /* dump native process if appropriate */
605            if (lseek(fd, 0, SEEK_END) < 0) {
606                fprintf(stderr, "lseek: %s\n", strerror(errno));
607            } else {
608                dump_backtrace_to_file(pid, fd);
609            }
610        }
611    }
612
613    if (dalvik_found == 0) {
614        fprintf(stderr, "Warning: no Dalvik processes found to dump stacks\n");
615    }
616
617    static char dump_traces_path[PATH_MAX];
618    strlcpy(dump_traces_path, traces_path, sizeof(dump_traces_path));
619    strlcat(dump_traces_path, ".bugreport", sizeof(dump_traces_path));
620    if (rename(traces_path, dump_traces_path)) {
621        fprintf(stderr, "rename(%s, %s): %s\n", traces_path, dump_traces_path, strerror(errno));
622        goto error_close_ifd;
623    }
624    result = dump_traces_path;
625
626    /* replace the saved [ANR] traces.txt file */
627    rename(anr_traces_path, traces_path);
628
629error_close_ifd:
630    close(ifd);
631error_close_fd:
632    close(fd);
633    return result;
634}
635
636void play_sound(const char* path) {
637    run_command(NULL, 5, "/system/bin/stagefright", "-o", "-a", path, NULL);
638}
639
640void dump_route_tables() {
641    const char* const RT_TABLES_PATH = "/data/misc/net/rt_tables";
642    dump_file("RT_TABLES", RT_TABLES_PATH);
643    FILE* fp = fopen(RT_TABLES_PATH, "r");
644    if (!fp) {
645        printf("*** %s: %s\n", RT_TABLES_PATH, strerror(errno));
646        return;
647    }
648    char table[16];
649    // Each line has an integer (the table number), a space, and a string (the table name). We only
650    // need the table number. It's a 32-bit unsigned number, so max 10 chars. Skip the table name.
651    // Add a fixed max limit so this doesn't go awry.
652    for (int i = 0; i < 64 && fscanf(fp, " %10s %*s", table) == 1; ++i) {
653        run_command("ROUTE TABLE IPv4", 10, "ip", "-4", "route", "show", "table", table, NULL);
654        run_command("ROUTE TABLE IPv6", 10, "ip", "-6", "route", "show", "table", table, NULL);
655    }
656    fclose(fp);
657}
658