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