utils.c revision 165c8bdfb585b224325423b21301620f9097dc64
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    char buffer[32768];
254    int fd = open(path, O_RDONLY);
255    if (fd < 0) {
256        int err = errno;
257        if (title) printf("------ %s (%s) ------\n", title, path);
258        printf("*** %s: %s\n", path, strerror(err));
259        if (title) printf("\n");
260        return -1;
261    }
262
263    if (title) printf("------ %s (%s", title, path);
264
265    if (title) {
266        struct stat st;
267        if (memcmp(path, "/proc/", 6) && memcmp(path, "/sys/", 5) && !fstat(fd, &st)) {
268            char stamp[80];
269            time_t mtime = st.st_mtime;
270            strftime(stamp, sizeof(stamp), "%Y-%m-%d %H:%M:%S", localtime(&mtime));
271            printf(": %s", stamp);
272        }
273        printf(") ------\n");
274    }
275
276    int newline = 0;
277    for (;;) {
278        int ret = read(fd, buffer, sizeof(buffer));
279        if (ret > 0) {
280            newline = (buffer[ret - 1] == '\n');
281            ret = fwrite(buffer, ret, 1, stdout);
282        }
283        if (ret <= 0) break;
284    }
285
286    close(fd);
287    if (!newline) printf("\n");
288    if (title) printf("\n");
289    return 0;
290}
291
292/* forks a command and waits for it to finish */
293int run_command(const char *title, int timeout_seconds, const char *command, ...) {
294    fflush(stdout);
295    clock_t start = clock();
296    pid_t pid = fork();
297
298    /* handle error case */
299    if (pid < 0) {
300        printf("*** fork: %s\n", strerror(errno));
301        return pid;
302    }
303
304    /* handle child case */
305    if (pid == 0) {
306        const char *args[1024] = {command};
307        size_t arg;
308
309        /* make sure the child dies when dumpstate dies */
310        prctl(PR_SET_PDEATHSIG, SIGKILL);
311
312        va_list ap;
313        va_start(ap, command);
314        if (title) printf("------ %s (%s", title, command);
315        for (arg = 1; arg < sizeof(args) / sizeof(args[0]); ++arg) {
316            args[arg] = va_arg(ap, const char *);
317            if (args[arg] == NULL) break;
318            if (title) printf(" %s", args[arg]);
319        }
320        if (title) printf(") ------\n");
321        fflush(stdout);
322
323        execvp(command, (char**) args);
324        printf("*** exec(%s): %s\n", command, strerror(errno));
325        fflush(stdout);
326        _exit(-1);
327    }
328
329    /* handle parent case */
330    for (;;) {
331        int status;
332        pid_t p = waitpid(pid, &status, WNOHANG);
333        float elapsed = (float) (clock() - start) / CLOCKS_PER_SEC;
334        if (p == pid) {
335            if (WIFSIGNALED(status)) {
336                printf("*** %s: Killed by signal %d\n", command, WTERMSIG(status));
337            } else if (WIFEXITED(status) && WEXITSTATUS(status) > 0) {
338                printf("*** %s: Exit code %d\n", command, WEXITSTATUS(status));
339            }
340            if (title) printf("[%s: %.1fs elapsed]\n\n", command, elapsed);
341            return status;
342        }
343
344        if (timeout_seconds && elapsed > timeout_seconds) {
345            printf("*** %s: Timed out after %.1fs (killing pid %d)\n", command, elapsed, pid);
346            kill(pid, SIGTERM);
347            return -1;
348        }
349
350        usleep(100000);  // poll every 0.1 sec
351    }
352}
353
354size_t num_props = 0;
355static char* props[2000];
356
357static void print_prop(const char *key, const char *name, void *user) {
358    (void) user;
359    if (num_props < sizeof(props) / sizeof(props[0])) {
360        char buf[PROPERTY_KEY_MAX + PROPERTY_VALUE_MAX + 10];
361        snprintf(buf, sizeof(buf), "[%s]: [%s]\n", key, name);
362        props[num_props++] = strdup(buf);
363    }
364}
365
366static int compare_prop(const void *a, const void *b) {
367    return strcmp(*(char * const *) a, *(char * const *) b);
368}
369
370/* prints all the system properties */
371void print_properties() {
372    size_t i;
373    num_props = 0;
374    property_list(print_prop, NULL);
375    qsort(&props, num_props, sizeof(props[0]), compare_prop);
376
377    printf("------ SYSTEM PROPERTIES ------\n");
378    for (i = 0; i < num_props; ++i) {
379        fputs(props[i], stdout);
380        free(props[i]);
381    }
382    printf("\n");
383}
384
385/* redirect output to a service control socket */
386void redirect_to_socket(FILE *redirect, const char *service) {
387    int s = android_get_control_socket(service);
388    if (s < 0) {
389        fprintf(stderr, "android_get_control_socket(%s): %s\n", service, strerror(errno));
390        exit(1);
391    }
392    if (listen(s, 4) < 0) {
393        fprintf(stderr, "listen(control socket): %s\n", strerror(errno));
394        exit(1);
395    }
396
397    struct sockaddr addr;
398    socklen_t alen = sizeof(addr);
399    int fd = accept(s, &addr, &alen);
400    if (fd < 0) {
401        fprintf(stderr, "accept(control socket): %s\n", strerror(errno));
402        exit(1);
403    }
404
405    fflush(redirect);
406    dup2(fd, fileno(redirect));
407    close(fd);
408}
409
410/* redirect output to a file, optionally gzipping; returns gzip pid (or -1) */
411pid_t redirect_to_file(FILE *redirect, char *path, int gzip_level) {
412    char *chp = path;
413
414    /* skip initial slash */
415    if (chp[0] == '/')
416        chp++;
417
418    /* create leading directories, if necessary */
419    while (chp && chp[0]) {
420        chp = strchr(chp, '/');
421        if (chp) {
422            *chp = 0;
423            mkdir(path, 0770);  /* drwxrwx--- */
424            *chp++ = '/';
425        }
426    }
427
428    int fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
429    if (fd < 0) {
430        fprintf(stderr, "%s: %s\n", path, strerror(errno));
431        exit(1);
432    }
433
434    pid_t gzip_pid = -1;
435    if (gzip_level > 0) {
436        int fds[2];
437        if (pipe(fds)) {
438            fprintf(stderr, "pipe: %s\n", strerror(errno));
439            exit(1);
440        }
441
442        fflush(redirect);
443        fflush(stdout);
444
445        gzip_pid = fork();
446        if (gzip_pid < 0) {
447            fprintf(stderr, "fork: %s\n", strerror(errno));
448            exit(1);
449        }
450
451        if (gzip_pid == 0) {
452            dup2(fds[0], STDIN_FILENO);
453            dup2(fd, STDOUT_FILENO);
454
455            close(fd);
456            close(fds[0]);
457            close(fds[1]);
458
459            char level[10];
460            snprintf(level, sizeof(level), "-%d", gzip_level);
461            execlp("gzip", "gzip", level, NULL);
462            fprintf(stderr, "exec(gzip): %s\n", strerror(errno));
463            _exit(-1);
464        }
465
466        close(fd);
467        close(fds[0]);
468        fd = fds[1];
469    }
470
471    dup2(fd, fileno(redirect));
472    close(fd);
473    return gzip_pid;
474}
475
476static bool should_dump_native_traces(const char* path) {
477    for (const char** p = native_processes_to_dump; *p; p++) {
478        if (!strcmp(*p, path)) {
479            return true;
480        }
481    }
482    return false;
483}
484
485/* dump Dalvik and native stack traces, return the trace file location (NULL if none) */
486const char *dump_traces() {
487    const char* result = NULL;
488
489    char traces_path[PROPERTY_VALUE_MAX] = "";
490    property_get("dalvik.vm.stack-trace-file", traces_path, "");
491    if (!traces_path[0]) return NULL;
492
493    /* move the old traces.txt (if any) out of the way temporarily */
494    char anr_traces_path[PATH_MAX];
495    strlcpy(anr_traces_path, traces_path, sizeof(anr_traces_path));
496    strlcat(anr_traces_path, ".anr", sizeof(anr_traces_path));
497    if (rename(traces_path, anr_traces_path) && errno != ENOENT) {
498        fprintf(stderr, "rename(%s, %s): %s\n", traces_path, anr_traces_path, strerror(errno));
499        return NULL;  // Can't rename old traces.txt -- no permission? -- leave it alone instead
500    }
501
502    /* make the directory if necessary */
503    char anr_traces_dir[PATH_MAX];
504    strlcpy(anr_traces_dir, traces_path, sizeof(anr_traces_dir));
505    char *slash = strrchr(anr_traces_dir, '/');
506    if (slash != NULL) {
507        *slash = '\0';
508        if (!mkdir(anr_traces_dir, 0775)) {
509            chown(anr_traces_dir, AID_SYSTEM, AID_SYSTEM);
510            chmod(anr_traces_dir, 0775);
511            if (selinux_android_restorecon(anr_traces_dir, 0) == -1) {
512                fprintf(stderr, "restorecon failed for %s: %s\n", anr_traces_dir, strerror(errno));
513            }
514        } else if (errno != EEXIST) {
515            fprintf(stderr, "mkdir(%s): %s\n", anr_traces_dir, strerror(errno));
516            return NULL;
517        }
518    }
519
520    /* create a new, empty traces.txt file to receive stack dumps */
521    int fd = open(traces_path, O_CREAT | O_WRONLY | O_TRUNC | O_NOFOLLOW, 0666);  /* -rw-rw-rw- */
522    if (fd < 0) {
523        fprintf(stderr, "%s: %s\n", traces_path, strerror(errno));
524        return NULL;
525    }
526    int chmod_ret = fchmod(fd, 0666);
527    if (chmod_ret < 0) {
528        fprintf(stderr, "fchmod on %s failed: %s\n", traces_path, strerror(errno));
529        close(fd);
530        return NULL;
531    }
532
533    /* walk /proc and kill -QUIT all Dalvik processes */
534    DIR *proc = opendir("/proc");
535    if (proc == NULL) {
536        fprintf(stderr, "/proc: %s\n", strerror(errno));
537        goto error_close_fd;
538    }
539
540    /* use inotify to find when processes are done dumping */
541    int ifd = inotify_init();
542    if (ifd < 0) {
543        fprintf(stderr, "inotify_init: %s\n", strerror(errno));
544        goto error_close_fd;
545    }
546
547    int wfd = inotify_add_watch(ifd, traces_path, IN_CLOSE_WRITE);
548    if (wfd < 0) {
549        fprintf(stderr, "inotify_add_watch(%s): %s\n", traces_path, strerror(errno));
550        goto error_close_ifd;
551    }
552
553    struct dirent *d;
554    int dalvik_found = 0;
555    while ((d = readdir(proc))) {
556        int pid = atoi(d->d_name);
557        if (pid <= 0) continue;
558
559        char path[PATH_MAX];
560        char data[PATH_MAX];
561        snprintf(path, sizeof(path), "/proc/%d/exe", pid);
562        ssize_t len = readlink(path, data, sizeof(data) - 1);
563        if (len <= 0) {
564            continue;
565        }
566        data[len] = '\0';
567
568        if (!strcmp(data, "/system/bin/app_process")) {
569            /* skip zygote -- it won't dump its stack anyway */
570            snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
571            int fd = open(path, O_RDONLY);
572            len = read(fd, data, sizeof(data) - 1);
573            close(fd);
574            if (len <= 0) {
575                continue;
576            }
577            data[len] = '\0';
578            if (!strcmp(data, "zygote")) {
579                continue;
580            }
581
582            ++dalvik_found;
583            if (kill(pid, SIGQUIT)) {
584                fprintf(stderr, "kill(%d, SIGQUIT): %s\n", pid, strerror(errno));
585                continue;
586            }
587
588            /* wait for the writable-close notification from inotify */
589            struct pollfd pfd = { ifd, POLLIN, 0 };
590            int ret = poll(&pfd, 1, 200);  /* 200 msec timeout */
591            if (ret < 0) {
592                fprintf(stderr, "poll: %s\n", strerror(errno));
593            } else if (ret == 0) {
594                fprintf(stderr, "warning: timed out dumping pid %d\n", pid);
595            } else {
596                struct inotify_event ie;
597                read(ifd, &ie, sizeof(ie));
598            }
599        } else if (should_dump_native_traces(data)) {
600            /* dump native process if appropriate */
601            if (lseek(fd, 0, SEEK_END) < 0) {
602                fprintf(stderr, "lseek: %s\n", strerror(errno));
603            } else {
604                dump_backtrace_to_file(pid, fd);
605            }
606        }
607    }
608
609    if (dalvik_found == 0) {
610        fprintf(stderr, "Warning: no Dalvik processes found to dump stacks\n");
611    }
612
613    static char dump_traces_path[PATH_MAX];
614    strlcpy(dump_traces_path, traces_path, sizeof(dump_traces_path));
615    strlcat(dump_traces_path, ".bugreport", sizeof(dump_traces_path));
616    if (rename(traces_path, dump_traces_path)) {
617        fprintf(stderr, "rename(%s, %s): %s\n", traces_path, dump_traces_path, strerror(errno));
618        goto error_close_ifd;
619    }
620    result = dump_traces_path;
621
622    /* replace the saved [ANR] traces.txt file */
623    rename(anr_traces_path, traces_path);
624
625error_close_ifd:
626    close(ifd);
627error_close_fd:
628    close(fd);
629    return result;
630}
631
632void play_sound(const char* path) {
633    run_command(NULL, 5, "/system/bin/stagefright", "-o", "-a", path, NULL);
634}
635