debuggerd.c revision c031a3b006129ca408eaade325a53a334daee3b2
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 <stdlib.h>
20#include <unistd.h>
21#include <errno.h>
22#include <signal.h>
23#include <pthread.h>
24#include <stdarg.h>
25#include <fcntl.h>
26#include <sys/types.h>
27#include <dirent.h>
28
29#include <sys/ptrace.h>
30#include <sys/wait.h>
31#include <sys/exec_elf.h>
32#include <sys/stat.h>
33
34#include <cutils/sockets.h>
35#include <cutils/logd.h>
36#include <cutils/sockets.h>
37#include <cutils/properties.h>
38
39#include <linux/input.h>
40
41#include <private/android_filesystem_config.h>
42
43#include <byteswap.h>
44#include "utility.h"
45
46#ifdef WITH_VFP
47#ifdef WITH_VFP_D32
48#define NUM_VFP_REGS 32
49#else
50#define NUM_VFP_REGS 16
51#endif
52#endif
53
54/* Main entry point to get the backtrace from the crashing process */
55extern int unwind_backtrace_with_ptrace(int tfd, pid_t pid, mapinfo *map,
56                                        unsigned int sp_list[],
57                                        int *frame0_pc_sane,
58                                        bool at_fault);
59
60static int logsocket = -1;
61
62#define ANDROID_LOG_INFO 4
63
64/* Log information onto the tombstone */
65void _LOG(int tfd, bool in_tombstone_only, const char *fmt, ...)
66{
67    char buf[512];
68
69    va_list ap;
70    va_start(ap, fmt);
71
72    if (tfd >= 0) {
73        int len;
74        vsnprintf(buf, sizeof(buf), fmt, ap);
75        len = strlen(buf);
76        if(tfd >= 0) write(tfd, buf, len);
77    }
78
79    if (!in_tombstone_only)
80        __android_log_vprint(ANDROID_LOG_INFO, "DEBUG", fmt, ap);
81}
82
83#define LOG(fmt...) _LOG(-1, 0, fmt)
84#if 0
85#define XLOG(fmt...) _LOG(-1, 0, fmt)
86#else
87#define XLOG(fmt...) do {} while(0)
88#endif
89
90// 6f000000-6f01e000 rwxp 00000000 00:0c 16389419   /system/lib/libcomposer.so
91// 012345678901234567890123456789012345678901234567890123456789
92// 0         1         2         3         4         5
93
94mapinfo *parse_maps_line(char *line)
95{
96    mapinfo *mi;
97    int len = strlen(line);
98
99    if(len < 1) return 0;
100    line[--len] = 0;
101
102    if(len < 50) return 0;
103    if(line[20] != 'x') return 0;
104
105    mi = malloc(sizeof(mapinfo) + (len - 47));
106    if(mi == 0) return 0;
107
108    mi->start = strtoul(line, 0, 16);
109    mi->end = strtoul(line + 9, 0, 16);
110    /* To be filled in parse_elf_info if the mapped section starts with
111     * elf_header
112     */
113    mi->exidx_start = mi->exidx_end = 0;
114    mi->symbols = 0;
115    mi->next = 0;
116    strcpy(mi->name, line + 49);
117
118    return mi;
119}
120
121void dump_build_info(int tfd)
122{
123    char fingerprint[PROPERTY_VALUE_MAX];
124
125    property_get("ro.build.fingerprint", fingerprint, "unknown");
126
127    _LOG(tfd, false, "Build fingerprint: '%s'\n", fingerprint);
128}
129
130
131void dump_stack_and_code(int tfd, int pid, mapinfo *map,
132                         int unwind_depth, unsigned int sp_list[],
133                         bool at_fault)
134{
135    unsigned int sp, pc, p, end, data;
136    struct pt_regs r;
137    int sp_depth;
138    bool only_in_tombstone = !at_fault;
139    char code_buffer[80];
140
141    if(ptrace(PTRACE_GETREGS, pid, 0, &r)) return;
142    sp = r.ARM_sp;
143    pc = r.ARM_pc;
144
145    _LOG(tfd, only_in_tombstone, "\ncode around pc:\n");
146
147    end = p = pc & ~3;
148    p -= 32;
149    end += 32;
150
151    /* Dump the code around PC as:
152     *  addr       contents
153     *  00008d34   fffffcd0 4c0eb530 b0934a0e 1c05447c
154     *  00008d44   f7ff18a0 490ced94 68035860 d0012b00
155     */
156    while (p <= end) {
157        int i;
158
159        sprintf(code_buffer, "%08x ", p);
160        for (i = 0; i < 4; i++) {
161            data = ptrace(PTRACE_PEEKTEXT, pid, (void*)p, NULL);
162            sprintf(code_buffer + strlen(code_buffer), "%08x ", data);
163            p += 4;
164        }
165        _LOG(tfd, only_in_tombstone, "%s\n", code_buffer);
166    }
167
168    if ((unsigned) r.ARM_lr != pc) {
169        _LOG(tfd, only_in_tombstone, "\ncode around lr:\n");
170
171        end = p = r.ARM_lr & ~3;
172        p -= 32;
173        end += 32;
174
175        /* Dump the code around LR as:
176         *  addr       contents
177         *  00008d34   fffffcd0 4c0eb530 b0934a0e 1c05447c
178         *  00008d44   f7ff18a0 490ced94 68035860 d0012b00
179         */
180        while (p <= end) {
181            int i;
182
183            sprintf(code_buffer, "%08x ", p);
184            for (i = 0; i < 4; i++) {
185                data = ptrace(PTRACE_PEEKTEXT, pid, (void*)p, NULL);
186                sprintf(code_buffer + strlen(code_buffer), "%08x ", data);
187                p += 4;
188            }
189            _LOG(tfd, only_in_tombstone, "%s\n", code_buffer);
190        }
191    }
192
193    p = sp - 64;
194    p &= ~3;
195    if (unwind_depth != 0) {
196        if (unwind_depth < STACK_CONTENT_DEPTH) {
197            end = sp_list[unwind_depth-1];
198        }
199        else {
200            end = sp_list[STACK_CONTENT_DEPTH-1];
201        }
202    }
203    else {
204        end = sp | 0x000000ff;
205        end += 0xff;
206    }
207
208    _LOG(tfd, only_in_tombstone, "\nstack:\n");
209
210    /* If the crash is due to PC == 0, there will be two frames that
211     * have identical SP value.
212     */
213    if (sp_list[0] == sp_list[1]) {
214        sp_depth = 1;
215    }
216    else {
217        sp_depth = 0;
218    }
219
220    while (p <= end) {
221         char *prompt;
222         char level[16];
223         data = ptrace(PTRACE_PEEKTEXT, pid, (void*)p, NULL);
224         if (p == sp_list[sp_depth]) {
225             sprintf(level, "#%02d", sp_depth++);
226             prompt = level;
227         }
228         else {
229             prompt = "   ";
230         }
231
232         /* Print the stack content in the log for the first 3 frames. For the
233          * rest only print them in the tombstone file.
234          */
235         _LOG(tfd, (sp_depth > 2) || only_in_tombstone,
236              "%s %08x  %08x  %s\n", prompt, p, data,
237              map_to_name(map, data, ""));
238         p += 4;
239    }
240    /* print another 64-byte of stack data after the last frame */
241
242    end = p+64;
243    while (p <= end) {
244         data = ptrace(PTRACE_PEEKTEXT, pid, (void*)p, NULL);
245         _LOG(tfd, (sp_depth > 2) || only_in_tombstone,
246              "    %08x  %08x  %s\n", p, data,
247              map_to_name(map, data, ""));
248         p += 4;
249    }
250}
251
252void dump_pc_and_lr(int tfd, int pid, mapinfo *map, int unwound_level,
253                    bool at_fault)
254{
255    struct pt_regs r;
256
257    if(ptrace(PTRACE_GETREGS, pid, 0, &r)) {
258        _LOG(tfd, !at_fault, "tid %d not responding!\n", pid);
259        return;
260    }
261
262    if (unwound_level == 0) {
263        _LOG(tfd, !at_fault, "         #%02d  pc %08x  %s\n", 0, r.ARM_pc,
264             map_to_name(map, r.ARM_pc, "<unknown>"));
265    }
266    _LOG(tfd, !at_fault, "         #%02d  lr %08x  %s\n", 1, r.ARM_lr,
267            map_to_name(map, r.ARM_lr, "<unknown>"));
268}
269
270void dump_registers(int tfd, int pid, bool at_fault)
271{
272    struct pt_regs r;
273    bool only_in_tombstone = !at_fault;
274
275    if(ptrace(PTRACE_GETREGS, pid, 0, &r)) {
276        _LOG(tfd, only_in_tombstone,
277             "cannot get registers: %s\n", strerror(errno));
278        return;
279    }
280
281    _LOG(tfd, only_in_tombstone, " r0 %08x  r1 %08x  r2 %08x  r3 %08x\n",
282         r.ARM_r0, r.ARM_r1, r.ARM_r2, r.ARM_r3);
283    _LOG(tfd, only_in_tombstone, " r4 %08x  r5 %08x  r6 %08x  r7 %08x\n",
284         r.ARM_r4, r.ARM_r5, r.ARM_r6, r.ARM_r7);
285    _LOG(tfd, only_in_tombstone, " r8 %08x  r9 %08x  10 %08x  fp %08x\n",
286         r.ARM_r8, r.ARM_r9, r.ARM_r10, r.ARM_fp);
287    _LOG(tfd, only_in_tombstone,
288         " ip %08x  sp %08x  lr %08x  pc %08x  cpsr %08x\n",
289         r.ARM_ip, r.ARM_sp, r.ARM_lr, r.ARM_pc, r.ARM_cpsr);
290
291#ifdef WITH_VFP
292    struct user_vfp vfp_regs;
293    int i;
294
295    if(ptrace(PTRACE_GETVFPREGS, pid, 0, &vfp_regs)) {
296        _LOG(tfd, only_in_tombstone,
297             "cannot get registers: %s\n", strerror(errno));
298        return;
299    }
300
301    for (i = 0; i < NUM_VFP_REGS; i += 2) {
302        _LOG(tfd, only_in_tombstone,
303             " d%-2d %016llx  d%-2d %016llx\n",
304              i, vfp_regs.fpregs[i], i+1, vfp_regs.fpregs[i+1]);
305    }
306    _LOG(tfd, only_in_tombstone, " scr %08lx\n\n", vfp_regs.fpscr);
307#endif
308}
309
310const char *get_signame(int sig)
311{
312    switch(sig) {
313    case SIGILL:     return "SIGILL";
314    case SIGABRT:    return "SIGABRT";
315    case SIGBUS:     return "SIGBUS";
316    case SIGFPE:     return "SIGFPE";
317    case SIGSEGV:    return "SIGSEGV";
318    case SIGSTKFLT:  return "SIGSTKFLT";
319    default:         return "?";
320    }
321}
322
323void dump_fault_addr(int tfd, int pid, int sig)
324{
325    siginfo_t si;
326
327    memset(&si, 0, sizeof(si));
328    if(ptrace(PTRACE_GETSIGINFO, pid, 0, &si)){
329        _LOG(tfd, false, "cannot get siginfo: %s\n", strerror(errno));
330    } else {
331        _LOG(tfd, false, "signal %d (%s), fault addr %08x\n",
332            sig, get_signame(sig), si.si_addr);
333    }
334}
335
336void dump_crash_banner(int tfd, unsigned pid, unsigned tid, int sig)
337{
338    char data[1024];
339    char *x = 0;
340    FILE *fp;
341
342    sprintf(data, "/proc/%d/cmdline", pid);
343    fp = fopen(data, "r");
344    if(fp) {
345        x = fgets(data, 1024, fp);
346        fclose(fp);
347    }
348
349    _LOG(tfd, false,
350         "*** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***\n");
351    dump_build_info(tfd);
352    _LOG(tfd, false, "pid: %d, tid: %d  >>> %s <<<\n",
353         pid, tid, x ? x : "UNKNOWN");
354
355    if(sig) dump_fault_addr(tfd, tid, sig);
356}
357
358/* After randomization (ASLR), stack contents that point to randomized
359 * code become uninterpretable (e.g. can't be resolved to line numbers).
360 * Here, we bundle enough information so that stack analysis on the
361 * server side can still be performed. This means we are leaking some
362 * information about the device (its randomization base). We have to make
363 * sure an attacker has no way of intercepting the tombstone.
364 */
365
366typedef struct {
367    int32_t mmap_addr;
368    char tag[4]; /* 'P', 'R', 'E', ' ' */
369} prelink_info_t __attribute__((packed));
370
371static inline void set_prelink(long *prelink_addr,
372                               prelink_info_t *info)
373{
374    // We will assume the binary is little-endian, and test the
375    // host endianness here.
376    unsigned long test_endianness = 0xFF;
377
378    if (sizeof(prelink_info_t) == 8 && prelink_addr) {
379        if (*(unsigned char *)&test_endianness)
380            *prelink_addr = info->mmap_addr;
381        else
382            *prelink_addr = bswap_32(info->mmap_addr);
383    }
384}
385
386static int check_prelinked(const char *fname,
387                           long *prelink_addr)
388{
389    *prelink_addr = 0;
390    if (sizeof(prelink_info_t) != 8) return 0;
391
392    int fd = open(fname, O_RDONLY);
393    if (fd < 0) return 0;
394    off_t end = lseek(fd, 0, SEEK_END);
395    int nr = sizeof(prelink_info_t);
396
397    off_t sz = lseek(fd, -nr, SEEK_CUR);
398    if ((long)(end - sz) != (long)nr) return 0;
399    if (sz == (off_t)-1) return 0;
400
401    prelink_info_t info;
402    int num_read = read(fd, &info, nr);
403    if (num_read < 0) return 0;
404    if (num_read != sizeof(info)) return 0;
405
406    int prelinked = 0;
407    if (!strncmp(info.tag, "PRE ", 4)) {
408        set_prelink(prelink_addr, &info);
409        prelinked = 1;
410    }
411    if (close(fd) < 0) return 0;
412    return prelinked;
413}
414
415void dump_randomization_base(int tfd, bool at_fault) {
416    bool only_in_tombstone = !at_fault;
417    long prelink_addr;
418    check_prelinked("/system/lib/libc.so", &prelink_addr);
419    _LOG(tfd, only_in_tombstone,
420         "\nlibc base address: %08x\n", prelink_addr);
421}
422
423/* End of ASLR-related logic. */
424
425static void parse_elf_info(mapinfo *milist, pid_t pid)
426{
427    mapinfo *mi;
428    for (mi = milist; mi != NULL; mi = mi->next) {
429        Elf32_Ehdr ehdr;
430
431        memset(&ehdr, 0, sizeof(Elf32_Ehdr));
432        /* Read in sizeof(Elf32_Ehdr) worth of data from the beginning of
433         * mapped section.
434         */
435        get_remote_struct(pid, (void *) (mi->start), &ehdr,
436                          sizeof(Elf32_Ehdr));
437        /* Check if it has the matching magic words */
438        if (IS_ELF(ehdr)) {
439            Elf32_Phdr phdr;
440            Elf32_Phdr *ptr;
441            int i;
442
443            ptr = (Elf32_Phdr *) (mi->start + ehdr.e_phoff);
444            for (i = 0; i < ehdr.e_phnum; i++) {
445                /* Parse the program header */
446                get_remote_struct(pid, (char *) (ptr+i), &phdr,
447                                  sizeof(Elf32_Phdr));
448                /* Found a EXIDX segment? */
449                if (phdr.p_type == PT_ARM_EXIDX) {
450                    mi->exidx_start = mi->start + phdr.p_offset;
451                    mi->exidx_end = mi->exidx_start + phdr.p_filesz;
452                    break;
453                }
454            }
455
456            /* Try to load symbols from this file */
457            mi->symbols = symbol_table_create(mi->name);
458        }
459    }
460}
461
462void dump_crash_report(int tfd, unsigned pid, unsigned tid, bool at_fault)
463{
464    char data[1024];
465    FILE *fp;
466    mapinfo *milist = 0;
467    unsigned int sp_list[STACK_CONTENT_DEPTH];
468    int stack_depth;
469    int frame0_pc_sane = 1;
470
471    if (!at_fault) {
472        _LOG(tfd, true,
473         "--- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---\n");
474        _LOG(tfd, true, "pid: %d, tid: %d\n", pid, tid);
475    }
476
477    dump_registers(tfd, tid, at_fault);
478
479    /* Clear stack pointer records */
480    memset(sp_list, 0, sizeof(sp_list));
481
482    sprintf(data, "/proc/%d/maps", pid);
483    fp = fopen(data, "r");
484    if(fp) {
485        while(fgets(data, 1024, fp)) {
486            mapinfo *mi = parse_maps_line(data);
487            if(mi) {
488                mi->next = milist;
489                milist = mi;
490            }
491        }
492        fclose(fp);
493    }
494
495    parse_elf_info(milist, tid);
496
497    /* If stack unwinder fails, use the default solution to dump the stack
498     * content.
499     */
500    stack_depth = unwind_backtrace_with_ptrace(tfd, tid, milist, sp_list,
501                                               &frame0_pc_sane, at_fault);
502
503    /* The stack unwinder should at least unwind two levels of stack. If less
504     * level is seen we make sure at lease pc and lr are dumped.
505     */
506    if (stack_depth < 2) {
507        dump_pc_and_lr(tfd, tid, milist, stack_depth, at_fault);
508    }
509
510    dump_randomization_base(tfd, at_fault);
511    dump_stack_and_code(tfd, tid, milist, stack_depth, sp_list, at_fault);
512
513    while(milist) {
514        mapinfo *next = milist->next;
515        symbol_table_free(milist->symbols);
516        free(milist);
517        milist = next;
518    }
519}
520
521#define MAX_TOMBSTONES	10
522
523#define typecheck(x,y) {    \
524    typeof(x) __dummy1;     \
525    typeof(y) __dummy2;     \
526    (void)(&__dummy1 == &__dummy2); }
527
528#define TOMBSTONE_DIR	"/data/tombstones"
529
530/*
531 * find_and_open_tombstone - find an available tombstone slot, if any, of the
532 * form tombstone_XX where XX is 00 to MAX_TOMBSTONES-1, inclusive. If no
533 * file is available, we reuse the least-recently-modified file.
534 */
535static int find_and_open_tombstone(void)
536{
537    unsigned long mtime = ULONG_MAX;
538    struct stat sb;
539    char path[128];
540    int fd, i, oldest = 0;
541
542    /*
543     * XXX: Our stat.st_mtime isn't time_t. If it changes, as it probably ought
544     * to, our logic breaks. This check will generate a warning if that happens.
545     */
546    typecheck(mtime, sb.st_mtime);
547
548    /*
549     * In a single wolf-like pass, find an available slot and, in case none
550     * exist, find and record the least-recently-modified file.
551     */
552    for (i = 0; i < MAX_TOMBSTONES; i++) {
553        snprintf(path, sizeof(path), TOMBSTONE_DIR"/tombstone_%02d", i);
554
555        if (!stat(path, &sb)) {
556            if (sb.st_mtime < mtime) {
557                oldest = i;
558                mtime = sb.st_mtime;
559            }
560            continue;
561        }
562        if (errno != ENOENT)
563            continue;
564
565        fd = open(path, O_CREAT | O_EXCL | O_WRONLY, 0600);
566        if (fd < 0)
567            continue;	/* raced ? */
568
569        fchown(fd, AID_SYSTEM, AID_SYSTEM);
570        return fd;
571    }
572
573    /* we didn't find an available file, so we clobber the oldest one */
574    snprintf(path, sizeof(path), TOMBSTONE_DIR"/tombstone_%02d", oldest);
575    fd = open(path, O_CREAT | O_TRUNC | O_WRONLY, 0600);
576    fchown(fd, AID_SYSTEM, AID_SYSTEM);
577
578    return fd;
579}
580
581/* Return true if some thread is not detached cleanly */
582static bool dump_sibling_thread_report(int tfd, unsigned pid, unsigned tid)
583{
584    char task_path[1024];
585
586    sprintf(task_path, "/proc/%d/task", pid);
587    DIR *d;
588    struct dirent *de;
589    int need_cleanup = 0;
590
591    d = opendir(task_path);
592    /* Bail early if cannot open the task directory */
593    if (d == NULL) {
594        XLOG("Cannot open /proc/%d/task\n", pid);
595        return false;
596    }
597    while ((de = readdir(d)) != NULL) {
598        unsigned new_tid;
599        /* Ignore "." and ".." */
600        if (!strcmp(de->d_name, ".") || !strcmp(de->d_name, ".."))
601            continue;
602        new_tid = atoi(de->d_name);
603        /* The main thread at fault has been handled individually */
604        if (new_tid == tid)
605            continue;
606
607        /* Skip this thread if cannot ptrace it */
608        if (ptrace(PTRACE_ATTACH, new_tid, 0, 0) < 0)
609            continue;
610
611        dump_crash_report(tfd, pid, new_tid, false);
612        need_cleanup |= ptrace(PTRACE_DETACH, new_tid, 0, 0);
613    }
614    closedir(d);
615    return need_cleanup != 0;
616}
617
618/* Return true if some thread is not detached cleanly */
619static bool engrave_tombstone(unsigned pid, unsigned tid, int debug_uid,
620                              int signal)
621{
622    int fd;
623    bool need_cleanup = false;
624
625    mkdir(TOMBSTONE_DIR, 0755);
626    chown(TOMBSTONE_DIR, AID_SYSTEM, AID_SYSTEM);
627
628    fd = find_and_open_tombstone();
629    if (fd < 0)
630        return need_cleanup;
631
632    dump_crash_banner(fd, pid, tid, signal);
633    dump_crash_report(fd, pid, tid, true);
634    /*
635     * If the user has requested to attach gdb, don't collect the per-thread
636     * information as it increases the chance to lose track of the process.
637     */
638    if ((signed)pid > debug_uid) {
639        need_cleanup = dump_sibling_thread_report(fd, pid, tid);
640    }
641
642    close(fd);
643    return need_cleanup;
644}
645
646static int
647write_string(const char* file, const char* string)
648{
649    int len;
650    int fd;
651    ssize_t amt;
652    fd = open(file, O_RDWR);
653    len = strlen(string);
654    if (fd < 0)
655        return -errno;
656    amt = write(fd, string, len);
657    close(fd);
658    return amt >= 0 ? 0 : -errno;
659}
660
661static
662void init_debug_led(void)
663{
664    // trout leds
665    write_string("/sys/class/leds/red/brightness", "0");
666    write_string("/sys/class/leds/green/brightness", "0");
667    write_string("/sys/class/leds/blue/brightness", "0");
668    write_string("/sys/class/leds/red/device/blink", "0");
669    // sardine leds
670    write_string("/sys/class/leds/left/cadence", "0,0");
671}
672
673static
674void enable_debug_led(void)
675{
676    // trout leds
677    write_string("/sys/class/leds/red/brightness", "255");
678    // sardine leds
679    write_string("/sys/class/leds/left/cadence", "1,0");
680}
681
682static
683void disable_debug_led(void)
684{
685    // trout leds
686    write_string("/sys/class/leds/red/brightness", "0");
687    // sardine leds
688    write_string("/sys/class/leds/left/cadence", "0,0");
689}
690
691extern int init_getevent();
692extern void uninit_getevent();
693extern int get_event(struct input_event* event, int timeout);
694
695static void wait_for_user_action(unsigned tid, struct ucred* cr)
696{
697    (void)tid;
698    /* First log a helpful message */
699    LOG(    "********************************************************\n"
700            "* Process %d has been suspended while crashing.  To\n"
701            "* attach gdbserver for a gdb connection on port 5039:\n"
702            "*\n"
703            "*     adb shell gdbserver :5039 --attach %d &\n"
704            "*\n"
705            "* Press HOME key to let the process continue crashing.\n"
706            "********************************************************\n",
707            cr->pid, cr->pid);
708
709    /* wait for HOME key (TODO: something useful for devices w/o HOME key) */
710    if (init_getevent() == 0) {
711        int ms = 1200 / 10;
712        int dit = 1;
713        int dah = 3*dit;
714        int _       = -dit;
715        int ___     = 3*_;
716        int _______ = 7*_;
717        const signed char codes[] = {
718           dit,_,dit,_,dit,___,dah,_,dah,_,dah,___,dit,_,dit,_,dit,_______
719        };
720        size_t s = 0;
721        struct input_event e;
722        int home = 0;
723        init_debug_led();
724        enable_debug_led();
725        do {
726            int timeout = abs((int)(codes[s])) * ms;
727            int res = get_event(&e, timeout);
728            if (res == 0) {
729                if (e.type==EV_KEY && e.code==KEY_HOME && e.value==0)
730                    home = 1;
731            } else if (res == 1) {
732                if (++s >= sizeof(codes)/sizeof(*codes))
733                    s = 0;
734                if (codes[s] > 0) {
735                    enable_debug_led();
736                } else {
737                    disable_debug_led();
738                }
739            }
740        } while (!home);
741        uninit_getevent();
742    }
743
744    /* don't forget to turn debug led off */
745    disable_debug_led();
746
747    /* close filedescriptor */
748    LOG("debuggerd resuming process %d", cr->pid);
749 }
750
751static void handle_crashing_process(int fd)
752{
753    char buf[64];
754    struct stat s;
755    unsigned tid;
756    struct ucred cr;
757    int n, len, status;
758    int tid_attach_status = -1;
759    unsigned retry = 30;
760    bool need_cleanup = false;
761
762    char value[PROPERTY_VALUE_MAX];
763    property_get("debug.db.uid", value, "-1");
764    int debug_uid = atoi(value);
765
766    XLOG("handle_crashing_process(%d)\n", fd);
767
768    len = sizeof(cr);
769    n = getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &cr, &len);
770    if(n != 0) {
771        LOG("cannot get credentials\n");
772        goto done;
773    }
774
775    XLOG("reading tid\n");
776    fcntl(fd, F_SETFL, O_NONBLOCK);
777    while((n = read(fd, &tid, sizeof(unsigned))) != sizeof(unsigned)) {
778        if(errno == EINTR) continue;
779        if(errno == EWOULDBLOCK) {
780            if(retry-- > 0) {
781                usleep(100 * 1000);
782                continue;
783            }
784            LOG("timed out reading tid\n");
785            goto done;
786        }
787        LOG("read failure? %s\n", strerror(errno));
788        goto done;
789    }
790
791    sprintf(buf,"/proc/%d/task/%d", cr.pid, tid);
792    if(stat(buf, &s)) {
793        LOG("tid %d does not exist in pid %d. ignoring debug request\n",
794            tid, cr.pid);
795        close(fd);
796        return;
797    }
798
799    XLOG("BOOM: pid=%d uid=%d gid=%d tid=%d\n", cr.pid, cr.uid, cr.gid, tid);
800
801    tid_attach_status = ptrace(PTRACE_ATTACH, tid, 0, 0);
802    if(tid_attach_status < 0) {
803        LOG("ptrace attach failed: %s\n", strerror(errno));
804        goto done;
805    }
806
807    close(fd);
808    fd = -1;
809
810    for(;;) {
811        n = waitpid(tid, &status, __WALL);
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    /* resume stopped process (so it can crash in peace) */
884    kill(cr.pid, SIGCONT);
885
886    if (need_cleanup) {
887        LOG("debuggerd committing suicide to free the zombie!\n");
888        kill(getpid(), SIGKILL);
889    }
890
891    if(fd != -1) close(fd);
892}
893
894int main()
895{
896    int s;
897    struct sigaction act;
898
899    logsocket = socket_local_client("logd",
900            ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_DGRAM);
901    if(logsocket < 0) {
902        logsocket = -1;
903    } else {
904        fcntl(logsocket, F_SETFD, FD_CLOEXEC);
905    }
906
907    act.sa_handler = SIG_DFL;
908    sigemptyset(&act.sa_mask);
909    sigaddset(&act.sa_mask,SIGCHLD);
910    act.sa_flags = SA_NOCLDWAIT;
911    sigaction(SIGCHLD, &act, 0);
912
913    s = socket_local_server("android:debuggerd",
914            ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
915    if(s < 0) return -1;
916    fcntl(s, F_SETFD, FD_CLOEXEC);
917
918    LOG("debuggerd: " __DATE__ " " __TIME__ "\n");
919
920    for(;;) {
921        struct sockaddr addr;
922        socklen_t alen;
923        int fd;
924
925        alen = sizeof(addr);
926        fd = accept(s, &addr, &alen);
927        if(fd < 0) continue;
928
929        fcntl(fd, F_SETFD, FD_CLOEXEC);
930
931        handle_crashing_process(fd);
932    }
933    return 0;
934}
935