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