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