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