1/*
2 * Copyright 2006, 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 <arpa/inet.h>
18#include <dirent.h>
19#include <elf.h>
20#include <errno.h>
21#include <fcntl.h>
22#include <pthread.h>
23#include <signal.h>
24#include <stdarg.h>
25#include <stdio.h>
26#include <sys/poll.h>
27#include <sys/prctl.h>
28#include <sys/ptrace.h>
29#include <sys/socket.h>
30#include <sys/stat.h>
31#include <sys/types.h>
32#include <sys/wait.h>
33#include <sys/un.h>
34#include <time.h>
35
36#include <memory>
37#include <set>
38#include <string>
39
40#include <selinux/android.h>
41
42#include <log/logger.h>
43
44#include <android-base/file.h>
45#include <android-base/unique_fd.h>
46#include <cutils/debugger.h>
47#include <cutils/properties.h>
48#include <cutils/sockets.h>
49#include <nativehelper/ScopedFd.h>
50
51#include <linux/input.h>
52
53#include <private/android_filesystem_config.h>
54
55#include "backtrace.h"
56#include "getevent.h"
57#include "signal_sender.h"
58#include "tombstone.h"
59#include "utility.h"
60
61// If the 32 bit executable is compiled on a 64 bit system,
62// use the 32 bit socket name.
63#if defined(TARGET_IS_64_BIT) && !defined(__LP64__)
64#define SOCKET_NAME DEBUGGER32_SOCKET_NAME
65#else
66#define SOCKET_NAME DEBUGGER_SOCKET_NAME
67#endif
68
69struct debugger_request_t {
70  debugger_action_t action;
71  pid_t pid, tid;
72  uid_t uid, gid;
73  uintptr_t abort_msg_address;
74  int32_t original_si_code;
75};
76
77static void wait_for_user_action(const debugger_request_t& request) {
78  // Explain how to attach the debugger.
79  ALOGI("***********************************************************\n"
80        "* Process %d has been suspended while crashing.\n"
81        "* To attach gdbserver and start gdb, run this on the host:\n"
82        "*\n"
83        "*     gdbclient.py -p %d\n"
84        "*\n"
85        "* Wait for gdb to start, then press the VOLUME DOWN key\n"
86        "* to let the process continue crashing.\n"
87        "***********************************************************",
88        request.pid, request.tid);
89
90  // Wait for VOLUME DOWN.
91  while (true) {
92    input_event e;
93    if (get_event(&e, -1) == 0) {
94      if (e.type == EV_KEY && e.code == KEY_VOLUMEDOWN && e.value == 0) {
95        break;
96      }
97    }
98  }
99
100  ALOGI("debuggerd resuming process %d", request.pid);
101}
102
103static int get_process_info(pid_t tid, pid_t* out_pid, uid_t* out_uid, uid_t* out_gid) {
104  char path[64];
105  snprintf(path, sizeof(path), "/proc/%d/status", tid);
106
107  FILE* fp = fopen(path, "r");
108  if (!fp) {
109    return -1;
110  }
111
112  int fields = 0;
113  char line[1024];
114  while (fgets(line, sizeof(line), fp)) {
115    size_t len = strlen(line);
116    if (len > 6 && !memcmp(line, "Tgid:\t", 6)) {
117      *out_pid = atoi(line + 6);
118      fields |= 1;
119    } else if (len > 5 && !memcmp(line, "Uid:\t", 5)) {
120      *out_uid = atoi(line + 5);
121      fields |= 2;
122    } else if (len > 5 && !memcmp(line, "Gid:\t", 5)) {
123      *out_gid = atoi(line + 5);
124      fields |= 4;
125    }
126  }
127  fclose(fp);
128  return fields == 7 ? 0 : -1;
129}
130
131/*
132 * Corresponds with debugger_action_t enum type in
133 * include/cutils/debugger.h.
134 */
135static const char *debuggerd_perms[] = {
136  NULL, /* crash is only used on self, no check applied */
137  "dump_tombstone",
138  "dump_backtrace"
139};
140
141static int audit_callback(void* data, security_class_t /* cls */, char* buf, size_t len)
142{
143    struct debugger_request_t* req = reinterpret_cast<debugger_request_t*>(data);
144
145    if (!req) {
146        ALOGE("No debuggerd request audit data");
147        return 0;
148    }
149
150    snprintf(buf, len, "pid=%d uid=%d gid=%d", req->pid, req->uid, req->gid);
151    return 0;
152}
153
154static bool selinux_action_allowed(int s, debugger_request_t* request)
155{
156  char *scon = NULL, *tcon = NULL;
157  const char *tclass = "debuggerd";
158  const char *perm;
159  bool allowed = false;
160
161  if (request->action <= 0 || request->action >= (sizeof(debuggerd_perms)/sizeof(debuggerd_perms[0]))) {
162    ALOGE("SELinux:  No permission defined for debugger action %d", request->action);
163    return false;
164  }
165
166  perm = debuggerd_perms[request->action];
167
168  if (getpeercon(s, &scon) < 0) {
169    ALOGE("Cannot get peer context from socket\n");
170    goto out;
171  }
172
173  if (getpidcon(request->tid, &tcon) < 0) {
174    ALOGE("Cannot get context for tid %d\n", request->tid);
175    goto out;
176  }
177
178  allowed = (selinux_check_access(scon, tcon, tclass, perm, reinterpret_cast<void*>(request)) == 0);
179
180out:
181   freecon(scon);
182   freecon(tcon);
183   return allowed;
184}
185
186static int read_request(int fd, debugger_request_t* out_request) {
187  ucred cr;
188  socklen_t len = sizeof(cr);
189  int status = getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &cr, &len);
190  if (status != 0) {
191    ALOGE("cannot get credentials");
192    return -1;
193  }
194
195  ALOGV("reading tid");
196  fcntl(fd, F_SETFL, O_NONBLOCK);
197
198  pollfd pollfds[1];
199  pollfds[0].fd = fd;
200  pollfds[0].events = POLLIN;
201  pollfds[0].revents = 0;
202  status = TEMP_FAILURE_RETRY(poll(pollfds, 1, 3000));
203  if (status != 1) {
204    ALOGE("timed out reading tid (from pid=%d uid=%d)\n", cr.pid, cr.uid);
205    return -1;
206  }
207
208  debugger_msg_t msg;
209  memset(&msg, 0, sizeof(msg));
210  status = TEMP_FAILURE_RETRY(read(fd, &msg, sizeof(msg)));
211  if (status < 0) {
212    ALOGE("read failure? %s (pid=%d uid=%d)\n", strerror(errno), cr.pid, cr.uid);
213    return -1;
214  }
215  if (status != sizeof(debugger_msg_t)) {
216    ALOGE("invalid crash request of size %d (from pid=%d uid=%d)\n", status, cr.pid, cr.uid);
217    return -1;
218  }
219
220  out_request->action = static_cast<debugger_action_t>(msg.action);
221  out_request->tid = msg.tid;
222  out_request->pid = cr.pid;
223  out_request->uid = cr.uid;
224  out_request->gid = cr.gid;
225  out_request->abort_msg_address = msg.abort_msg_address;
226  out_request->original_si_code = msg.original_si_code;
227
228  if (msg.action == DEBUGGER_ACTION_CRASH) {
229    // Ensure that the tid reported by the crashing process is valid.
230    char buf[64];
231    struct stat s;
232    snprintf(buf, sizeof buf, "/proc/%d/task/%d", out_request->pid, out_request->tid);
233    if (stat(buf, &s)) {
234      ALOGE("tid %d does not exist in pid %d. ignoring debug request\n",
235          out_request->tid, out_request->pid);
236      return -1;
237    }
238  } else if (cr.uid == 0
239            || (cr.uid == AID_SYSTEM && msg.action == DEBUGGER_ACTION_DUMP_BACKTRACE)) {
240    // Only root or system can ask us to attach to any process and dump it explicitly.
241    // However, system is only allowed to collect backtraces but cannot dump tombstones.
242    status = get_process_info(out_request->tid, &out_request->pid,
243                              &out_request->uid, &out_request->gid);
244    if (status < 0) {
245      ALOGE("tid %d does not exist. ignoring explicit dump request\n", out_request->tid);
246      return -1;
247    }
248
249    if (!selinux_action_allowed(fd, out_request))
250      return -1;
251  } else {
252    // No one else is allowed to dump arbitrary processes.
253    return -1;
254  }
255  return 0;
256}
257
258static int activity_manager_connect() {
259  android::base::unique_fd amfd(socket(PF_UNIX, SOCK_STREAM, 0));
260  if (amfd.get() < -1) {
261    ALOGE("debuggerd: Unable to connect to activity manager (socket failed: %s)", strerror(errno));
262    return -1;
263  }
264
265  struct sockaddr_un address;
266  memset(&address, 0, sizeof(address));
267  address.sun_family = AF_UNIX;
268  // The path used here must match the value defined in NativeCrashListener.java.
269  strncpy(address.sun_path, "/data/system/ndebugsocket", sizeof(address.sun_path));
270  if (TEMP_FAILURE_RETRY(connect(amfd.get(), reinterpret_cast<struct sockaddr*>(&address),
271                                 sizeof(address))) == -1) {
272    ALOGE("debuggerd: Unable to connect to activity manager (connect failed: %s)", strerror(errno));
273    return -1;
274  }
275
276  struct timeval tv;
277  memset(&tv, 0, sizeof(tv));
278  tv.tv_sec = 1;  // tight leash
279  if (setsockopt(amfd.get(), SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)) == -1) {
280    ALOGE("debuggerd: Unable to connect to activity manager (setsockopt SO_SNDTIMEO failed: %s)",
281          strerror(errno));
282    return -1;
283  }
284
285  tv.tv_sec = 3;  // 3 seconds on handshake read
286  if (setsockopt(amfd.get(), SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) == -1) {
287    ALOGE("debuggerd: Unable to connect to activity manager (setsockopt SO_RCVTIMEO failed: %s)",
288          strerror(errno));
289    return -1;
290  }
291
292  return amfd.release();
293}
294
295static void activity_manager_write(int pid, int signal, int amfd, const std::string& amfd_data) {
296  if (amfd == -1) {
297    return;
298  }
299
300  // Activity Manager protocol: binary 32-bit network-byte-order ints for the
301  // pid and signal number, followed by the raw text of the dump, culminating
302  // in a zero byte that marks end-of-data.
303  uint32_t datum = htonl(pid);
304  if (!android::base::WriteFully(amfd, &datum, 4)) {
305    ALOGE("AM pid write failed: %s\n", strerror(errno));
306    return;
307  }
308  datum = htonl(signal);
309  if (!android::base::WriteFully(amfd, &datum, 4)) {
310    ALOGE("AM signal write failed: %s\n", strerror(errno));
311    return;
312  }
313
314  if (!android::base::WriteFully(amfd, amfd_data.c_str(), amfd_data.size())) {
315    ALOGE("AM data write failed: %s\n", strerror(errno));
316    return;
317  }
318
319  // Send EOD to the Activity Manager, then wait for its ack to avoid racing
320  // ahead and killing the target out from under it.
321  uint8_t eodMarker = 0;
322  if (!android::base::WriteFully(amfd, &eodMarker, 1)) {
323    ALOGE("AM eod write failed: %s\n", strerror(errno));
324    return;
325  }
326  // 3 sec timeout reading the ack; we're fine if the read fails.
327  android::base::ReadFully(amfd, &eodMarker, 1);
328}
329
330static bool should_attach_gdb(const debugger_request_t& request) {
331  if (request.action == DEBUGGER_ACTION_CRASH) {
332    return property_get_bool("debug.debuggerd.wait_for_gdb", false);
333  }
334  return false;
335}
336
337#if defined(__LP64__)
338static bool is32bit(pid_t tid) {
339  char* exeline;
340  if (asprintf(&exeline, "/proc/%d/exe", tid) == -1) {
341    return false;
342  }
343  int fd = TEMP_FAILURE_RETRY(open(exeline, O_RDONLY | O_CLOEXEC));
344  int saved_errno = errno;
345  free(exeline);
346  if (fd == -1) {
347    ALOGW("Failed to open /proc/%d/exe %s", tid, strerror(saved_errno));
348    return false;
349  }
350
351  char ehdr[EI_NIDENT];
352  ssize_t bytes = TEMP_FAILURE_RETRY(read(fd, &ehdr, sizeof(ehdr)));
353  close(fd);
354  if (bytes != (ssize_t) sizeof(ehdr) || memcmp(ELFMAG, ehdr, SELFMAG) != 0) {
355    return false;
356  }
357  if (ehdr[EI_CLASS] == ELFCLASS32) {
358    return true;
359  }
360  return false;
361}
362
363static void redirect_to_32(int fd, debugger_request_t* request) {
364  debugger_msg_t msg;
365  memset(&msg, 0, sizeof(msg));
366  msg.tid = request->tid;
367  msg.action = request->action;
368
369  int sock_fd = socket_local_client(DEBUGGER32_SOCKET_NAME, ANDROID_SOCKET_NAMESPACE_ABSTRACT,
370                                    SOCK_STREAM | SOCK_CLOEXEC);
371  if (sock_fd < 0) {
372    ALOGE("Failed to connect to debuggerd32: %s", strerror(errno));
373    return;
374  }
375
376  if (TEMP_FAILURE_RETRY(write(sock_fd, &msg, sizeof(msg))) != (ssize_t) sizeof(msg)) {
377    ALOGE("Failed to write request to debuggerd32 socket: %s", strerror(errno));
378    close(sock_fd);
379    return;
380  }
381
382  char ack;
383  if (TEMP_FAILURE_RETRY(read(sock_fd, &ack, 1)) == -1) {
384    ALOGE("Failed to read ack from debuggerd32 socket: %s", strerror(errno));
385    close(sock_fd);
386    return;
387  }
388
389  char buffer[1024];
390  ssize_t bytes_read;
391  while ((bytes_read = TEMP_FAILURE_RETRY(read(sock_fd, buffer, sizeof(buffer)))) > 0) {
392    ssize_t bytes_to_send = bytes_read;
393    ssize_t bytes_written;
394    do {
395      bytes_written = TEMP_FAILURE_RETRY(write(fd, buffer + bytes_read - bytes_to_send,
396                                               bytes_to_send));
397      if (bytes_written == -1) {
398        if (errno == EAGAIN) {
399          // Retry the write.
400          continue;
401        }
402        ALOGE("Error while writing data to fd: %s", strerror(errno));
403        break;
404      }
405      bytes_to_send -= bytes_written;
406    } while (bytes_written != 0 && bytes_to_send > 0);
407    if (bytes_to_send != 0) {
408        ALOGE("Failed to write all data to fd: read %zd, sent %zd", bytes_read, bytes_to_send);
409        break;
410    }
411  }
412  close(sock_fd);
413}
414#endif
415
416static void ptrace_siblings(pid_t pid, pid_t main_tid, std::set<pid_t>& tids) {
417  char task_path[64];
418
419  snprintf(task_path, sizeof(task_path), "/proc/%d/task", pid);
420
421  std::unique_ptr<DIR, int (*)(DIR*)> d(opendir(task_path), closedir);
422
423  // Bail early if the task directory cannot be opened.
424  if (!d) {
425    ALOGE("debuggerd: failed to open /proc/%d/task: %s", pid, strerror(errno));
426    return;
427  }
428
429  struct dirent* de;
430  while ((de = readdir(d.get())) != NULL) {
431    // Ignore "." and "..".
432    if (!strcmp(de->d_name, ".") || !strcmp(de->d_name, "..")) {
433      continue;
434    }
435
436    char* end;
437    pid_t tid = strtoul(de->d_name, &end, 10);
438    if (*end) {
439      continue;
440    }
441
442    if (tid == main_tid) {
443      continue;
444    }
445
446    if (ptrace(PTRACE_ATTACH, tid, 0, 0) < 0) {
447      ALOGE("debuggerd: ptrace attach to %d failed: %s", tid, strerror(errno));
448      continue;
449    }
450
451    tids.insert(tid);
452  }
453}
454
455static bool perform_dump(const debugger_request_t& request, int fd, int tombstone_fd,
456                         BacktraceMap* backtrace_map, const std::set<pid_t>& siblings,
457                         int* crash_signal, std::string* amfd_data) {
458  if (TEMP_FAILURE_RETRY(write(fd, "\0", 1)) != 1) {
459    ALOGE("debuggerd: failed to respond to client: %s\n", strerror(errno));
460    return false;
461  }
462
463  int total_sleep_time_usec = 0;
464  while (true) {
465    int signal = wait_for_signal(request.tid, &total_sleep_time_usec);
466    switch (signal) {
467      case -1:
468        ALOGE("debuggerd: timed out waiting for signal");
469        return false;
470
471      case SIGSTOP:
472        if (request.action == DEBUGGER_ACTION_DUMP_TOMBSTONE) {
473          ALOGV("debuggerd: stopped -- dumping to tombstone");
474          engrave_tombstone(tombstone_fd, backtrace_map, request.pid, request.tid, siblings, signal,
475                            request.original_si_code, request.abort_msg_address, amfd_data);
476        } else if (request.action == DEBUGGER_ACTION_DUMP_BACKTRACE) {
477          ALOGV("debuggerd: stopped -- dumping to fd");
478          dump_backtrace(fd, backtrace_map, request.pid, request.tid, siblings, nullptr);
479        } else {
480          ALOGV("debuggerd: stopped -- continuing");
481          if (ptrace(PTRACE_CONT, request.tid, 0, 0) != 0) {
482            ALOGE("debuggerd: ptrace continue failed: %s", strerror(errno));
483            return false;
484          }
485          continue;  // loop again
486        }
487        break;
488
489      case SIGABRT:
490      case SIGBUS:
491      case SIGFPE:
492      case SIGILL:
493      case SIGSEGV:
494#ifdef SIGSTKFLT
495      case SIGSTKFLT:
496#endif
497      case SIGSYS:
498      case SIGTRAP:
499        ALOGV("stopped -- fatal signal\n");
500        *crash_signal = signal;
501        engrave_tombstone(tombstone_fd, backtrace_map, request.pid, request.tid, siblings, signal,
502                          request.original_si_code, request.abort_msg_address, amfd_data);
503        break;
504
505      default:
506        ALOGE("debuggerd: process stopped due to unexpected signal %d\n", signal);
507        break;
508    }
509    break;
510  }
511
512  return true;
513}
514
515static bool drop_privileges() {
516  // AID_LOG: for reading the logs data associated with the crashing process.
517  // AID_READPROC: for reading /proc/<PID>/{comm,cmdline}.
518  gid_t groups[] = { AID_DEBUGGERD, AID_LOG, AID_READPROC };
519  if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) {
520    ALOGE("debuggerd: failed to setgroups: %s", strerror(errno));
521    return false;
522  }
523
524  if (setresgid(AID_DEBUGGERD, AID_DEBUGGERD, AID_DEBUGGERD) != 0) {
525    ALOGE("debuggerd: failed to setresgid: %s", strerror(errno));
526    return false;
527  }
528
529  if (setresuid(AID_DEBUGGERD, AID_DEBUGGERD, AID_DEBUGGERD) != 0) {
530    ALOGE("debuggerd: failed to setresuid: %s", strerror(errno));
531    return false;
532  }
533
534  return true;
535}
536
537static void worker_process(int fd, debugger_request_t& request) {
538  // Open the tombstone file if we need it.
539  std::string tombstone_path;
540  int tombstone_fd = -1;
541  switch (request.action) {
542    case DEBUGGER_ACTION_DUMP_TOMBSTONE:
543    case DEBUGGER_ACTION_CRASH:
544      tombstone_fd = open_tombstone(&tombstone_path);
545      if (tombstone_fd == -1) {
546        ALOGE("debuggerd: failed to open tombstone file: %s\n", strerror(errno));
547        exit(1);
548      }
549      break;
550
551    case DEBUGGER_ACTION_DUMP_BACKTRACE:
552      break;
553
554    default:
555      ALOGE("debuggerd: unexpected request action: %d", request.action);
556      exit(1);
557  }
558
559  // At this point, the thread that made the request is blocked in
560  // a read() call.  If the thread has crashed, then this gives us
561  // time to PTRACE_ATTACH to it before it has a chance to really fault.
562  //
563  // The PTRACE_ATTACH sends a SIGSTOP to the target process, but it
564  // won't necessarily have stopped by the time ptrace() returns.  (We
565  // currently assume it does.)  We write to the file descriptor to
566  // ensure that it can run as soon as we call PTRACE_CONT below.
567  // See details in bionic/libc/linker/debugger.c, in function
568  // debugger_signal_handler().
569
570  // Attach to the target process.
571  if (ptrace(PTRACE_ATTACH, request.tid, 0, 0) != 0) {
572    ALOGE("debuggerd: ptrace attach failed: %s", strerror(errno));
573    exit(1);
574  }
575
576  // Don't attach to the sibling threads if we want to attach gdb.
577  // Supposedly, it makes the process less reliable.
578  bool attach_gdb = should_attach_gdb(request);
579  if (attach_gdb) {
580    // Open all of the input devices we need to listen for VOLUMEDOWN before dropping privileges.
581    if (init_getevent() != 0) {
582      ALOGE("debuggerd: failed to initialize input device, not waiting for gdb");
583      attach_gdb = false;
584    }
585
586  }
587
588  std::set<pid_t> siblings;
589  if (!attach_gdb) {
590    ptrace_siblings(request.pid, request.tid, siblings);
591  }
592
593  // Generate the backtrace map before dropping privileges.
594  std::unique_ptr<BacktraceMap> backtrace_map(BacktraceMap::Create(request.pid));
595
596  int amfd = -1;
597  std::unique_ptr<std::string> amfd_data;
598  if (request.action == DEBUGGER_ACTION_CRASH) {
599    // Connect to the activity manager before dropping privileges.
600    amfd = activity_manager_connect();
601    amfd_data.reset(new std::string);
602  }
603
604  bool succeeded = false;
605
606  // Now that we've done everything that requires privileges, we can drop them.
607  if (!drop_privileges()) {
608    ALOGE("debuggerd: failed to drop privileges, exiting");
609    _exit(1);
610  }
611
612  int crash_signal = SIGKILL;
613  succeeded = perform_dump(request, fd, tombstone_fd, backtrace_map.get(), siblings,
614                           &crash_signal, amfd_data.get());
615  if (succeeded) {
616    if (request.action == DEBUGGER_ACTION_DUMP_TOMBSTONE) {
617      if (!tombstone_path.empty()) {
618        android::base::WriteFully(fd, tombstone_path.c_str(), tombstone_path.length());
619      }
620    }
621  }
622
623  if (attach_gdb) {
624    // Tell the signal process to send SIGSTOP to the target.
625    if (!send_signal(request.pid, 0, SIGSTOP)) {
626      ALOGE("debuggerd: failed to stop process for gdb attach: %s", strerror(errno));
627      attach_gdb = false;
628    }
629  }
630
631  if (!attach_gdb) {
632    // Tell the Activity Manager about the crashing process. If we are
633    // waiting for gdb to attach, do not send this or Activity Manager
634    // might kill the process before anyone can attach.
635    activity_manager_write(request.pid, crash_signal, amfd, *amfd_data.get());
636  }
637
638  if (ptrace(PTRACE_DETACH, request.tid, 0, 0) != 0) {
639    ALOGE("debuggerd: ptrace detach from %d failed: %s", request.tid, strerror(errno));
640  }
641
642  for (pid_t sibling : siblings) {
643    ptrace(PTRACE_DETACH, sibling, 0, 0);
644  }
645
646  // Send the signal back to the process if it crashed and we're not waiting for gdb.
647  if (!attach_gdb && request.action == DEBUGGER_ACTION_CRASH) {
648    if (!send_signal(request.pid, request.tid, crash_signal)) {
649      ALOGE("debuggerd: failed to kill process %d: %s", request.pid, strerror(errno));
650    }
651  }
652
653  // Wait for gdb, if requested.
654  if (attach_gdb) {
655    wait_for_user_action(request);
656
657    // Now tell the activity manager about this process.
658    activity_manager_write(request.pid, crash_signal, amfd, *amfd_data.get());
659
660    // Tell the signal process to send SIGCONT to the target.
661    if (!send_signal(request.pid, 0, SIGCONT)) {
662      ALOGE("debuggerd: failed to resume process %d: %s", request.pid, strerror(errno));
663    }
664
665    uninit_getevent();
666  }
667
668  close(amfd);
669
670  exit(!succeeded);
671}
672
673static void monitor_worker_process(int child_pid, const debugger_request_t& request) {
674  struct timespec timeout = {.tv_sec = 10, .tv_nsec = 0 };
675  if (should_attach_gdb(request)) {
676    // If wait_for_gdb is enabled, set the timeout to something large.
677    timeout.tv_sec = INT_MAX;
678  }
679
680  sigset_t signal_set;
681  sigemptyset(&signal_set);
682  sigaddset(&signal_set, SIGCHLD);
683
684  bool kill_worker = false;
685  bool kill_target = false;
686  bool kill_self = false;
687
688  int status;
689  siginfo_t siginfo;
690  int signal = TEMP_FAILURE_RETRY(sigtimedwait(&signal_set, &siginfo, &timeout));
691  if (signal == SIGCHLD) {
692    pid_t rc = waitpid(-1, &status, WNOHANG | WUNTRACED);
693    if (rc != child_pid) {
694      ALOGE("debuggerd: waitpid returned unexpected pid (%d), committing murder-suicide", rc);
695
696      if (WIFEXITED(status)) {
697        ALOGW("debuggerd: pid %d exited with status %d", rc, WEXITSTATUS(status));
698      } else if (WIFSIGNALED(status)) {
699        ALOGW("debuggerd: pid %d received signal %d", rc, WTERMSIG(status));
700      } else if (WIFSTOPPED(status)) {
701        ALOGW("debuggerd: pid %d stopped by signal %d", rc, WSTOPSIG(status));
702      } else if (WIFCONTINUED(status)) {
703        ALOGW("debuggerd: pid %d continued", rc);
704      }
705
706      kill_worker = true;
707      kill_target = true;
708      kill_self = true;
709    } else if (WIFSIGNALED(status)) {
710      ALOGE("debuggerd: worker process %d terminated due to signal %d", child_pid, WTERMSIG(status));
711      kill_worker = false;
712      kill_target = true;
713    } else if (WIFSTOPPED(status)) {
714      ALOGE("debuggerd: worker process %d stopped due to signal %d", child_pid, WSTOPSIG(status));
715      kill_worker = true;
716      kill_target = true;
717    }
718  } else {
719    ALOGE("debuggerd: worker process %d timed out", child_pid);
720    kill_worker = true;
721    kill_target = true;
722  }
723
724  if (kill_worker) {
725    // Something bad happened, kill the worker.
726    if (kill(child_pid, SIGKILL) != 0) {
727      ALOGE("debuggerd: failed to kill worker process %d: %s", child_pid, strerror(errno));
728    } else {
729      waitpid(child_pid, &status, 0);
730    }
731  }
732
733  int exit_signal = SIGCONT;
734  if (kill_target && request.action == DEBUGGER_ACTION_CRASH) {
735    ALOGE("debuggerd: killing target %d", request.pid);
736    exit_signal = SIGKILL;
737  } else {
738    ALOGW("debuggerd: resuming target %d", request.pid);
739  }
740
741  if (kill(request.pid, exit_signal) != 0) {
742    ALOGE("debuggerd: failed to send signal %d to target: %s", exit_signal, strerror(errno));
743  }
744
745  if (kill_self) {
746    stop_signal_sender();
747    _exit(1);
748  }
749}
750
751static void handle_request(int fd) {
752  ALOGV("handle_request(%d)\n", fd);
753
754  ScopedFd closer(fd);
755  debugger_request_t request;
756  memset(&request, 0, sizeof(request));
757  int status = read_request(fd, &request);
758  if (status != 0) {
759    return;
760  }
761
762  ALOGW("debuggerd: handling request: pid=%d uid=%d gid=%d tid=%d\n", request.pid, request.uid,
763        request.gid, request.tid);
764
765#if defined(__LP64__)
766  // On 64 bit systems, requests to dump 32 bit and 64 bit tids come
767  // to the 64 bit debuggerd. If the process is a 32 bit executable,
768  // redirect the request to the 32 bit debuggerd.
769  if (is32bit(request.tid)) {
770    // Only dump backtrace and dump tombstone requests can be redirected.
771    if (request.action == DEBUGGER_ACTION_DUMP_BACKTRACE ||
772        request.action == DEBUGGER_ACTION_DUMP_TOMBSTONE) {
773      redirect_to_32(fd, &request);
774    } else {
775      ALOGE("debuggerd: Not allowed to redirect action %d to 32 bit debuggerd\n", request.action);
776    }
777    return;
778  }
779#endif
780
781  // Fork a child to handle the rest of the request.
782  pid_t fork_pid = fork();
783  if (fork_pid == -1) {
784    ALOGE("debuggerd: failed to fork: %s\n", strerror(errno));
785  } else if (fork_pid == 0) {
786    worker_process(fd, request);
787  } else {
788    monitor_worker_process(fork_pid, request);
789  }
790}
791
792static int do_server() {
793  // debuggerd crashes can't be reported to debuggerd.
794  // Reset all of the crash handlers.
795  signal(SIGABRT, SIG_DFL);
796  signal(SIGBUS, SIG_DFL);
797  signal(SIGFPE, SIG_DFL);
798  signal(SIGILL, SIG_DFL);
799  signal(SIGSEGV, SIG_DFL);
800#ifdef SIGSTKFLT
801  signal(SIGSTKFLT, SIG_DFL);
802#endif
803  signal(SIGTRAP, SIG_DFL);
804
805  // Ignore failed writes to closed sockets
806  signal(SIGPIPE, SIG_IGN);
807
808  // Block SIGCHLD so we can sigtimedwait for it.
809  sigset_t sigchld;
810  sigemptyset(&sigchld);
811  sigaddset(&sigchld, SIGCHLD);
812  sigprocmask(SIG_SETMASK, &sigchld, nullptr);
813
814  int s = socket_local_server(SOCKET_NAME, ANDROID_SOCKET_NAMESPACE_ABSTRACT,
815                              SOCK_STREAM | SOCK_CLOEXEC);
816  if (s == -1) return 1;
817
818  // Fork a process that stays root, and listens on a pipe to pause and resume the target.
819  if (!start_signal_sender()) {
820    ALOGE("debuggerd: failed to fork signal sender");
821    return 1;
822  }
823
824  ALOGI("debuggerd: starting\n");
825
826  for (;;) {
827    sockaddr_storage ss;
828    sockaddr* addrp = reinterpret_cast<sockaddr*>(&ss);
829    socklen_t alen = sizeof(ss);
830
831    ALOGV("waiting for connection\n");
832    int fd = accept4(s, addrp, &alen, SOCK_CLOEXEC);
833    if (fd == -1) {
834      ALOGE("accept failed: %s\n", strerror(errno));
835      continue;
836    }
837
838    handle_request(fd);
839  }
840  return 0;
841}
842
843static int do_explicit_dump(pid_t tid, bool dump_backtrace) {
844  fprintf(stdout, "Sending request to dump task %d.\n", tid);
845
846  if (dump_backtrace) {
847    fflush(stdout);
848    if (dump_backtrace_to_file(tid, fileno(stdout)) < 0) {
849      fputs("Error dumping backtrace.\n", stderr);
850      return 1;
851    }
852  } else {
853    char tombstone_path[PATH_MAX];
854    if (dump_tombstone(tid, tombstone_path, sizeof(tombstone_path)) < 0) {
855      fputs("Error dumping tombstone.\n", stderr);
856      return 1;
857    }
858    fprintf(stderr, "Tombstone written to: %s\n", tombstone_path);
859  }
860  return 0;
861}
862
863static void usage() {
864  fputs("Usage: -b [<tid>]\n"
865        "  -b dump backtrace to console, otherwise dump full tombstone file\n"
866        "\n"
867        "If tid specified, sends a request to debuggerd to dump that task.\n"
868        "Otherwise, starts the debuggerd server.\n", stderr);
869}
870
871int main(int argc, char** argv) {
872  union selinux_callback cb;
873  if (argc == 1) {
874    cb.func_audit = audit_callback;
875    selinux_set_callback(SELINUX_CB_AUDIT, cb);
876    cb.func_log = selinux_log_callback;
877    selinux_set_callback(SELINUX_CB_LOG, cb);
878    return do_server();
879  }
880
881  bool dump_backtrace = false;
882  bool have_tid = false;
883  pid_t tid = 0;
884  for (int i = 1; i < argc; i++) {
885    if (!strcmp(argv[i], "-b")) {
886      dump_backtrace = true;
887    } else if (!have_tid) {
888      tid = atoi(argv[i]);
889      have_tid = true;
890    } else {
891      usage();
892      return 1;
893    }
894  }
895  if (!have_tid) {
896    usage();
897    return 1;
898  }
899  return do_explicit_dump(tid, dump_backtrace);
900}
901