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