blob: d4be25bd202a0088fb801b482b365bc92f9d796f [file] [log] [blame]
Josh Gaocbe70cb2016-10-18 18:17:52 -07001/*
2 * Copyright 2016, 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 <fcntl.h>
20#include <stdlib.h>
Josh Gao85bcaf62017-02-01 16:35:31 -080021#include <sys/capability.h>
22#include <sys/prctl.h>
Josh Gaocbe70cb2016-10-18 18:17:52 -070023#include <sys/ptrace.h>
24#include <sys/types.h>
25#include <sys/un.h>
Josh Gao85bcaf62017-02-01 16:35:31 -080026#include <syscall.h>
Josh Gaocbe70cb2016-10-18 18:17:52 -070027#include <unistd.h>
28
29#include <limits>
30#include <memory>
31#include <set>
32#include <vector>
33
34#include <android-base/file.h>
35#include <android-base/logging.h>
36#include <android-base/parseint.h>
37#include <android-base/properties.h>
38#include <android-base/stringprintf.h>
39#include <android-base/unique_fd.h>
40#include <cutils/sockets.h>
Vijay Venkatramana95acea2017-01-23 20:11:51 -080041#include <log/log.h>
Josh Gaocbe70cb2016-10-18 18:17:52 -070042#include <procinfo/process.h>
43#include <selinux/selinux.h>
44
45#include "backtrace.h"
46#include "tombstone.h"
47#include "utility.h"
48
49#include "debuggerd/handler.h"
50#include "debuggerd/protocol.h"
51#include "debuggerd/util.h"
52
53using android::base::unique_fd;
54using android::base::StringPrintf;
55
Josh Gaofe902762017-02-01 16:31:43 -080056static bool pid_contains_tid(int pid_proc_fd, pid_t tid) {
57 struct stat st;
58 std::string task_path = StringPrintf("task/%d", tid);
59 return fstatat(pid_proc_fd, task_path.c_str(), &st, 0) == 0;
Josh Gaocbe70cb2016-10-18 18:17:52 -070060}
61
62// Attach to a thread, and verify that it's still a member of the given process
Josh Gaofe902762017-02-01 16:31:43 -080063static bool ptrace_seize_thread(int pid_proc_fd, pid_t tid, std::string* error) {
Josh Gao122479f2017-01-22 16:42:32 -080064 if (ptrace(PTRACE_SEIZE, tid, 0, 0) != 0) {
Josh Gao42fd74b2017-01-20 12:51:11 -080065 *error = StringPrintf("failed to attach to thread %d: %s", tid, strerror(errno));
Josh Gaocbe70cb2016-10-18 18:17:52 -070066 return false;
67 }
68
69 // Make sure that the task we attached to is actually part of the pid we're dumping.
Josh Gaofe902762017-02-01 16:31:43 -080070 if (!pid_contains_tid(pid_proc_fd, tid)) {
Josh Gaocbe70cb2016-10-18 18:17:52 -070071 if (ptrace(PTRACE_DETACH, tid, 0, 0) != 0) {
72 PLOG(FATAL) << "failed to detach from thread " << tid;
73 }
Josh Gaofe902762017-02-01 16:31:43 -080074 *error = StringPrintf("thread %d is not in process", tid);
Josh Gaocbe70cb2016-10-18 18:17:52 -070075 return false;
76 }
Josh Gao122479f2017-01-22 16:42:32 -080077
78 // Put the task into ptrace-stop state.
79 if (ptrace(PTRACE_INTERRUPT, tid, 0, 0) != 0) {
80 PLOG(FATAL) << "failed to interrupt thread " << tid;
81 }
82
Josh Gaocbe70cb2016-10-18 18:17:52 -070083 return true;
84}
85
86static bool activity_manager_notify(int pid, int signal, const std::string& amfd_data) {
87 android::base::unique_fd amfd(socket_local_client("/data/system/ndebugsocket", ANDROID_SOCKET_NAMESPACE_FILESYSTEM, SOCK_STREAM));
88 if (amfd.get() == -1) {
89 PLOG(ERROR) << "unable to connect to activity manager";
90 return false;
91 }
92
93 struct timeval tv = {
94 .tv_sec = 1,
95 .tv_usec = 0,
96 };
97 if (setsockopt(amfd.get(), SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)) == -1) {
98 PLOG(ERROR) << "failed to set send timeout on activity manager socket";
99 return false;
100 }
101 tv.tv_sec = 3; // 3 seconds on handshake read
102 if (setsockopt(amfd.get(), SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) == -1) {
103 PLOG(ERROR) << "failed to set receive timeout on activity manager socket";
104 return false;
105 }
106
107 // Activity Manager protocol: binary 32-bit network-byte-order ints for the
108 // pid and signal number, followed by the raw text of the dump, culminating
109 // in a zero byte that marks end-of-data.
110 uint32_t datum = htonl(pid);
111 if (!android::base::WriteFully(amfd, &datum, 4)) {
112 PLOG(ERROR) << "AM pid write failed";
113 return false;
114 }
115 datum = htonl(signal);
116 if (!android::base::WriteFully(amfd, &datum, 4)) {
117 PLOG(ERROR) << "AM signal write failed";
118 return false;
119 }
120 if (!android::base::WriteFully(amfd, amfd_data.c_str(), amfd_data.size() + 1)) {
121 PLOG(ERROR) << "AM data write failed";
122 return false;
123 }
124
125 // 3 sec timeout reading the ack; we're fine if the read fails.
126 char ack;
127 android::base::ReadFully(amfd, &ack, 1);
128 return true;
129}
130
131static bool tombstoned_connect(pid_t pid, unique_fd* tombstoned_socket, unique_fd* output_fd) {
132 unique_fd sockfd(socket_local_client(kTombstonedCrashSocketName,
133 ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_SEQPACKET));
134 if (sockfd == -1) {
135 PLOG(ERROR) << "failed to connect to tombstoned";
136 return false;
137 }
138
139 TombstonedCrashPacket packet = {};
140 packet.packet_type = CrashPacketType::kDumpRequest;
141 packet.packet.dump_request.pid = pid;
142 if (TEMP_FAILURE_RETRY(write(sockfd, &packet, sizeof(packet))) != sizeof(packet)) {
143 PLOG(ERROR) << "failed to write DumpRequest packet";
144 return false;
145 }
146
147 unique_fd tmp_output_fd;
148 ssize_t rc = recv_fd(sockfd, &packet, sizeof(packet), &tmp_output_fd);
149 if (rc == -1) {
150 PLOG(ERROR) << "failed to read response to DumpRequest packet";
151 return false;
152 } else if (rc != sizeof(packet)) {
153 LOG(ERROR) << "read DumpRequest response packet of incorrect length (expected "
154 << sizeof(packet) << ", got " << rc << ")";
155 return false;
156 }
157
158 *tombstoned_socket = std::move(sockfd);
159 *output_fd = std::move(tmp_output_fd);
160 return true;
161}
162
163static bool tombstoned_notify_completion(int tombstoned_socket) {
164 TombstonedCrashPacket packet = {};
165 packet.packet_type = CrashPacketType::kCompletedDump;
166 if (TEMP_FAILURE_RETRY(write(tombstoned_socket, &packet, sizeof(packet))) != sizeof(packet)) {
167 return false;
168 }
169 return true;
170}
171
Josh Gao57594112017-01-22 17:41:15 -0800172static void signal_handler(int) {
173 // We can't log easily, because the heap might be corrupt.
174 // Just die and let the surrounding log context explain things.
175 _exit(1);
176}
177
Josh Gaocbe70cb2016-10-18 18:17:52 -0700178static void abort_handler(pid_t target, const bool& tombstoned_connected,
179 unique_fd& tombstoned_socket, unique_fd& output_fd,
180 const char* abort_msg) {
Josh Gaocbe70cb2016-10-18 18:17:52 -0700181 // If we abort before we get an output fd, contact tombstoned to let any
182 // potential listeners know that we failed.
183 if (!tombstoned_connected) {
184 if (!tombstoned_connect(target, &tombstoned_socket, &output_fd)) {
185 // We failed to connect, not much we can do.
186 LOG(ERROR) << "failed to connected to tombstoned to report failure";
187 _exit(1);
188 }
189 }
190
191 dprintf(output_fd.get(), "crash_dump failed to dump process %d: %s\n", target, abort_msg);
192
Josh Gaocbe70cb2016-10-18 18:17:52 -0700193 _exit(1);
194}
195
Josh Gao85bcaf62017-02-01 16:35:31 -0800196static void drop_capabilities() {
197 __user_cap_header_struct capheader;
198 memset(&capheader, 0, sizeof(capheader));
199 capheader.version = _LINUX_CAPABILITY_VERSION_3;
200 capheader.pid = 0;
201
202 __user_cap_data_struct capdata[2];
203 memset(&capdata, 0, sizeof(capdata));
204
205 if (capset(&capheader, &capdata[0]) == -1) {
206 PLOG(FATAL) << "failed to drop capabilities";
207 }
208
209 if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) != 0) {
210 PLOG(FATAL) << "failed to set PR_SET_NO_NEW_PRIVS";
211 }
212}
213
Josh Gaocbe70cb2016-10-18 18:17:52 -0700214static void check_process(int proc_fd, pid_t expected_pid) {
215 android::procinfo::ProcessInfo proc_info;
216 if (!android::procinfo::GetProcessInfoFromProcPidFd(proc_fd, &proc_info)) {
217 LOG(FATAL) << "failed to fetch process info";
218 }
219
220 if (proc_info.pid != expected_pid) {
Josh Gaof6ad5852017-02-15 12:21:11 -0800221 LOG(FATAL) << "pid mismatch: expected " << expected_pid << ", actual " << proc_info.pid;
Josh Gaocbe70cb2016-10-18 18:17:52 -0700222 }
223}
224
225int main(int argc, char** argv) {
226 pid_t target = getppid();
227 bool tombstoned_connected = false;
228 unique_fd tombstoned_socket;
229 unique_fd output_fd;
230
231 android::base::InitLogging(argv);
232 android::base::SetAborter([&](const char* abort_msg) {
233 abort_handler(target, tombstoned_connected, tombstoned_socket, output_fd, abort_msg);
234 });
235
Josh Gao57594112017-01-22 17:41:15 -0800236 // Don't try to dump ourselves.
237 struct sigaction action = {};
238 action.sa_handler = signal_handler;
239 debuggerd_register_handlers(&action);
240
Josh Gao2f11a252017-02-13 14:46:19 -0800241 if (argc != 3) {
Josh Gaocbe70cb2016-10-18 18:17:52 -0700242 return 1;
243 }
244
245 pid_t main_tid;
Josh Gao2f11a252017-02-13 14:46:19 -0800246 pid_t pseudothread_tid;
Josh Gaocbe70cb2016-10-18 18:17:52 -0700247
248 if (target == 1) {
249 LOG(FATAL) << "target died before we could attach";
250 }
251
252 if (!android::base::ParseInt(argv[1], &main_tid, 1, std::numeric_limits<pid_t>::max())) {
253 LOG(FATAL) << "invalid main tid: " << argv[1];
254 }
255
Josh Gao2f11a252017-02-13 14:46:19 -0800256 if (!android::base::ParseInt(argv[2], &pseudothread_tid, 1, std::numeric_limits<pid_t>::max())) {
Josh Gaof6ad5852017-02-15 12:21:11 -0800257 LOG(FATAL) << "invalid pseudothread tid: " << argv[2];
Josh Gao2f11a252017-02-13 14:46:19 -0800258 }
259
Josh Gaocbe70cb2016-10-18 18:17:52 -0700260 android::procinfo::ProcessInfo target_info;
261 if (!android::procinfo::GetProcessInfo(main_tid, &target_info)) {
262 LOG(FATAL) << "failed to fetch process info for target " << main_tid;
263 }
264
265 if (main_tid != target_info.tid || target != target_info.pid) {
266 LOG(FATAL) << "target info mismatch, expected pid " << target << ", tid " << main_tid
267 << ", received pid " << target_info.pid << ", tid " << target_info.tid;
268 }
269
270 // Open /proc/`getppid()` in the original process, and pass it down to the forked child.
271 std::string target_proc_path = "/proc/" + std::to_string(target);
272 int target_proc_fd = open(target_proc_path.c_str(), O_DIRECTORY | O_RDONLY);
273 if (target_proc_fd == -1) {
274 PLOG(FATAL) << "failed to open " << target_proc_path;
275 }
276
277 // Reparent ourselves to init, so that the signal handler can waitpid on the
278 // original process to avoid leaving a zombie for non-fatal dumps.
279 pid_t forkpid = fork();
280 if (forkpid == -1) {
281 PLOG(FATAL) << "fork failed";
282 } else if (forkpid != 0) {
283 exit(0);
284 }
285
Josh Gao7c6e3132017-01-22 17:59:02 -0800286 // Die if we take too long.
287 alarm(20);
288
Josh Gaocbe70cb2016-10-18 18:17:52 -0700289 check_process(target_proc_fd, target);
290
Josh Gao42fd74b2017-01-20 12:51:11 -0800291 std::string attach_error;
Josh Gao2f11a252017-02-13 14:46:19 -0800292
293 // Seize the main thread.
Josh Gaofe902762017-02-01 16:31:43 -0800294 if (!ptrace_seize_thread(target_proc_fd, main_tid, &attach_error)) {
Josh Gao42fd74b2017-01-20 12:51:11 -0800295 LOG(FATAL) << attach_error;
Josh Gaocbe70cb2016-10-18 18:17:52 -0700296 }
297
Josh Gao2f11a252017-02-13 14:46:19 -0800298 // Seize the siblings.
299 std::set<pid_t> attached_siblings;
300 {
301 std::set<pid_t> siblings;
302 if (!android::procinfo::GetProcessTids(target, &siblings)) {
303 PLOG(FATAL) << "failed to get process siblings";
304 }
305
306 // but not the already attached main thread.
307 siblings.erase(main_tid);
308 // or the handler pseudothread.
309 siblings.erase(pseudothread_tid);
310
311 for (pid_t sibling_tid : siblings) {
312 if (!ptrace_seize_thread(target_proc_fd, sibling_tid, &attach_error)) {
313 LOG(WARNING) << attach_error;
314 } else {
315 attached_siblings.insert(sibling_tid);
316 }
317 }
318 }
319
320 // Collect the backtrace map and open files, while the process still has PR_GET_DUMPABLE=1
321 std::unique_ptr<BacktraceMap> backtrace_map(BacktraceMap::Create(main_tid));
322 if (!backtrace_map) {
323 LOG(FATAL) << "failed to create backtrace map";
324 }
325
326 // Collect the list of open files.
327 OpenFilesList open_files;
328 populate_open_files_list(target, &open_files);
329
330 // Drop our capabilities now that we've attached to the threads we care about.
331 drop_capabilities();
Josh Gaocbe70cb2016-10-18 18:17:52 -0700332 check_process(target_proc_fd, target);
333
334 LOG(INFO) << "obtaining output fd from tombstoned";
335 tombstoned_connected = tombstoned_connect(target, &tombstoned_socket, &output_fd);
336
337 // Write a '\1' to stdout to tell the crashing process to resume.
Josh Gao2f11a252017-02-13 14:46:19 -0800338 // It also restores the value of PR_SET_DUMPABLE at this point.
Josh Gaocbe70cb2016-10-18 18:17:52 -0700339 if (TEMP_FAILURE_RETRY(write(STDOUT_FILENO, "\1", 1)) == -1) {
340 PLOG(ERROR) << "failed to communicate to target process";
341 }
342
343 if (tombstoned_connected) {
344 if (TEMP_FAILURE_RETRY(dup2(output_fd.get(), STDOUT_FILENO)) == -1) {
345 PLOG(ERROR) << "failed to dup2 output fd (" << output_fd.get() << ") to STDOUT_FILENO";
346 }
347 } else {
348 unique_fd devnull(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
349 TEMP_FAILURE_RETRY(dup2(devnull.get(), STDOUT_FILENO));
Josh Gao0a379012017-01-24 15:20:42 -0800350 output_fd = std::move(devnull);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700351 }
352
Josh Gaocbe70cb2016-10-18 18:17:52 -0700353 LOG(INFO) << "performing dump of process " << target << " (target tid = " << main_tid << ")";
354
Josh Gao122479f2017-01-22 16:42:32 -0800355 // At this point, the thread that made the request has been attached and is
356 // in ptrace-stopped state. After resumption, the triggering signal that has
357 // been queued will be delivered.
Josh Gaocbe70cb2016-10-18 18:17:52 -0700358 if (ptrace(PTRACE_CONT, main_tid, 0, 0) != 0) {
359 PLOG(ERROR) << "PTRACE_CONT(" << main_tid << ") failed";
360 exit(1);
361 }
362
363 siginfo_t siginfo = {};
364 if (!wait_for_signal(main_tid, &siginfo)) {
365 printf("failed to wait for signal in tid %d: %s\n", main_tid, strerror(errno));
366 exit(1);
367 }
368
369 int signo = siginfo.si_signo;
Josh Gaofe902762017-02-01 16:31:43 -0800370 bool fatal_signal = signo != DEBUGGER_SIGNAL;
Josh Gaocbe70cb2016-10-18 18:17:52 -0700371 bool backtrace = false;
372 uintptr_t abort_address = 0;
373
374 // si_value can represent three things:
375 // 0: dump tombstone
376 // 1: dump backtrace
377 // everything else: abort message address (implies dump tombstone)
378 if (siginfo.si_value.sival_int == 1) {
379 backtrace = true;
380 } else if (siginfo.si_value.sival_ptr != nullptr) {
381 abort_address = reinterpret_cast<uintptr_t>(siginfo.si_value.sival_ptr);
382 }
383
Josh Gaocbe70cb2016-10-18 18:17:52 -0700384 // TODO: Use seccomp to lock ourselves down.
385
Josh Gaocbe70cb2016-10-18 18:17:52 -0700386 std::string amfd_data;
Josh Gaocbe70cb2016-10-18 18:17:52 -0700387 if (backtrace) {
Josh Gao42fd74b2017-01-20 12:51:11 -0800388 dump_backtrace(output_fd.get(), backtrace_map.get(), target, main_tid, attached_siblings, 0);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700389 } else {
Josh Gao42fd74b2017-01-20 12:51:11 -0800390 engrave_tombstone(output_fd.get(), backtrace_map.get(), open_files, target, main_tid,
391 attached_siblings, abort_address, fatal_signal ? &amfd_data : nullptr);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700392 }
393
Josh Gao7c6e3132017-01-22 17:59:02 -0800394 // We don't actually need to PTRACE_DETACH, as long as our tracees aren't in
395 // group-stop state, which is true as long as no stopping signals are sent.
396
Josh Gaocbe70cb2016-10-18 18:17:52 -0700397 bool wait_for_gdb = android::base::GetBoolProperty("debug.debuggerd.wait_for_gdb", false);
Josh Gao7c6e3132017-01-22 17:59:02 -0800398 if (!fatal_signal || siginfo.si_code == SI_USER) {
Josh Gaocbe70cb2016-10-18 18:17:52 -0700399 // Don't wait_for_gdb when the process didn't actually crash.
Josh Gao7c6e3132017-01-22 17:59:02 -0800400 wait_for_gdb = false;
Josh Gaocbe70cb2016-10-18 18:17:52 -0700401 }
402
Josh Gao7c6e3132017-01-22 17:59:02 -0800403 // If the process crashed or we need to send it SIGSTOP for wait_for_gdb,
404 // get it in a state where it can receive signals, and then send the relevant
405 // signal.
406 if (wait_for_gdb || fatal_signal) {
407 if (ptrace(PTRACE_INTERRUPT, main_tid, 0, 0) != 0) {
408 PLOG(ERROR) << "failed to use PTRACE_INTERRUPT on " << main_tid;
Josh Gaocbe70cb2016-10-18 18:17:52 -0700409 }
Josh Gaocbe70cb2016-10-18 18:17:52 -0700410
Josh Gao7c6e3132017-01-22 17:59:02 -0800411 if (tgkill(target, main_tid, wait_for_gdb ? SIGSTOP : signo) != 0) {
412 PLOG(ERROR) << "failed to resend signal " << signo << " to " << main_tid;
413 }
Josh Gaocbe70cb2016-10-18 18:17:52 -0700414 }
415
416 if (wait_for_gdb) {
Josh Gao7c6e3132017-01-22 17:59:02 -0800417 // Use ALOGI to line up with output from engrave_tombstone.
418 ALOGI(
419 "***********************************************************\n"
420 "* Process %d has been suspended while crashing.\n"
421 "* To attach gdbserver and start gdb, run this on the host:\n"
422 "*\n"
423 "* gdbclient.py -p %d\n"
424 "*\n"
425 "***********************************************************",
426 target, main_tid);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700427 }
428
429 if (fatal_signal) {
430 activity_manager_notify(target, signo, amfd_data);
431 }
432
433 // Close stdout before we notify tombstoned of completion.
434 close(STDOUT_FILENO);
Josh Gao0a379012017-01-24 15:20:42 -0800435 if (tombstoned_connected && !tombstoned_notify_completion(tombstoned_socket.get())) {
Josh Gaocbe70cb2016-10-18 18:17:52 -0700436 LOG(ERROR) << "failed to notify tombstoned of completion";
437 }
438
439 return 0;
440}