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