debuggerd.c revision e5cc5396e83d12b7ca02ff6096a9950807aa010d
1/* system/debuggerd/debuggerd.c
2**
3** Copyright 2006, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9**     http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18#include <stdio.h>
19#include <errno.h>
20#include <signal.h>
21#include <pthread.h>
22#include <stdarg.h>
23#include <fcntl.h>
24#include <sys/types.h>
25#include <dirent.h>
26
27#include <sys/ptrace.h>
28#include <sys/wait.h>
29#include <sys/exec_elf.h>
30#include <sys/stat.h>
31
32#include <cutils/sockets.h>
33#include <cutils/logd.h>
34#include <cutils/logger.h>
35#include <cutils/properties.h>
36
37#include <linux/input.h>
38
39#include <private/android_filesystem_config.h>
40
41#include "debuggerd.h"
42#include "utility.h"
43
44#define ANDROID_LOG_INFO 4
45
46void _LOG(int tfd, bool in_tombstone_only, const char *fmt, ...)
47    __attribute__ ((format(printf, 3, 4)));
48
49/* Log information onto the tombstone */
50void _LOG(int tfd, bool in_tombstone_only, const char *fmt, ...)
51{
52    char buf[512];
53
54    va_list ap;
55    va_start(ap, fmt);
56
57    if (tfd >= 0) {
58        int len;
59        vsnprintf(buf, sizeof(buf), fmt, ap);
60        len = strlen(buf);
61        if(tfd >= 0) write(tfd, buf, len);
62    }
63
64    if (!in_tombstone_only)
65        __android_log_vprint(ANDROID_LOG_INFO, "DEBUG", fmt, ap);
66    va_end(ap);
67}
68
69// 6f000000-6f01e000 rwxp 00000000 00:0c 16389419   /system/lib/libcomposer.so
70// 012345678901234567890123456789012345678901234567890123456789
71// 0         1         2         3         4         5
72
73mapinfo *parse_maps_line(char *line)
74{
75    mapinfo *mi;
76    int len = strlen(line);
77
78    if (len < 1) return 0;      /* not expected */
79    line[--len] = 0;
80
81    if (len < 50) {
82        mi = malloc(sizeof(mapinfo) + 1);
83    } else {
84        mi = malloc(sizeof(mapinfo) + (len - 47));
85    }
86    if (mi == 0) return 0;
87
88    mi->isExecutable = (line[20] == 'x');
89
90    mi->start = strtoul(line, 0, 16);
91    mi->end = strtoul(line + 9, 0, 16);
92    /* To be filled in parse_elf_info if the mapped section starts with
93     * elf_header
94     */
95    mi->exidx_start = mi->exidx_end = 0;
96    mi->symbols = 0;
97    mi->next = 0;
98    if (len < 50) {
99        mi->name[0] = '\0';
100    } else {
101        strcpy(mi->name, line + 49);
102    }
103
104    return mi;
105}
106
107void dump_build_info(int tfd)
108{
109    char fingerprint[PROPERTY_VALUE_MAX];
110
111    property_get("ro.build.fingerprint", fingerprint, "unknown");
112
113    _LOG(tfd, false, "Build fingerprint: '%s'\n", fingerprint);
114}
115
116const char *get_signame(int sig)
117{
118    switch(sig) {
119    case SIGILL:     return "SIGILL";
120    case SIGABRT:    return "SIGABRT";
121    case SIGBUS:     return "SIGBUS";
122    case SIGFPE:     return "SIGFPE";
123    case SIGSEGV:    return "SIGSEGV";
124    case SIGSTKFLT:  return "SIGSTKFLT";
125    default:         return "?";
126    }
127}
128
129const char *get_sigcode(int signo, int code)
130{
131    switch (signo) {
132    case SIGILL:
133        switch (code) {
134        case ILL_ILLOPC: return "ILL_ILLOPC";
135        case ILL_ILLOPN: return "ILL_ILLOPN";
136        case ILL_ILLADR: return "ILL_ILLADR";
137        case ILL_ILLTRP: return "ILL_ILLTRP";
138        case ILL_PRVOPC: return "ILL_PRVOPC";
139        case ILL_PRVREG: return "ILL_PRVREG";
140        case ILL_COPROC: return "ILL_COPROC";
141        case ILL_BADSTK: return "ILL_BADSTK";
142        }
143        break;
144    case SIGBUS:
145        switch (code) {
146        case BUS_ADRALN: return "BUS_ADRALN";
147        case BUS_ADRERR: return "BUS_ADRERR";
148        case BUS_OBJERR: return "BUS_OBJERR";
149        }
150        break;
151    case SIGFPE:
152        switch (code) {
153        case FPE_INTDIV: return "FPE_INTDIV";
154        case FPE_INTOVF: return "FPE_INTOVF";
155        case FPE_FLTDIV: return "FPE_FLTDIV";
156        case FPE_FLTOVF: return "FPE_FLTOVF";
157        case FPE_FLTUND: return "FPE_FLTUND";
158        case FPE_FLTRES: return "FPE_FLTRES";
159        case FPE_FLTINV: return "FPE_FLTINV";
160        case FPE_FLTSUB: return "FPE_FLTSUB";
161        }
162        break;
163    case SIGSEGV:
164        switch (code) {
165        case SEGV_MAPERR: return "SEGV_MAPERR";
166        case SEGV_ACCERR: return "SEGV_ACCERR";
167        }
168        break;
169    }
170    return "?";
171}
172
173void dump_fault_addr(int tfd, int pid, int sig)
174{
175    siginfo_t si;
176
177    memset(&si, 0, sizeof(si));
178    if(ptrace(PTRACE_GETSIGINFO, pid, 0, &si)){
179        _LOG(tfd, false, "cannot get siginfo: %s\n", strerror(errno));
180    } else if (signal_has_address(sig)) {
181        _LOG(tfd, false, "signal %d (%s), code %d (%s), fault addr %08x\n",
182             sig, get_signame(sig),
183             si.si_code, get_sigcode(sig, si.si_code),
184             (uintptr_t) si.si_addr);
185    } else {
186        _LOG(tfd, false, "signal %d (%s), code %d (%s), fault addr --------\n",
187             sig, get_signame(sig), si.si_code, get_sigcode(sig, si.si_code));
188    }
189}
190
191void dump_crash_banner(int tfd, unsigned pid, unsigned tid, int sig)
192{
193    char data[1024];
194    char *x = 0;
195    FILE *fp;
196
197    sprintf(data, "/proc/%d/cmdline", pid);
198    fp = fopen(data, "r");
199    if(fp) {
200        x = fgets(data, 1024, fp);
201        fclose(fp);
202    }
203
204    _LOG(tfd, false,
205         "*** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***\n");
206    dump_build_info(tfd);
207    _LOG(tfd, false, "pid: %d, tid: %d  >>> %s <<<\n",
208         pid, tid, x ? x : "UNKNOWN");
209
210    if(sig) dump_fault_addr(tfd, tid, sig);
211}
212
213static void parse_elf_info(mapinfo *milist, pid_t pid)
214{
215    mapinfo *mi;
216    for (mi = milist; mi != NULL; mi = mi->next) {
217        if (!mi->isExecutable)
218            continue;
219
220        Elf32_Ehdr ehdr;
221
222        memset(&ehdr, 0, sizeof(Elf32_Ehdr));
223        /* Read in sizeof(Elf32_Ehdr) worth of data from the beginning of
224         * mapped section.
225         */
226        get_remote_struct(pid, (void *) (mi->start), &ehdr,
227                          sizeof(Elf32_Ehdr));
228        /* Check if it has the matching magic words */
229        if (IS_ELF(ehdr)) {
230            Elf32_Phdr phdr;
231            Elf32_Phdr *ptr;
232            int i;
233
234            ptr = (Elf32_Phdr *) (mi->start + ehdr.e_phoff);
235            for (i = 0; i < ehdr.e_phnum; i++) {
236                /* Parse the program header */
237                get_remote_struct(pid, (char *) (ptr+i), &phdr,
238                                  sizeof(Elf32_Phdr));
239#ifdef __arm__
240                /* Found a EXIDX segment? */
241                if (phdr.p_type == PT_ARM_EXIDX) {
242                    mi->exidx_start = mi->start + phdr.p_offset;
243                    mi->exidx_end = mi->exidx_start + phdr.p_filesz;
244                    break;
245                }
246#endif
247            }
248
249            /* Try to load symbols from this file */
250            mi->symbols = symbol_table_create(mi->name);
251        }
252    }
253}
254
255void dump_crash_report(int tfd, unsigned pid, unsigned tid, bool at_fault)
256{
257    char data[1024];
258    FILE *fp;
259    mapinfo *milist = 0;
260    unsigned int sp_list[STACK_CONTENT_DEPTH];
261    int stack_depth;
262#ifdef __arm__
263    int frame0_pc_sane = 1;
264#endif
265
266    if (!at_fault) {
267        _LOG(tfd, true,
268         "--- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---\n");
269        _LOG(tfd, true, "pid: %d, tid: %d\n", pid, tid);
270    }
271
272    dump_registers(tfd, tid, at_fault);
273
274    /* Clear stack pointer records */
275    memset(sp_list, 0, sizeof(sp_list));
276
277    sprintf(data, "/proc/%d/maps", pid);
278    fp = fopen(data, "r");
279    if(fp) {
280        while(fgets(data, 1024, fp)) {
281            mapinfo *mi = parse_maps_line(data);
282            if(mi) {
283                mi->next = milist;
284                milist = mi;
285            }
286        }
287        fclose(fp);
288    }
289
290    parse_elf_info(milist, tid);
291
292#if __arm__
293    /* If stack unwinder fails, use the default solution to dump the stack
294     * content.
295     */
296    stack_depth = unwind_backtrace_with_ptrace(tfd, tid, milist, sp_list,
297                                               &frame0_pc_sane, at_fault);
298
299    /* The stack unwinder should at least unwind two levels of stack. If less
300     * level is seen we make sure at lease pc and lr are dumped.
301     */
302    if (stack_depth < 2) {
303        dump_pc_and_lr(tfd, tid, milist, stack_depth, at_fault);
304    }
305
306    dump_stack_and_code(tfd, tid, milist, stack_depth, sp_list, at_fault);
307#elif __i386__
308    /* If stack unwinder fails, use the default solution to dump the stack
309    * content.
310    */
311    stack_depth = unwind_backtrace_with_ptrace_x86(tfd, tid, milist,at_fault);
312#else
313#error "Unsupported architecture"
314#endif
315
316    while(milist) {
317        mapinfo *next = milist->next;
318        symbol_table_free(milist->symbols);
319        free(milist);
320        milist = next;
321    }
322}
323
324#define MAX_TOMBSTONES	10
325
326#define typecheck(x,y) {    \
327    typeof(x) __dummy1;     \
328    typeof(y) __dummy2;     \
329    (void)(&__dummy1 == &__dummy2); }
330
331#define TOMBSTONE_DIR	"/data/tombstones"
332
333/*
334 * find_and_open_tombstone - find an available tombstone slot, if any, of the
335 * form tombstone_XX where XX is 00 to MAX_TOMBSTONES-1, inclusive. If no
336 * file is available, we reuse the least-recently-modified file.
337 */
338static int find_and_open_tombstone(void)
339{
340    unsigned long mtime = ULONG_MAX;
341    struct stat sb;
342    char path[128];
343    int fd, i, oldest = 0;
344
345    /*
346     * XXX: Our stat.st_mtime isn't time_t. If it changes, as it probably ought
347     * to, our logic breaks. This check will generate a warning if that happens.
348     */
349    typecheck(mtime, sb.st_mtime);
350
351    /*
352     * In a single wolf-like pass, find an available slot and, in case none
353     * exist, find and record the least-recently-modified file.
354     */
355    for (i = 0; i < MAX_TOMBSTONES; i++) {
356        snprintf(path, sizeof(path), TOMBSTONE_DIR"/tombstone_%02d", i);
357
358        if (!stat(path, &sb)) {
359            if (sb.st_mtime < mtime) {
360                oldest = i;
361                mtime = sb.st_mtime;
362            }
363            continue;
364        }
365        if (errno != ENOENT)
366            continue;
367
368        fd = open(path, O_CREAT | O_EXCL | O_WRONLY, 0600);
369        if (fd < 0)
370            continue;	/* raced ? */
371
372        fchown(fd, AID_SYSTEM, AID_SYSTEM);
373        return fd;
374    }
375
376    /* we didn't find an available file, so we clobber the oldest one */
377    snprintf(path, sizeof(path), TOMBSTONE_DIR"/tombstone_%02d", oldest);
378    fd = open(path, O_CREAT | O_TRUNC | O_WRONLY, 0600);
379    fchown(fd, AID_SYSTEM, AID_SYSTEM);
380
381    return fd;
382}
383
384/* Return true if some thread is not detached cleanly */
385static bool dump_sibling_thread_report(int tfd, unsigned pid, unsigned tid)
386{
387    char task_path[1024];
388
389    sprintf(task_path, "/proc/%d/task", pid);
390    DIR *d;
391    struct dirent *de;
392    int need_cleanup = 0;
393
394    d = opendir(task_path);
395    /* Bail early if cannot open the task directory */
396    if (d == NULL) {
397        XLOG("Cannot open /proc/%d/task\n", pid);
398        return false;
399    }
400    while ((de = readdir(d)) != NULL) {
401        unsigned new_tid;
402        /* Ignore "." and ".." */
403        if (!strcmp(de->d_name, ".") || !strcmp(de->d_name, ".."))
404            continue;
405        new_tid = atoi(de->d_name);
406        /* The main thread at fault has been handled individually */
407        if (new_tid == tid)
408            continue;
409
410        /* Skip this thread if cannot ptrace it */
411        if (ptrace(PTRACE_ATTACH, new_tid, 0, 0) < 0)
412            continue;
413
414        dump_crash_report(tfd, pid, new_tid, false);
415
416        if (ptrace(PTRACE_DETACH, new_tid, 0, 0) != 0) {
417            XLOG("detach of tid %d failed: %s\n", new_tid, strerror(errno));
418            need_cleanup = 1;
419        }
420    }
421    closedir(d);
422
423    return need_cleanup != 0;
424}
425
426/*
427 * Reads the contents of the specified log device, filters out the entries
428 * that don't match the specified pid, and writes them to the tombstone file.
429 *
430 * If "tailOnly" is set, we only print the last few lines.
431 */
432static void dump_log_file(int tfd, unsigned pid, const char* filename,
433    bool tailOnly)
434{
435    bool first = true;
436
437    /* circular buffer, for "tailOnly" mode */
438    const int kShortLogMaxLines = 5;
439    const int kShortLogLineLen = 256;
440    char shortLog[kShortLogMaxLines][kShortLogLineLen];
441    int shortLogCount = 0;
442    int shortLogNext = 0;
443
444    int logfd = open(filename, O_RDONLY | O_NONBLOCK);
445    if (logfd < 0) {
446        XLOG("Unable to open %s: %s\n", filename, strerror(errno));
447        return;
448    }
449
450    union {
451        unsigned char buf[LOGGER_ENTRY_MAX_LEN + 1];
452        struct logger_entry entry;
453    } log_entry;
454
455    while (true) {
456        ssize_t actual = read(logfd, log_entry.buf, LOGGER_ENTRY_MAX_LEN);
457        if (actual < 0) {
458            if (errno == EINTR) {
459                /* interrupted by signal, retry */
460                continue;
461            } else if (errno == EAGAIN) {
462                /* non-blocking EOF; we're done */
463                break;
464            } else {
465                _LOG(tfd, true, "Error while reading log: %s\n",
466                    strerror(errno));
467                break;
468            }
469        } else if (actual == 0) {
470            _LOG(tfd, true, "Got zero bytes while reading log: %s\n",
471                strerror(errno));
472            break;
473        }
474
475        /*
476         * NOTE: if you XLOG something here, this will spin forever,
477         * because you will be writing as fast as you're reading.  Any
478         * high-frequency debug diagnostics should just be written to
479         * the tombstone file.
480         */
481
482        struct logger_entry* entry = &log_entry.entry;
483
484        if (entry->pid != (int32_t) pid) {
485            /* wrong pid, ignore */
486            continue;
487        }
488
489        if (first) {
490            _LOG(tfd, true, "--------- %slog %s\n",
491                tailOnly ? "tail end of " : "", filename);
492            first = false;
493        }
494
495        /*
496         * Msg format is: <priority:1><tag:N>\0<message:N>\0
497         *
498         * We want to display it in the same format as "logcat -v threadtime"
499         * (although in this case the pid is redundant).
500         *
501         * TODO: scan for line breaks ('\n') and display each text line
502         * on a separate line, prefixed with the header, like logcat does.
503         */
504        static const char* kPrioChars = "!.VDIWEFS";
505        unsigned char prio = entry->msg[0];
506        char* tag = entry->msg + 1;
507        char* msg = tag + strlen(tag) + 1;
508
509        /* consume any trailing newlines */
510        char* eatnl = msg + strlen(msg) - 1;
511        while (eatnl >= msg && *eatnl == '\n') {
512            *eatnl-- = '\0';
513        }
514
515        char prioChar = (prio < strlen(kPrioChars) ? kPrioChars[prio] : '?');
516
517        char timeBuf[32];
518        time_t sec = (time_t) entry->sec;
519        struct tm tmBuf;
520        struct tm* ptm;
521        ptm = localtime_r(&sec, &tmBuf);
522        strftime(timeBuf, sizeof(timeBuf), "%m-%d %H:%M:%S", ptm);
523
524        if (tailOnly) {
525            snprintf(shortLog[shortLogNext], kShortLogLineLen,
526                "%s.%03d %5d %5d %c %-8s: %s",
527                timeBuf, entry->nsec / 1000000, entry->pid, entry->tid,
528                prioChar, tag, msg);
529            shortLogNext = (shortLogNext + 1) % kShortLogMaxLines;
530            shortLogCount++;
531        } else {
532            _LOG(tfd, true, "%s.%03d %5d %5d %c %-8s: %s\n",
533                timeBuf, entry->nsec / 1000000, entry->pid, entry->tid,
534                prioChar, tag, msg);
535        }
536    }
537
538    if (tailOnly) {
539        int i;
540
541        /*
542         * If we filled the buffer, we want to start at "next", which has
543         * the oldest entry.  If we didn't, we want to start at zero.
544         */
545        if (shortLogCount < kShortLogMaxLines) {
546            shortLogNext = 0;
547        } else {
548            shortLogCount = kShortLogMaxLines;  /* cap at window size */
549        }
550
551        for (i = 0; i < shortLogCount; i++) {
552            _LOG(tfd, true, "%s\n", shortLog[shortLogNext]);
553            shortLogNext = (shortLogNext + 1) % kShortLogMaxLines;
554        }
555    }
556
557    close(logfd);
558}
559
560/*
561 * Dumps the logs generated by the specified pid to the tombstone, from both
562 * "system" and "main" log devices.  Ideally we'd interleave the output.
563 */
564static void dump_logs(int tfd, unsigned pid, bool tailOnly)
565{
566    dump_log_file(tfd, pid, "/dev/log/system", tailOnly);
567    dump_log_file(tfd, pid, "/dev/log/main", tailOnly);
568}
569
570/* Return true if some thread is not detached cleanly */
571static bool engrave_tombstone(unsigned pid, unsigned tid, int debug_uid,
572                              int signal)
573{
574    int fd;
575    bool need_cleanup = false;
576
577    /* don't copy log messages to tombstone unless this is a dev device */
578    char value[PROPERTY_VALUE_MAX];
579    property_get("ro.debuggable", value, "0");
580    bool wantLogs = (value[0] == '1');
581
582    mkdir(TOMBSTONE_DIR, 0755);
583    chown(TOMBSTONE_DIR, AID_SYSTEM, AID_SYSTEM);
584
585    fd = find_and_open_tombstone();
586    if (fd < 0)
587        return need_cleanup;
588
589    dump_crash_banner(fd, pid, tid, signal);
590    dump_crash_report(fd, pid, tid, true);
591
592    if (wantLogs) {
593        dump_logs(fd, pid, true);
594    }
595
596    /*
597     * If the user has requested to attach gdb, don't collect the per-thread
598     * information as it increases the chance to lose track of the process.
599     */
600    if ((signed)pid > debug_uid) {
601        need_cleanup = dump_sibling_thread_report(fd, pid, tid);
602    }
603
604    if (wantLogs) {
605        dump_logs(fd, pid, false);
606    }
607
608    close(fd);
609    return need_cleanup;
610}
611
612static int
613write_string(const char* file, const char* string)
614{
615    int len;
616    int fd;
617    ssize_t amt;
618    fd = open(file, O_RDWR);
619    len = strlen(string);
620    if (fd < 0)
621        return -errno;
622    amt = write(fd, string, len);
623    close(fd);
624    return amt >= 0 ? 0 : -errno;
625}
626
627static
628void init_debug_led(void)
629{
630    // trout leds
631    write_string("/sys/class/leds/red/brightness", "0");
632    write_string("/sys/class/leds/green/brightness", "0");
633    write_string("/sys/class/leds/blue/brightness", "0");
634    write_string("/sys/class/leds/red/device/blink", "0");
635    // sardine leds
636    write_string("/sys/class/leds/left/cadence", "0,0");
637}
638
639static
640void enable_debug_led(void)
641{
642    // trout leds
643    write_string("/sys/class/leds/red/brightness", "255");
644    // sardine leds
645    write_string("/sys/class/leds/left/cadence", "1,0");
646}
647
648static
649void disable_debug_led(void)
650{
651    // trout leds
652    write_string("/sys/class/leds/red/brightness", "0");
653    // sardine leds
654    write_string("/sys/class/leds/left/cadence", "0,0");
655}
656
657extern int init_getevent();
658extern void uninit_getevent();
659extern int get_event(struct input_event* event, int timeout);
660
661static void wait_for_user_action(unsigned tid, struct ucred* cr)
662{
663    (void)tid;
664    /* First log a helpful message */
665    LOG(    "********************************************************\n"
666            "* Process %d has been suspended while crashing.  To\n"
667            "* attach gdbserver for a gdb connection on port 5039:\n"
668            "*\n"
669            "*     adb shell gdbserver :5039 --attach %d &\n"
670            "*\n"
671            "* Press HOME key to let the process continue crashing.\n"
672            "********************************************************\n",
673            cr->pid, cr->pid);
674
675    /* wait for HOME key (TODO: something useful for devices w/o HOME key) */
676    if (init_getevent() == 0) {
677        int ms = 1200 / 10;
678        int dit = 1;
679        int dah = 3*dit;
680        int _       = -dit;
681        int ___     = 3*_;
682        int _______ = 7*_;
683        const signed char codes[] = {
684           dit,_,dit,_,dit,___,dah,_,dah,_,dah,___,dit,_,dit,_,dit,_______
685        };
686        size_t s = 0;
687        struct input_event e;
688        int home = 0;
689        init_debug_led();
690        enable_debug_led();
691        do {
692            int timeout = abs((int)(codes[s])) * ms;
693            int res = get_event(&e, timeout);
694            if (res == 0) {
695                if (e.type==EV_KEY && e.code==KEY_HOME && e.value==0)
696                    home = 1;
697            } else if (res == 1) {
698                if (++s >= sizeof(codes)/sizeof(*codes))
699                    s = 0;
700                if (codes[s] > 0) {
701                    enable_debug_led();
702                } else {
703                    disable_debug_led();
704                }
705            }
706        } while (!home);
707        uninit_getevent();
708    }
709
710    /* don't forget to turn debug led off */
711    disable_debug_led();
712
713    /* close filedescriptor */
714    LOG("debuggerd resuming process %d", cr->pid);
715 }
716
717static void handle_crashing_process(int fd)
718{
719    char buf[64];
720    struct stat s;
721    unsigned tid;
722    struct ucred cr;
723    int n, len, status;
724    int tid_attach_status = -1;
725    unsigned retry = 30;
726    bool need_cleanup = false;
727
728    char value[PROPERTY_VALUE_MAX];
729    property_get("debug.db.uid", value, "-1");
730    int debug_uid = atoi(value);
731
732    XLOG("handle_crashing_process(%d)\n", fd);
733
734    len = sizeof(cr);
735    n = getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &cr, &len);
736    if(n != 0) {
737        LOG("cannot get credentials\n");
738        goto done;
739    }
740
741    XLOG("reading tid\n");
742    fcntl(fd, F_SETFL, O_NONBLOCK);
743    while((n = read(fd, &tid, sizeof(unsigned))) != sizeof(unsigned)) {
744        if(errno == EINTR) continue;
745        if(errno == EWOULDBLOCK) {
746            if(retry-- > 0) {
747                usleep(100 * 1000);
748                continue;
749            }
750            LOG("timed out reading tid\n");
751            goto done;
752        }
753        LOG("read failure? %s\n", strerror(errno));
754        goto done;
755    }
756
757    snprintf(buf, sizeof buf, "/proc/%d/task/%d", cr.pid, tid);
758    if(stat(buf, &s)) {
759        LOG("tid %d does not exist in pid %d. ignoring debug request\n",
760            tid, cr.pid);
761        close(fd);
762        return;
763    }
764
765    XLOG("BOOM: pid=%d uid=%d gid=%d tid=%d\n", cr.pid, cr.uid, cr.gid, tid);
766
767    /* Note that at this point, the target thread's signal handler
768     * is blocked in a read() call. This gives us the time to PTRACE_ATTACH
769     * to it before it has a chance to really fault.
770     *
771     * The PTRACE_ATTACH sends a SIGSTOP to the target process, but it
772     * won't necessarily have stopped by the time ptrace() returns.  (We
773     * currently assume it does.)  We write to the file descriptor to
774     * ensure that it can run as soon as we call PTRACE_CONT below.
775     * See details in bionic/libc/linker/debugger.c, in function
776     * debugger_signal_handler().
777     */
778    tid_attach_status = ptrace(PTRACE_ATTACH, tid, 0, 0);
779    int ptrace_error = errno;
780
781    if (TEMP_FAILURE_RETRY(write(fd, &tid, 1)) != 1) {
782        XLOG("failed responding to client: %s\n",
783            strerror(errno));
784        goto done;
785    }
786
787    if(tid_attach_status < 0) {
788        LOG("ptrace attach failed: %s\n", strerror(ptrace_error));
789        goto done;
790    }
791
792    close(fd);
793    fd = -1;
794
795    const int sleep_time_usec = 200000;         /* 0.2 seconds */
796    const int max_total_sleep_usec = 3000000;   /* 3 seconds */
797    int loop_limit = max_total_sleep_usec / sleep_time_usec;
798    for(;;) {
799        if (loop_limit-- == 0) {
800            LOG("timed out waiting for pid=%d tid=%d uid=%d to die\n",
801                cr.pid, tid, cr.uid);
802            goto done;
803        }
804        n = waitpid(tid, &status, __WALL | WNOHANG);
805
806        if (n == 0) {
807            /* not ready yet */
808            XLOG("not ready yet\n");
809            usleep(sleep_time_usec);
810            continue;
811        }
812
813        if(n < 0) {
814            if(errno == EAGAIN) continue;
815            LOG("waitpid failed: %s\n", strerror(errno));
816            goto done;
817        }
818
819        XLOG("waitpid: n=%d status=%08x\n", n, status);
820
821        if(WIFSTOPPED(status)){
822            n = WSTOPSIG(status);
823            switch(n) {
824            case SIGSTOP:
825                XLOG("stopped -- continuing\n");
826                n = ptrace(PTRACE_CONT, tid, 0, 0);
827                if(n) {
828                    LOG("ptrace failed: %s\n", strerror(errno));
829                    goto done;
830                }
831                continue;
832
833            case SIGILL:
834            case SIGABRT:
835            case SIGBUS:
836            case SIGFPE:
837            case SIGSEGV:
838            case SIGSTKFLT: {
839                XLOG("stopped -- fatal signal\n");
840                need_cleanup = engrave_tombstone(cr.pid, tid, debug_uid, n);
841                kill(tid, SIGSTOP);
842                goto done;
843            }
844
845            default:
846                XLOG("stopped -- unexpected signal\n");
847                goto done;
848            }
849        } else {
850            XLOG("unexpected waitpid response\n");
851            goto done;
852        }
853    }
854
855done:
856    XLOG("detaching\n");
857
858    /* stop the process so we can debug */
859    kill(cr.pid, SIGSTOP);
860
861    /*
862     * If a thread has been attached by ptrace, make sure it is detached
863     * successfully otherwise we will get a zombie.
864     */
865    if (tid_attach_status == 0) {
866        int detach_status;
867        /* detach so we can attach gdbserver */
868        detach_status = ptrace(PTRACE_DETACH, tid, 0, 0);
869        need_cleanup |= (detach_status != 0);
870    }
871
872    /*
873     * if debug.db.uid is set, its value indicates if we should wait
874     * for user action for the crashing process.
875     * in this case, we log a message and turn the debug LED on
876     * waiting for a gdb connection (for instance)
877     */
878
879    if ((signed)cr.uid <= debug_uid) {
880        wait_for_user_action(tid, &cr);
881    }
882
883    /*
884     * Resume stopped process (so it can crash in peace).  If we didn't
885     * successfully detach, we're still the parent, and the actual parent
886     * won't receive a death notification via wait(2).  At this point
887     * there's not much we can do about that.
888     */
889    kill(cr.pid, SIGCONT);
890
891    if (need_cleanup) {
892        LOG("debuggerd committing suicide to free the zombie!\n");
893        kill(getpid(), SIGKILL);
894    }
895
896    if(fd != -1) close(fd);
897}
898
899
900int main()
901{
902    int s;
903    struct sigaction act;
904    int logsocket = -1;
905
906    /*
907     * debuggerd crashes can't be reported to debuggerd.  Reset all of the
908     * crash handlers.
909     */
910    signal(SIGILL, SIG_DFL);
911    signal(SIGABRT, SIG_DFL);
912    signal(SIGBUS, SIG_DFL);
913    signal(SIGFPE, SIG_DFL);
914    signal(SIGSEGV, SIG_DFL);
915    signal(SIGSTKFLT, SIG_DFL);
916    signal(SIGPIPE, SIG_DFL);
917
918    logsocket = socket_local_client("logd",
919            ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_DGRAM);
920    if(logsocket < 0) {
921        logsocket = -1;
922    } else {
923        fcntl(logsocket, F_SETFD, FD_CLOEXEC);
924    }
925
926    act.sa_handler = SIG_DFL;
927    sigemptyset(&act.sa_mask);
928    sigaddset(&act.sa_mask,SIGCHLD);
929    act.sa_flags = SA_NOCLDWAIT;
930    sigaction(SIGCHLD, &act, 0);
931
932    s = socket_local_server("android:debuggerd",
933            ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
934    if(s < 0) return -1;
935    fcntl(s, F_SETFD, FD_CLOEXEC);
936
937    LOG("debuggerd: " __DATE__ " " __TIME__ "\n");
938
939    for(;;) {
940        struct sockaddr addr;
941        socklen_t alen;
942        int fd;
943
944        alen = sizeof(addr);
945        XLOG("waiting for connection\n");
946        fd = accept(s, &addr, &alen);
947        if(fd < 0) {
948            XLOG("accept failed: %s\n", strerror(errno));
949            continue;
950        }
951
952        fcntl(fd, F_SETFD, FD_CLOEXEC);
953
954        handle_crashing_process(fd);
955    }
956    return 0;
957}
958