utils.cpp revision 3dba69aad214a873c619d125ff0441b817947100
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>
27#include <string.h>
28#include <sys/inotify.h>
29#include <sys/stat.h>
30#include <sys/sysconf.h>
31#include <sys/time.h>
32#include <sys/wait.h>
33#include <sys/klog.h>
34#include <time.h>
35#include <unistd.h>
36#include <vector>
37#include <sys/prctl.h>
38
39#define LOG_TAG "dumpstate"
40#include <cutils/debugger.h>
41#include <cutils/log.h>
42#include <cutils/properties.h>
43#include <cutils/sockets.h>
44#include <private/android_filesystem_config.h>
45
46#include <selinux/android.h>
47
48#include "dumpstate.h"
49
50static const int64_t NANOS_PER_SEC = 1000000000;
51
52/* list of native processes to include in the native dumps */
53static const char* native_processes_to_dump[] = {
54        "/system/bin/audioserver",
55        "/system/bin/cameraserver",
56        "/system/bin/drmserver",
57        "/system/bin/mediaserver",
58        "/system/bin/sdcard",
59        "/system/bin/surfaceflinger",
60        "/system/bin/vehicle_network_service",
61        NULL,
62};
63
64DurationReporter::DurationReporter(const char *title) : DurationReporter(title, stdout) {}
65
66DurationReporter::DurationReporter(const char *title, FILE *out) {
67    title_ = title;
68    if (title) {
69        started_ = DurationReporter::nanotime();
70    }
71    out_ = out;
72}
73
74DurationReporter::~DurationReporter() {
75    if (title_) {
76        uint64_t elapsed = DurationReporter::nanotime() - started_;
77        // Use "Yoda grammar" to make it easier to grep|sort sections.
78        if (out_) {
79            fprintf(out_, "------ %.3fs was the duration of '%s' ------\n",
80                   (float) elapsed / NANOS_PER_SEC, title_);
81        } else {
82            MYLOGD("Duration of '%s': %.3fs\n", title_, (float) elapsed / NANOS_PER_SEC);
83        }
84    }
85}
86
87uint64_t DurationReporter::DurationReporter::nanotime() {
88    struct timespec ts;
89    clock_gettime(CLOCK_MONOTONIC, &ts);
90    return (uint64_t) ts.tv_sec * NANOS_PER_SEC + ts.tv_nsec;
91}
92
93void for_each_userid(void (*func)(int), const char *header) {
94    ON_DRY_RUN_RETURN();
95    DIR *d;
96    struct dirent *de;
97
98    if (header) printf("\n------ %s ------\n", header);
99    func(0);
100
101    if (!(d = opendir("/data/system/users"))) {
102        printf("Failed to open /data/system/users (%s)\n", strerror(errno));
103        return;
104    }
105
106    while ((de = readdir(d))) {
107        int userid;
108        if (de->d_type != DT_DIR || !(userid = atoi(de->d_name))) {
109            continue;
110        }
111        func(userid);
112    }
113
114    closedir(d);
115}
116
117static void __for_each_pid(void (*helper)(int, const char *, void *), const char *header, void *arg) {
118    DIR *d;
119    struct dirent *de;
120
121    if (!(d = opendir("/proc"))) {
122        printf("Failed to open /proc (%s)\n", strerror(errno));
123        return;
124    }
125
126    if (header) printf("\n------ %s ------\n", header);
127    while ((de = readdir(d))) {
128        int pid;
129        int fd;
130        char cmdpath[255];
131        char cmdline[255];
132
133        if (!(pid = atoi(de->d_name))) {
134            continue;
135        }
136
137        memset(cmdline, 0, sizeof(cmdline));
138
139        snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/cmdline", pid);
140        if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
141            TEMP_FAILURE_RETRY(read(fd, cmdline, sizeof(cmdline) - 2));
142            close(fd);
143            if (cmdline[0]) {
144                helper(pid, cmdline, arg);
145                continue;
146            }
147        }
148
149        // if no cmdline, a kernel thread has comm
150        snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/comm", pid);
151        if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
152            TEMP_FAILURE_RETRY(read(fd, cmdline + 1, sizeof(cmdline) - 4));
153            close(fd);
154            if (cmdline[1]) {
155                cmdline[0] = '[';
156                size_t len = strcspn(cmdline, "\f\b\r\n");
157                cmdline[len] = ']';
158                cmdline[len+1] = '\0';
159            }
160        }
161        if (!cmdline[0]) {
162            strcpy(cmdline, "N/A");
163        }
164        helper(pid, cmdline, arg);
165    }
166
167    closedir(d);
168}
169
170static void for_each_pid_helper(int pid, const char *cmdline, void *arg) {
171    for_each_pid_func *func = (for_each_pid_func*) arg;
172    func(pid, cmdline);
173}
174
175void for_each_pid(for_each_pid_func func, const char *header) {
176    ON_DRY_RUN_RETURN();
177  __for_each_pid(for_each_pid_helper, header, (void *)func);
178}
179
180static void for_each_tid_helper(int pid, const char *cmdline, void *arg) {
181    DIR *d;
182    struct dirent *de;
183    char taskpath[255];
184    for_each_tid_func *func = (for_each_tid_func *) arg;
185
186    sprintf(taskpath, "/proc/%d/task", pid);
187
188    if (!(d = opendir(taskpath))) {
189        printf("Failed to open %s (%s)\n", taskpath, strerror(errno));
190        return;
191    }
192
193    func(pid, pid, cmdline);
194
195    while ((de = readdir(d))) {
196        int tid;
197        int fd;
198        char commpath[255];
199        char comm[255];
200
201        if (!(tid = atoi(de->d_name))) {
202            continue;
203        }
204
205        if (tid == pid)
206            continue;
207
208        sprintf(commpath,"/proc/%d/comm", tid);
209        memset(comm, 0, sizeof(comm));
210        if ((fd = TEMP_FAILURE_RETRY(open(commpath, O_RDONLY | O_CLOEXEC))) < 0) {
211            strcpy(comm, "N/A");
212        } else {
213            char *c;
214            TEMP_FAILURE_RETRY(read(fd, comm, sizeof(comm) - 2));
215            close(fd);
216
217            c = strrchr(comm, '\n');
218            if (c) {
219                *c = '\0';
220            }
221        }
222        func(pid, tid, comm);
223    }
224
225    closedir(d);
226}
227
228void for_each_tid(for_each_tid_func func, const char *header) {
229    ON_DRY_RUN_RETURN();
230    __for_each_pid(for_each_tid_helper, header, (void *) func);
231}
232
233void show_wchan(int pid, int tid, const char *name) {
234    ON_DRY_RUN_RETURN();
235    char path[255];
236    char buffer[255];
237    int fd, ret, save_errno;
238    char name_buffer[255];
239
240    memset(buffer, 0, sizeof(buffer));
241
242    sprintf(path, "/proc/%d/wchan", tid);
243    if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
244        printf("Failed to open '%s' (%s)\n", path, strerror(errno));
245        return;
246    }
247
248    ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
249    save_errno = errno;
250    close(fd);
251
252    if (ret < 0) {
253        printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
254        return;
255    }
256
257    snprintf(name_buffer, sizeof(name_buffer), "%*s%s",
258             pid == tid ? 0 : 3, "", name);
259
260    printf("%-7d %-32s %s\n", tid, name_buffer, buffer);
261
262    return;
263}
264
265// print time in centiseconds
266static void snprcent(char *buffer, size_t len, size_t spc,
267                     unsigned long long time) {
268    static long hz; // cache discovered hz
269
270    if (hz <= 0) {
271        hz = sysconf(_SC_CLK_TCK);
272        if (hz <= 0) {
273            hz = 1000;
274        }
275    }
276
277    // convert to centiseconds
278    time = (time * 100 + (hz / 2)) / hz;
279
280    char str[16];
281
282    snprintf(str, sizeof(str), " %llu.%02u",
283             time / 100, (unsigned)(time % 100));
284    size_t offset = strlen(buffer);
285    snprintf(buffer + offset, (len > offset) ? len - offset : 0,
286             "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
287}
288
289// print permille as a percent
290static void snprdec(char *buffer, size_t len, size_t spc, unsigned permille) {
291    char str[16];
292
293    snprintf(str, sizeof(str), " %u.%u%%", permille / 10, permille % 10);
294    size_t offset = strlen(buffer);
295    snprintf(buffer + offset, (len > offset) ? len - offset : 0,
296             "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
297}
298
299void show_showtime(int pid, const char *name) {
300    ON_DRY_RUN_RETURN();
301    char path[255];
302    char buffer[1023];
303    int fd, ret, save_errno;
304
305    memset(buffer, 0, sizeof(buffer));
306
307    sprintf(path, "/proc/%d/stat", pid);
308    if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
309        printf("Failed to open '%s' (%s)\n", path, strerror(errno));
310        return;
311    }
312
313    ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
314    save_errno = errno;
315    close(fd);
316
317    if (ret < 0) {
318        printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
319        return;
320    }
321
322    // field 14 is utime
323    // field 15 is stime
324    // field 42 is iotime
325    unsigned long long utime = 0, stime = 0, iotime = 0;
326    if (sscanf(buffer,
327               "%*u %*s %*s %*d %*d %*d %*d %*d %*d %*d %*d "
328               "%*d %*d %llu %llu %*d %*d %*d %*d %*d %*d "
329               "%*d %*d %*d %*d %*d %*d %*d %*d %*d %*d "
330               "%*d %*d %*d %*d %*d %*d %*d %*d %*d %llu ",
331               &utime, &stime, &iotime) != 3) {
332        return;
333    }
334
335    unsigned long long total = utime + stime;
336    if (!total) {
337        return;
338    }
339
340    unsigned permille = (iotime * 1000 + (total / 2)) / total;
341    if (permille > 1000) {
342        permille = 1000;
343    }
344
345    // try to beautify and stabilize columns at <80 characters
346    snprintf(buffer, sizeof(buffer), "%-6d%s", pid, name);
347    if ((name[0] != '[') || utime) {
348        snprcent(buffer, sizeof(buffer), 57, utime);
349    }
350    snprcent(buffer, sizeof(buffer), 65, stime);
351    if ((name[0] != '[') || iotime) {
352        snprcent(buffer, sizeof(buffer), 73, iotime);
353    }
354    if (iotime) {
355        snprdec(buffer, sizeof(buffer), 79, permille);
356    }
357    puts(buffer); // adds a trailing newline
358
359    return;
360}
361
362void do_dmesg() {
363    const char *title = "KERNEL LOG (dmesg)";
364    DurationReporter duration_reporter(title);
365    printf("------ %s ------\n", title);
366
367    ON_DRY_RUN_RETURN();
368    /* Get size of kernel buffer */
369    int size = klogctl(KLOG_SIZE_BUFFER, NULL, 0);
370    if (size <= 0) {
371        printf("Unexpected klogctl return value: %d\n\n", size);
372        return;
373    }
374    char *buf = (char *) malloc(size + 1);
375    if (buf == NULL) {
376        printf("memory allocation failed\n\n");
377        return;
378    }
379    int retval = klogctl(KLOG_READ_ALL, buf, size);
380    if (retval < 0) {
381        printf("klogctl failure\n\n");
382        free(buf);
383        return;
384    }
385    buf[retval] = '\0';
386    printf("%s\n\n", buf);
387    free(buf);
388    return;
389}
390
391void do_showmap(int pid, const char *name) {
392    char title[255];
393    char arg[255];
394
395    sprintf(title, "SHOW MAP %d (%s)", pid, name);
396    sprintf(arg, "%d", pid);
397    run_command(title, 10, SU_PATH, "root", "showmap", "-q", arg, NULL);
398}
399
400static int _dump_file_from_fd(const char *title, const char *path, int fd) {
401    if (title) {
402        printf("------ %s (%s", title, path);
403
404        struct stat st;
405        // Only show the modification time of non-device files.
406        size_t path_len = strlen(path);
407        if ((path_len < 6 || memcmp(path, "/proc/", 6)) &&
408                (path_len < 5 || memcmp(path, "/sys/", 5)) &&
409                (path_len < 3 || memcmp(path, "/d/", 3)) &&
410                !fstat(fd, &st)) {
411            char stamp[80];
412            time_t mtime = st.st_mtime;
413            strftime(stamp, sizeof(stamp), "%Y-%m-%d %H:%M:%S", localtime(&mtime));
414            printf(": %s", stamp);
415        }
416        printf(") ------\n");
417    }
418    ON_DRY_RUN({ update_progress(WEIGHT_FILE); close(fd); return 0; });
419
420    bool newline = false;
421    fd_set read_set;
422    struct timeval tm;
423    while (1) {
424        FD_ZERO(&read_set);
425        FD_SET(fd, &read_set);
426        /* Timeout if no data is read for 30 seconds. */
427        tm.tv_sec = 30;
428        tm.tv_usec = 0;
429        uint64_t elapsed = DurationReporter::nanotime();
430        int ret = TEMP_FAILURE_RETRY(select(fd + 1, &read_set, NULL, NULL, &tm));
431        if (ret == -1) {
432            printf("*** %s: select failed: %s\n", path, strerror(errno));
433            newline = true;
434            break;
435        } else if (ret == 0) {
436            elapsed = DurationReporter::nanotime() - elapsed;
437            printf("*** %s: Timed out after %.3fs\n", path,
438                   (float) elapsed / NANOS_PER_SEC);
439            newline = true;
440            break;
441        } else {
442            char buffer[65536];
443            ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
444            if (bytes_read > 0) {
445                fwrite(buffer, bytes_read, 1, stdout);
446                newline = (buffer[bytes_read-1] == '\n');
447            } else {
448                if (bytes_read == -1) {
449                    printf("*** %s: Failed to read from fd: %s", path, strerror(errno));
450                    newline = true;
451                }
452                break;
453            }
454        }
455    }
456    update_progress(WEIGHT_FILE);
457    close(fd);
458
459    if (!newline) printf("\n");
460    if (title) printf("\n");
461    return 0;
462}
463
464/* prints the contents of a file */
465int dump_file(const char *title, const char *path) {
466    DurationReporter duration_reporter(title);
467    int fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
468    if (fd < 0) {
469        int err = errno;
470        printf("*** %s: %s\n", path, strerror(err));
471        if (title) printf("\n");
472        return -1;
473    }
474    return _dump_file_from_fd(title, path, fd);
475}
476
477/* calls skip to gate calling dump_from_fd recursively
478 * in the specified directory. dump_from_fd defaults to
479 * dump_file_from_fd above when set to NULL. skip defaults
480 * to false when set to NULL. dump_from_fd will always be
481 * called with title NULL.
482 */
483int dump_files(const char *title, const char *dir,
484        bool (*skip)(const char *path),
485        int (*dump_from_fd)(const char *title, const char *path, int fd)) {
486    DurationReporter duration_reporter(title);
487    DIR *dirp;
488    struct dirent *d;
489    char *newpath = NULL;
490    const char *slash = "/";
491    int fd, retval = 0;
492
493    if (title) {
494        printf("------ %s (%s) ------\n", title, dir);
495    }
496    ON_DRY_RUN_RETURN(0);
497
498    if (dir[strlen(dir) - 1] == '/') {
499        ++slash;
500    }
501    dirp = opendir(dir);
502    if (dirp == NULL) {
503        retval = -errno;
504        MYLOGE("%s: %s\n", dir, strerror(errno));
505        return retval;
506    }
507
508    if (!dump_from_fd) {
509        dump_from_fd = dump_file_from_fd;
510    }
511    for (; ((d = readdir(dirp))); free(newpath), newpath = NULL) {
512        if ((d->d_name[0] == '.')
513         && (((d->d_name[1] == '.') && (d->d_name[2] == '\0'))
514          || (d->d_name[1] == '\0'))) {
515            continue;
516        }
517        asprintf(&newpath, "%s%s%s%s", dir, slash, d->d_name,
518                 (d->d_type == DT_DIR) ? "/" : "");
519        if (!newpath) {
520            retval = -errno;
521            continue;
522        }
523        if (skip && (*skip)(newpath)) {
524            continue;
525        }
526        if (d->d_type == DT_DIR) {
527            int ret = dump_files(NULL, newpath, skip, dump_from_fd);
528            if (ret < 0) {
529                retval = ret;
530            }
531            continue;
532        }
533        fd = TEMP_FAILURE_RETRY(open(newpath, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
534        if (fd < 0) {
535            retval = fd;
536            printf("*** %s: %s\n", newpath, strerror(errno));
537            continue;
538        }
539        (*dump_from_fd)(NULL, newpath, fd);
540    }
541    closedir(dirp);
542    if (title) {
543        printf("\n");
544    }
545    return retval;
546}
547
548/* fd must have been opened with the flag O_NONBLOCK. With this flag set,
549 * it's possible to avoid issues where opening the file itself can get
550 * stuck.
551 */
552int dump_file_from_fd(const char *title, const char *path, int fd) {
553    int flags = fcntl(fd, F_GETFL);
554    if (flags == -1) {
555        printf("*** %s: failed to get flags on fd %d: %s\n", path, fd, strerror(errno));
556        close(fd);
557        return -1;
558    } else if (!(flags & O_NONBLOCK)) {
559        printf("*** %s: fd must have O_NONBLOCK set.\n", path);
560        close(fd);
561        return -1;
562    }
563    return _dump_file_from_fd(title, path, fd);
564}
565
566bool waitpid_with_timeout(pid_t pid, int timeout_seconds, int* status) {
567    sigset_t child_mask, old_mask;
568    sigemptyset(&child_mask);
569    sigaddset(&child_mask, SIGCHLD);
570
571    if (sigprocmask(SIG_BLOCK, &child_mask, &old_mask) == -1) {
572        printf("*** sigprocmask failed: %s\n", strerror(errno));
573        return false;
574    }
575
576    struct timespec ts;
577    ts.tv_sec = timeout_seconds;
578    ts.tv_nsec = 0;
579    int ret = TEMP_FAILURE_RETRY(sigtimedwait(&child_mask, NULL, &ts));
580    int saved_errno = errno;
581    // Set the signals back the way they were.
582    if (sigprocmask(SIG_SETMASK, &old_mask, NULL) == -1) {
583        printf("*** sigprocmask failed: %s\n", strerror(errno));
584        if (ret == 0) {
585            return false;
586        }
587    }
588    if (ret == -1) {
589        errno = saved_errno;
590        if (errno == EAGAIN) {
591            errno = ETIMEDOUT;
592        } else {
593            printf("*** sigtimedwait failed: %s\n", strerror(errno));
594        }
595        return false;
596    }
597
598    pid_t child_pid = waitpid(pid, status, WNOHANG);
599    if (child_pid != pid) {
600        if (child_pid != -1) {
601            printf("*** Waiting for pid %d, got pid %d instead\n", pid, child_pid);
602        } else {
603            printf("*** waitpid failed: %s\n", strerror(errno));
604        }
605        return false;
606    }
607    return true;
608}
609
610// TODO: refactor all those commands that convert args
611void format_args(const char* command, const char *args[], std::string *string);
612
613int run_command(const char *title, int timeout_seconds, const char *command, ...) {
614    DurationReporter duration_reporter(title);
615    fflush(stdout);
616
617    const char *args[1024] = {command};
618    size_t arg;
619    va_list ap;
620    va_start(ap, command);
621    if (title) printf("------ %s (%s", title, command);
622    bool null_terminated = false;
623    for (arg = 1; arg < sizeof(args) / sizeof(args[0]); ++arg) {
624        args[arg] = va_arg(ap, const char *);
625        if (args[arg] == nullptr) {
626            null_terminated = true;
627            break;
628        }
629        if (title) printf(" %s", args[arg]);
630    }
631    if (title) printf(") ------\n");
632    fflush(stdout);
633    if (!null_terminated) {
634        // Fail now, otherwise execvp() call on run_command_always() might hang.
635        std::string cmd;
636        format_args(command, args, &cmd);
637        MYLOGE("skipping command %s because its args were not NULL-terminated", cmd.c_str());
638        return -1;
639    }
640
641    ON_DRY_RUN({ update_progress(timeout_seconds); va_end(ap); return 0; });
642
643    int status = run_command_always(title, timeout_seconds, args);
644    va_end(ap);
645    return status;
646}
647
648/* forks a command and waits for it to finish */
649int run_command_always(const char *title, int timeout_seconds, const char *args[]) {
650    /* TODO: for now we're simplifying the progress calculation by using the timeout as the weight.
651     * It's a good approximation for most cases, except when calling dumpsys, where its weight
652     * should be much higher proportionally to its timeout. */
653    int weight = timeout_seconds;
654
655    const char *command = args[0];
656    uint64_t start = DurationReporter::nanotime();
657    pid_t pid = fork();
658
659    /* handle error case */
660    if (pid < 0) {
661        printf("*** fork: %s\n", strerror(errno));
662        return pid;
663    }
664
665    /* handle child case */
666    if (pid == 0) {
667
668        /* make sure the child dies when dumpstate dies */
669        prctl(PR_SET_PDEATHSIG, SIGKILL);
670
671        /* just ignore SIGPIPE, will go down with parent's */
672        struct sigaction sigact;
673        memset(&sigact, 0, sizeof(sigact));
674        sigact.sa_handler = SIG_IGN;
675        sigaction(SIGPIPE, &sigact, NULL);
676
677        execvp(command, (char**) args);
678        // execvp's result will be handled after waitpid_with_timeout() below...
679        _exit(-1); // ...but it doesn't hurt to force exit, just in case
680    }
681
682    /* handle parent case */
683    int status;
684    bool ret = waitpid_with_timeout(pid, timeout_seconds, &status);
685    uint64_t elapsed = DurationReporter::nanotime() - start;
686    std::string cmd; // used to log command and its args
687    if (!ret) {
688        if (errno == ETIMEDOUT) {
689            format_args(command, args, &cmd);
690            printf("*** command '%s' timed out after %.3fs (killing pid %d)\n", cmd.c_str(),
691                   (float) elapsed / NANOS_PER_SEC, pid);
692            MYLOGE("command '%s' timed out after %.3fs (killing pid %d)\n", cmd.c_str(),
693                   (float) elapsed / NANOS_PER_SEC, pid);
694        } else {
695            format_args(command, args, &cmd);
696            printf("*** command '%s': Error after %.4fs (killing pid %d)\n", cmd.c_str(),
697                   (float) elapsed / NANOS_PER_SEC, pid);
698            MYLOGE("command '%s': Error after %.4fs (killing pid %d)\n", cmd.c_str(),
699                   (float) elapsed / NANOS_PER_SEC, pid);
700        }
701        kill(pid, SIGTERM);
702        if (!waitpid_with_timeout(pid, 5, NULL)) {
703            kill(pid, SIGKILL);
704            if (!waitpid_with_timeout(pid, 5, NULL)) {
705                printf("couldn not kill command '%s' (pid %d) even with SIGKILL.\n", command, pid);
706                MYLOGE("couldn not kill command '%s' (pid %d) even with SIGKILL.\n", command, pid);
707            }
708        }
709        return -1;
710    } else if (status) {
711        format_args(command, args, &cmd);
712        printf("*** command '%s' failed: %s\n", cmd.c_str(), strerror(errno));
713        MYLOGE("command '%s' failed: %s\n", cmd.c_str(), strerror(errno));
714        return -2;
715    }
716
717    if (WIFSIGNALED(status)) {
718        printf("*** %s: Killed by signal %d\n", command, WTERMSIG(status));
719    } else if (WIFEXITED(status) && WEXITSTATUS(status) > 0) {
720        printf("*** %s: Exit code %d\n", command, WEXITSTATUS(status));
721    }
722
723    if (weight > 0) {
724        update_progress(weight);
725    }
726    return status;
727}
728
729void send_broadcast(const std::string& action, const std::vector<std::string>& args) {
730    if (args.size() > 1000) {
731        MYLOGE("send_broadcast: too many arguments (%d)\n", (int) args.size());
732        return;
733    }
734    const char *am_args[1024] = { SU_PATH, "shell", "/system/bin/am", "broadcast",
735                                  "--user", "0", "-a", action.c_str() };
736    size_t am_index = 7; // Starts at the index of last initial value above.
737    for (const std::string& arg : args) {
738        am_args[++am_index] = arg.c_str();
739    }
740    // Always terminate with NULL.
741    am_args[am_index + 1] = NULL;
742    std::string args_string;
743    format_args(am_index + 1, am_args, &args_string);
744    MYLOGD("send_broadcast command: %s\n", args_string.c_str());
745    run_command_always(NULL, 5, am_args);
746}
747
748size_t num_props = 0;
749static char* props[2000];
750
751static void print_prop(const char *key, const char *name, void *user) {
752    (void) user;
753    if (num_props < sizeof(props) / sizeof(props[0])) {
754        char buf[PROPERTY_KEY_MAX + PROPERTY_VALUE_MAX + 10];
755        snprintf(buf, sizeof(buf), "[%s]: [%s]\n", key, name);
756        props[num_props++] = strdup(buf);
757    }
758}
759
760static int compare_prop(const void *a, const void *b) {
761    return strcmp(*(char * const *) a, *(char * const *) b);
762}
763
764/* prints all the system properties */
765void print_properties() {
766    const char* title = "SYSTEM PROPERTIES";
767    DurationReporter duration_reporter(title);
768    printf("------ %s ------\n", title);
769    ON_DRY_RUN_RETURN();
770    size_t i;
771    num_props = 0;
772    property_list(print_prop, NULL);
773    qsort(&props, num_props, sizeof(props[0]), compare_prop);
774
775    for (i = 0; i < num_props; ++i) {
776        fputs(props[i], stdout);
777        free(props[i]);
778    }
779    printf("\n");
780}
781
782/* redirect output to a service control socket */
783void redirect_to_socket(FILE *redirect, const char *service) {
784    int s = android_get_control_socket(service);
785    if (s < 0) {
786        MYLOGE("android_get_control_socket(%s): %s\n", service, strerror(errno));
787        exit(1);
788    }
789    fcntl(s, F_SETFD, FD_CLOEXEC);
790    if (listen(s, 4) < 0) {
791        MYLOGE("listen(control socket): %s\n", strerror(errno));
792        exit(1);
793    }
794
795    struct sockaddr addr;
796    socklen_t alen = sizeof(addr);
797    int fd = accept(s, &addr, &alen);
798    if (fd < 0) {
799        MYLOGE("accept(control socket): %s\n", strerror(errno));
800        exit(1);
801    }
802
803    fflush(redirect);
804    dup2(fd, fileno(redirect));
805    close(fd);
806}
807
808void create_parent_dirs(const char *path) {
809    char *chp = const_cast<char *> (path);
810
811    /* skip initial slash */
812    if (chp[0] == '/')
813        chp++;
814
815    /* create leading directories, if necessary */
816    struct stat dir_stat;
817    while (chp && chp[0]) {
818        chp = strchr(chp, '/');
819        if (chp) {
820            *chp = 0;
821            if (stat(path, &dir_stat) == -1 || !S_ISDIR(dir_stat.st_mode)) {
822                MYLOGI("Creating directory %s\n", path);
823                if (mkdir(path, 0770)) { /* drwxrwx--- */
824                    MYLOGE("Unable to create directory %s: %s\n", path, strerror(errno));
825                } else if (chown(path, AID_SHELL, AID_SHELL)) {
826                    MYLOGE("Unable to change ownership of dir %s: %s\n", path, strerror(errno));
827                }
828            }
829            *chp++ = '/';
830        }
831    }
832}
833
834/* redirect output to a file */
835void redirect_to_file(FILE *redirect, char *path) {
836    create_parent_dirs(path);
837
838    int fd = TEMP_FAILURE_RETRY(open(path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW,
839                                     S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
840    if (fd < 0) {
841        MYLOGE("%s: %s\n", path, strerror(errno));
842        exit(1);
843    }
844
845    TEMP_FAILURE_RETRY(dup2(fd, fileno(redirect)));
846    close(fd);
847}
848
849static bool should_dump_native_traces(const char* path) {
850    for (const char** p = native_processes_to_dump; *p; p++) {
851        if (!strcmp(*p, path)) {
852            return true;
853        }
854    }
855    return false;
856}
857
858/* dump Dalvik and native stack traces, return the trace file location (NULL if none) */
859const char *dump_traces() {
860    DurationReporter duration_reporter("DUMP TRACES", NULL);
861    ON_DRY_RUN_RETURN(NULL);
862    const char* result = NULL;
863
864    char traces_path[PROPERTY_VALUE_MAX] = "";
865    property_get("dalvik.vm.stack-trace-file", traces_path, "");
866    if (!traces_path[0]) return NULL;
867
868    /* move the old traces.txt (if any) out of the way temporarily */
869    char anr_traces_path[PATH_MAX];
870    strlcpy(anr_traces_path, traces_path, sizeof(anr_traces_path));
871    strlcat(anr_traces_path, ".anr", sizeof(anr_traces_path));
872    if (rename(traces_path, anr_traces_path) && errno != ENOENT) {
873        MYLOGE("rename(%s, %s): %s\n", traces_path, anr_traces_path, strerror(errno));
874        return NULL;  // Can't rename old traces.txt -- no permission? -- leave it alone instead
875    }
876
877    /* create a new, empty traces.txt file to receive stack dumps */
878    int fd = TEMP_FAILURE_RETRY(open(traces_path, O_CREAT | O_WRONLY | O_TRUNC | O_NOFOLLOW | O_CLOEXEC,
879                                     0666));  /* -rw-rw-rw- */
880    if (fd < 0) {
881        MYLOGE("%s: %s\n", traces_path, strerror(errno));
882        return NULL;
883    }
884    int chmod_ret = fchmod(fd, 0666);
885    if (chmod_ret < 0) {
886        MYLOGE("fchmod on %s failed: %s\n", traces_path, strerror(errno));
887        close(fd);
888        return NULL;
889    }
890
891    /* Variables below must be initialized before 'goto' statements */
892    int dalvik_found = 0;
893    int ifd, wfd = -1;
894
895    /* walk /proc and kill -QUIT all Dalvik processes */
896    DIR *proc = opendir("/proc");
897    if (proc == NULL) {
898        MYLOGE("/proc: %s\n", strerror(errno));
899        goto error_close_fd;
900    }
901
902    /* use inotify to find when processes are done dumping */
903    ifd = inotify_init();
904    if (ifd < 0) {
905        MYLOGE("inotify_init: %s\n", strerror(errno));
906        goto error_close_fd;
907    }
908
909    wfd = inotify_add_watch(ifd, traces_path, IN_CLOSE_WRITE);
910    if (wfd < 0) {
911        MYLOGE("inotify_add_watch(%s): %s\n", traces_path, strerror(errno));
912        goto error_close_ifd;
913    }
914
915    struct dirent *d;
916    while ((d = readdir(proc))) {
917        int pid = atoi(d->d_name);
918        if (pid <= 0) continue;
919
920        char path[PATH_MAX];
921        char data[PATH_MAX];
922        snprintf(path, sizeof(path), "/proc/%d/exe", pid);
923        ssize_t len = readlink(path, data, sizeof(data) - 1);
924        if (len <= 0) {
925            continue;
926        }
927        data[len] = '\0';
928
929        if (!strncmp(data, "/system/bin/app_process", strlen("/system/bin/app_process"))) {
930            /* skip zygote -- it won't dump its stack anyway */
931            snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
932            int cfd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC));
933            len = read(cfd, data, sizeof(data) - 1);
934            close(cfd);
935            if (len <= 0) {
936                continue;
937            }
938            data[len] = '\0';
939            if (!strncmp(data, "zygote", strlen("zygote"))) {
940                continue;
941            }
942
943            ++dalvik_found;
944            uint64_t start = DurationReporter::nanotime();
945            if (kill(pid, SIGQUIT)) {
946                MYLOGE("kill(%d, SIGQUIT): %s\n", pid, strerror(errno));
947                continue;
948            }
949
950            /* wait for the writable-close notification from inotify */
951            struct pollfd pfd = { ifd, POLLIN, 0 };
952            int ret = poll(&pfd, 1, 5000);  /* 5 sec timeout */
953            if (ret < 0) {
954                MYLOGE("poll: %s\n", strerror(errno));
955            } else if (ret == 0) {
956                MYLOGE("warning: timed out dumping pid %d\n", pid);
957            } else {
958                struct inotify_event ie;
959                read(ifd, &ie, sizeof(ie));
960            }
961
962            if (lseek(fd, 0, SEEK_END) < 0) {
963                MYLOGE("lseek: %s\n", strerror(errno));
964            } else {
965                dprintf(fd, "[dump dalvik stack %d: %.3fs elapsed]\n",
966                        pid, (float)(DurationReporter::nanotime() - start) / NANOS_PER_SEC);
967            }
968        } else if (should_dump_native_traces(data)) {
969            /* dump native process if appropriate */
970            if (lseek(fd, 0, SEEK_END) < 0) {
971                MYLOGE("lseek: %s\n", strerror(errno));
972            } else {
973                static uint16_t timeout_failures = 0;
974                uint64_t start = DurationReporter::nanotime();
975
976                /* If 3 backtrace dumps fail in a row, consider debuggerd dead. */
977                if (timeout_failures == 3) {
978                    dprintf(fd, "too many stack dump failures, skipping...\n");
979                } else if (dump_backtrace_to_file_timeout(pid, fd, 20) == -1) {
980                    dprintf(fd, "dumping failed, likely due to a timeout\n");
981                    timeout_failures++;
982                } else {
983                    timeout_failures = 0;
984                }
985                dprintf(fd, "[dump native stack %d: %.3fs elapsed]\n",
986                        pid, (float)(DurationReporter::nanotime() - start) / NANOS_PER_SEC);
987            }
988        }
989    }
990
991    if (dalvik_found == 0) {
992        MYLOGE("Warning: no Dalvik processes found to dump stacks\n");
993    }
994
995    static char dump_traces_path[PATH_MAX];
996    strlcpy(dump_traces_path, traces_path, sizeof(dump_traces_path));
997    strlcat(dump_traces_path, ".bugreport", sizeof(dump_traces_path));
998    if (rename(traces_path, dump_traces_path)) {
999        MYLOGE("rename(%s, %s): %s\n", traces_path, dump_traces_path, strerror(errno));
1000        goto error_close_ifd;
1001    }
1002    result = dump_traces_path;
1003
1004    /* replace the saved [ANR] traces.txt file */
1005    rename(anr_traces_path, traces_path);
1006
1007error_close_ifd:
1008    close(ifd);
1009error_close_fd:
1010    close(fd);
1011    return result;
1012}
1013
1014void dump_route_tables() {
1015    DurationReporter duration_reporter("DUMP ROUTE TABLES");
1016    ON_DRY_RUN_RETURN();
1017    const char* const RT_TABLES_PATH = "/data/misc/net/rt_tables";
1018    dump_file("RT_TABLES", RT_TABLES_PATH);
1019    FILE* fp = fopen(RT_TABLES_PATH, "re");
1020    if (!fp) {
1021        printf("*** %s: %s\n", RT_TABLES_PATH, strerror(errno));
1022        return;
1023    }
1024    char table[16];
1025    // Each line has an integer (the table number), a space, and a string (the table name). We only
1026    // need the table number. It's a 32-bit unsigned number, so max 10 chars. Skip the table name.
1027    // Add a fixed max limit so this doesn't go awry.
1028    for (int i = 0; i < 64 && fscanf(fp, " %10s %*s", table) == 1; ++i) {
1029        run_command("ROUTE TABLE IPv4", 10, "ip", "-4", "route", "show", "table", table, NULL);
1030        run_command("ROUTE TABLE IPv6", 10, "ip", "-6", "route", "show", "table", table, NULL);
1031    }
1032    fclose(fp);
1033}
1034
1035/* overall progress */
1036int progress = 0;
1037int do_update_progress = 0; // Set by dumpstate.cpp
1038int weight_total = WEIGHT_TOTAL;
1039
1040// TODO: make this function thread safe if sections are generated in parallel.
1041void update_progress(int delta) {
1042    if (!do_update_progress) return;
1043
1044    progress += delta;
1045
1046    char key[PROPERTY_KEY_MAX];
1047    char value[PROPERTY_VALUE_MAX];
1048
1049    // adjusts max on the fly
1050    if (progress > weight_total) {
1051        int new_total = weight_total * 1.2;
1052        MYLOGD("Adjusting total weight from %d to %d\n", weight_total, new_total);
1053        weight_total = new_total;
1054        sprintf(key, "dumpstate.%d.max", getpid());
1055        sprintf(value, "%d", weight_total);
1056        int status = property_set(key, value);
1057        if (status) {
1058            MYLOGE("Could not update max weight by setting system property %s to %s: %d\n",
1059                    key, value, status);
1060        }
1061    }
1062
1063    sprintf(key, "dumpstate.%d.progress", getpid());
1064    sprintf(value, "%d", progress);
1065
1066    if (progress % 100 == 0) {
1067        // We don't want to spam logcat, so only log multiples of 100.
1068        MYLOGD("Setting progress (%s): %s/%d\n", key, value, weight_total);
1069    } else {
1070        // stderr is ignored on normal invocations, but useful when calling /system/bin/dumpstate
1071        // directly for debuggging.
1072        fprintf(stderr, "Setting progress (%s): %s/%d\n", key, value, weight_total);
1073    }
1074
1075    int status = property_set(key, value);
1076    if (status) {
1077        MYLOGE("Could not update progress by setting system property %s to %s: %d\n",
1078                key, value, status);
1079    }
1080}
1081
1082void take_screenshot(const std::string& path) {
1083    const char *args[] = { "/system/bin/screencap", "-p", path.c_str(), NULL };
1084    run_command_always(NULL, 10, args);
1085}
1086
1087void vibrate(FILE* vibrator, int ms) {
1088    fprintf(vibrator, "%d\n", ms);
1089    fflush(vibrator);
1090}
1091
1092bool is_dir(const char* pathname) {
1093    struct stat info;
1094    if (stat(pathname, &info) == -1) {
1095        return false;
1096    }
1097    return S_ISDIR(info.st_mode);
1098}
1099
1100time_t get_mtime(int fd, time_t default_mtime) {
1101    struct stat info;
1102    if (fstat(fd, &info) == -1) {
1103        return default_mtime;
1104    }
1105    return info.st_mtime;
1106}
1107
1108void dump_emmc_ecsd(const char *ext_csd_path) {
1109    static const size_t EXT_CSD_REV = 192;
1110    static const size_t EXT_PRE_EOL_INFO = 267;
1111    static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_A = 268;
1112    static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_B = 269;
1113    struct hex {
1114        char str[2];
1115    } buffer[512];
1116    int fd, ext_csd_rev, ext_pre_eol_info;
1117    ssize_t bytes_read;
1118    static const char *ver_str[] = {
1119        "4.0", "4.1", "4.2", "4.3", "Obsolete", "4.41", "4.5", "5.0"
1120    };
1121    static const char *eol_str[] = {
1122        "Undefined",
1123        "Normal",
1124        "Warning (consumed 80% of reserve)",
1125        "Urgent (consumed 90% of reserve)"
1126    };
1127
1128    printf("------ %s Extended CSD ------\n", ext_csd_path);
1129
1130    fd = TEMP_FAILURE_RETRY(open(ext_csd_path,
1131                                 O_RDONLY | O_NONBLOCK | O_CLOEXEC));
1132    if (fd < 0) {
1133        printf("*** %s: %s\n\n", ext_csd_path, strerror(errno));
1134        return;
1135    }
1136
1137    bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
1138    close(fd);
1139    if (bytes_read < 0) {
1140        printf("*** %s: %s\n\n", ext_csd_path, strerror(errno));
1141        return;
1142    }
1143    if (bytes_read < (ssize_t)(EXT_CSD_REV * sizeof(struct hex))) {
1144        printf("*** %s: truncated content %zd\n\n", ext_csd_path, bytes_read);
1145        return;
1146    }
1147
1148    ext_csd_rev = 0;
1149    if (sscanf(buffer[EXT_CSD_REV].str, "%02x", &ext_csd_rev) != 1) {
1150        printf("*** %s: EXT_CSD_REV parse error \"%.2s\"\n\n",
1151               ext_csd_path, buffer[EXT_CSD_REV].str);
1152        return;
1153    }
1154
1155    printf("rev 1.%d (MMC %s)\n",
1156           ext_csd_rev,
1157           (ext_csd_rev < (int)(sizeof(ver_str) / sizeof(ver_str[0]))) ?
1158               ver_str[ext_csd_rev] :
1159               "Unknown");
1160    if (ext_csd_rev < 7) {
1161        printf("\n");
1162        return;
1163    }
1164
1165    if (bytes_read < (ssize_t)(EXT_PRE_EOL_INFO * sizeof(struct hex))) {
1166        printf("*** %s: truncated content %zd\n\n", ext_csd_path, bytes_read);
1167        return;
1168    }
1169
1170    ext_pre_eol_info = 0;
1171    if (sscanf(buffer[EXT_PRE_EOL_INFO].str, "%02x", &ext_pre_eol_info) != 1) {
1172        printf("*** %s: PRE_EOL_INFO parse error \"%.2s\"\n\n",
1173               ext_csd_path, buffer[EXT_PRE_EOL_INFO].str);
1174        return;
1175    }
1176    printf("PRE_EOL_INFO %d (MMC %s)\n",
1177           ext_pre_eol_info,
1178           eol_str[(ext_pre_eol_info < (int)
1179                       (sizeof(eol_str) / sizeof(eol_str[0]))) ?
1180                           ext_pre_eol_info : 0]);
1181
1182    for (size_t lifetime = EXT_DEVICE_LIFE_TIME_EST_TYP_A;
1183            lifetime <= EXT_DEVICE_LIFE_TIME_EST_TYP_B;
1184            ++lifetime) {
1185        int ext_device_life_time_est;
1186        static const char *est_str[] = {
1187            "Undefined",
1188            "0-10% of device lifetime used",
1189            "10-20% of device lifetime used",
1190            "20-30% of device lifetime used",
1191            "30-40% of device lifetime used",
1192            "40-50% of device lifetime used",
1193            "50-60% of device lifetime used",
1194            "60-70% of device lifetime used",
1195            "70-80% of device lifetime used",
1196            "80-90% of device lifetime used",
1197            "90-100% of device lifetime used",
1198            "Exceeded the maximum estimated device lifetime",
1199        };
1200
1201        if (bytes_read < (ssize_t)(lifetime * sizeof(struct hex))) {
1202            printf("*** %s: truncated content %zd\n", ext_csd_path, bytes_read);
1203            break;
1204        }
1205
1206        ext_device_life_time_est = 0;
1207        if (sscanf(buffer[lifetime].str, "%02x", &ext_device_life_time_est) != 1) {
1208            printf("*** %s: DEVICE_LIFE_TIME_EST_TYP_%c parse error \"%.2s\"\n",
1209                   ext_csd_path,
1210                   (unsigned)(lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) + 'A',
1211                   buffer[lifetime].str);
1212            continue;
1213        }
1214        printf("DEVICE_LIFE_TIME_EST_TYP_%c %d (MMC %s)\n",
1215               (unsigned)(lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) + 'A',
1216               ext_device_life_time_est,
1217               est_str[(ext_device_life_time_est < (int)
1218                           (sizeof(est_str) / sizeof(est_str[0]))) ?
1219                               ext_device_life_time_est : 0]);
1220    }
1221
1222    printf("\n");
1223}
1224
1225// TODO: refactor all those commands that convert args
1226void format_args(int argc, const char *argv[], std::string *args) {
1227    LOG_ALWAYS_FATAL_IF(args == nullptr);
1228    for (int i = 0; i < argc; i++) {
1229        args->append(argv[i]);
1230        if (i < argc -1) {
1231          args->append(" ");
1232        }
1233    }
1234}
1235void format_args(const char* command, const char *args[], std::string *string) {
1236    LOG_ALWAYS_FATAL_IF(args == nullptr || command == nullptr);
1237    string->append(command);
1238    if (args[0] == nullptr) return;
1239    string->append(" ");
1240
1241    for (int arg = 1; arg <= 1000; ++arg) {
1242        if (args[arg] == nullptr) return;
1243        string->append(args[arg]);
1244        if (args[arg+1] != nullptr) {
1245            string->append(" ");
1246        }
1247    }
1248    MYLOGE("internal error: missing NULL entry on %s", string->c_str());
1249}
1250