blob: e4f88b0faa8b56f42e9060fad97f5475fef224c1 [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>
21#include <syscall.h>
22#include <sys/ptrace.h>
23#include <sys/types.h>
24#include <sys/un.h>
25#include <unistd.h>
26
27#include <limits>
28#include <memory>
29#include <set>
30#include <vector>
31
32#include <android-base/file.h>
33#include <android-base/logging.h>
34#include <android-base/parseint.h>
35#include <android-base/properties.h>
36#include <android-base/stringprintf.h>
37#include <android-base/unique_fd.h>
38#include <cutils/sockets.h>
Vijay Venkatramana95acea2017-01-23 20:11:51 -080039#include <log/log.h>
Josh Gaocbe70cb2016-10-18 18:17:52 -070040#include <procinfo/process.h>
41#include <selinux/selinux.h>
42
43#include "backtrace.h"
44#include "tombstone.h"
45#include "utility.h"
46
47#include "debuggerd/handler.h"
48#include "debuggerd/protocol.h"
49#include "debuggerd/util.h"
50
51using android::base::unique_fd;
52using android::base::StringPrintf;
53
54static bool pid_contains_tid(pid_t pid, pid_t tid) {
55 std::string task_path = StringPrintf("/proc/%d/task/%d", pid, tid);
56 return access(task_path.c_str(), F_OK) == 0;
57}
58
59// Attach to a thread, and verify that it's still a member of the given process
Josh Gao122479f2017-01-22 16:42:32 -080060static bool ptrace_seize_thread(pid_t pid, pid_t tid, std::string* error) {
61 if (ptrace(PTRACE_SEIZE, tid, 0, 0) != 0) {
Josh Gao42fd74b2017-01-20 12:51:11 -080062 *error = StringPrintf("failed to attach to thread %d: %s", tid, strerror(errno));
Josh Gaocbe70cb2016-10-18 18:17:52 -070063 return false;
64 }
65
66 // Make sure that the task we attached to is actually part of the pid we're dumping.
67 if (!pid_contains_tid(pid, tid)) {
68 if (ptrace(PTRACE_DETACH, tid, 0, 0) != 0) {
69 PLOG(FATAL) << "failed to detach from thread " << tid;
70 }
Josh Gao42fd74b2017-01-20 12:51:11 -080071 *error = StringPrintf("thread %d is not in process %d", tid, pid);
Josh Gaocbe70cb2016-10-18 18:17:52 -070072 return false;
73 }
Josh Gao122479f2017-01-22 16:42:32 -080074
75 // Put the task into ptrace-stop state.
76 if (ptrace(PTRACE_INTERRUPT, tid, 0, 0) != 0) {
77 PLOG(FATAL) << "failed to interrupt thread " << tid;
78 }
79
Josh Gaocbe70cb2016-10-18 18:17:52 -070080 return true;
81}
82
83static bool activity_manager_notify(int pid, int signal, const std::string& amfd_data) {
84 android::base::unique_fd amfd(socket_local_client("/data/system/ndebugsocket", ANDROID_SOCKET_NAMESPACE_FILESYSTEM, SOCK_STREAM));
85 if (amfd.get() == -1) {
86 PLOG(ERROR) << "unable to connect to activity manager";
87 return false;
88 }
89
90 struct timeval tv = {
91 .tv_sec = 1,
92 .tv_usec = 0,
93 };
94 if (setsockopt(amfd.get(), SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)) == -1) {
95 PLOG(ERROR) << "failed to set send timeout on activity manager socket";
96 return false;
97 }
98 tv.tv_sec = 3; // 3 seconds on handshake read
99 if (setsockopt(amfd.get(), SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) == -1) {
100 PLOG(ERROR) << "failed to set receive timeout on activity manager socket";
101 return false;
102 }
103
104 // Activity Manager protocol: binary 32-bit network-byte-order ints for the
105 // pid and signal number, followed by the raw text of the dump, culminating
106 // in a zero byte that marks end-of-data.
107 uint32_t datum = htonl(pid);
108 if (!android::base::WriteFully(amfd, &datum, 4)) {
109 PLOG(ERROR) << "AM pid write failed";
110 return false;
111 }
112 datum = htonl(signal);
113 if (!android::base::WriteFully(amfd, &datum, 4)) {
114 PLOG(ERROR) << "AM signal write failed";
115 return false;
116 }
117 if (!android::base::WriteFully(amfd, amfd_data.c_str(), amfd_data.size() + 1)) {
118 PLOG(ERROR) << "AM data write failed";
119 return false;
120 }
121
122 // 3 sec timeout reading the ack; we're fine if the read fails.
123 char ack;
124 android::base::ReadFully(amfd, &ack, 1);
125 return true;
126}
127
128static bool tombstoned_connect(pid_t pid, unique_fd* tombstoned_socket, unique_fd* output_fd) {
129 unique_fd sockfd(socket_local_client(kTombstonedCrashSocketName,
130 ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_SEQPACKET));
131 if (sockfd == -1) {
132 PLOG(ERROR) << "failed to connect to tombstoned";
133 return false;
134 }
135
136 TombstonedCrashPacket packet = {};
137 packet.packet_type = CrashPacketType::kDumpRequest;
138 packet.packet.dump_request.pid = pid;
139 if (TEMP_FAILURE_RETRY(write(sockfd, &packet, sizeof(packet))) != sizeof(packet)) {
140 PLOG(ERROR) << "failed to write DumpRequest packet";
141 return false;
142 }
143
144 unique_fd tmp_output_fd;
145 ssize_t rc = recv_fd(sockfd, &packet, sizeof(packet), &tmp_output_fd);
146 if (rc == -1) {
147 PLOG(ERROR) << "failed to read response to DumpRequest packet";
148 return false;
149 } else if (rc != sizeof(packet)) {
150 LOG(ERROR) << "read DumpRequest response packet of incorrect length (expected "
151 << sizeof(packet) << ", got " << rc << ")";
152 return false;
153 }
154
155 *tombstoned_socket = std::move(sockfd);
156 *output_fd = std::move(tmp_output_fd);
157 return true;
158}
159
160static bool tombstoned_notify_completion(int tombstoned_socket) {
161 TombstonedCrashPacket packet = {};
162 packet.packet_type = CrashPacketType::kCompletedDump;
163 if (TEMP_FAILURE_RETRY(write(tombstoned_socket, &packet, sizeof(packet))) != sizeof(packet)) {
164 return false;
165 }
166 return true;
167}
168
Josh Gao57594112017-01-22 17:41:15 -0800169static void signal_handler(int) {
170 // We can't log easily, because the heap might be corrupt.
171 // Just die and let the surrounding log context explain things.
172 _exit(1);
173}
174
Josh Gaocbe70cb2016-10-18 18:17:52 -0700175static void abort_handler(pid_t target, const bool& tombstoned_connected,
176 unique_fd& tombstoned_socket, unique_fd& output_fd,
177 const char* abort_msg) {
Josh Gaocbe70cb2016-10-18 18:17:52 -0700178 // If we abort before we get an output fd, contact tombstoned to let any
179 // potential listeners know that we failed.
180 if (!tombstoned_connected) {
181 if (!tombstoned_connect(target, &tombstoned_socket, &output_fd)) {
182 // We failed to connect, not much we can do.
183 LOG(ERROR) << "failed to connected to tombstoned to report failure";
184 _exit(1);
185 }
186 }
187
188 dprintf(output_fd.get(), "crash_dump failed to dump process %d: %s\n", target, abort_msg);
189
Josh Gaocbe70cb2016-10-18 18:17:52 -0700190 _exit(1);
191}
192
193static void check_process(int proc_fd, pid_t expected_pid) {
194 android::procinfo::ProcessInfo proc_info;
195 if (!android::procinfo::GetProcessInfoFromProcPidFd(proc_fd, &proc_info)) {
196 LOG(FATAL) << "failed to fetch process info";
197 }
198
199 if (proc_info.pid != expected_pid) {
200 LOG(FATAL) << "pid mismatch: expected " << expected_pid << ", actual " << proc_info.ppid;
201 }
202}
203
204int main(int argc, char** argv) {
205 pid_t target = getppid();
206 bool tombstoned_connected = false;
207 unique_fd tombstoned_socket;
208 unique_fd output_fd;
209
210 android::base::InitLogging(argv);
211 android::base::SetAborter([&](const char* abort_msg) {
212 abort_handler(target, tombstoned_connected, tombstoned_socket, output_fd, abort_msg);
213 });
214
Josh Gao57594112017-01-22 17:41:15 -0800215 // Don't try to dump ourselves.
216 struct sigaction action = {};
217 action.sa_handler = signal_handler;
218 debuggerd_register_handlers(&action);
219
Josh Gaocbe70cb2016-10-18 18:17:52 -0700220 if (argc != 2) {
221 return 1;
222 }
223
224 pid_t main_tid;
225
226 if (target == 1) {
227 LOG(FATAL) << "target died before we could attach";
228 }
229
230 if (!android::base::ParseInt(argv[1], &main_tid, 1, std::numeric_limits<pid_t>::max())) {
231 LOG(FATAL) << "invalid main tid: " << argv[1];
232 }
233
234 android::procinfo::ProcessInfo target_info;
235 if (!android::procinfo::GetProcessInfo(main_tid, &target_info)) {
236 LOG(FATAL) << "failed to fetch process info for target " << main_tid;
237 }
238
239 if (main_tid != target_info.tid || target != target_info.pid) {
240 LOG(FATAL) << "target info mismatch, expected pid " << target << ", tid " << main_tid
241 << ", received pid " << target_info.pid << ", tid " << target_info.tid;
242 }
243
244 // Open /proc/`getppid()` in the original process, and pass it down to the forked child.
245 std::string target_proc_path = "/proc/" + std::to_string(target);
246 int target_proc_fd = open(target_proc_path.c_str(), O_DIRECTORY | O_RDONLY);
247 if (target_proc_fd == -1) {
248 PLOG(FATAL) << "failed to open " << target_proc_path;
249 }
250
251 // Reparent ourselves to init, so that the signal handler can waitpid on the
252 // original process to avoid leaving a zombie for non-fatal dumps.
253 pid_t forkpid = fork();
254 if (forkpid == -1) {
255 PLOG(FATAL) << "fork failed";
256 } else if (forkpid != 0) {
257 exit(0);
258 }
259
Josh Gao7c6e3132017-01-22 17:59:02 -0800260 // Die if we take too long.
261 alarm(20);
262
Josh Gaocbe70cb2016-10-18 18:17:52 -0700263 check_process(target_proc_fd, target);
264
Josh Gao42fd74b2017-01-20 12:51:11 -0800265 std::string attach_error;
Josh Gao122479f2017-01-22 16:42:32 -0800266 if (!ptrace_seize_thread(target, main_tid, &attach_error)) {
Josh Gao42fd74b2017-01-20 12:51:11 -0800267 LOG(FATAL) << attach_error;
Josh Gaocbe70cb2016-10-18 18:17:52 -0700268 }
269
270 check_process(target_proc_fd, target);
271
272 LOG(INFO) << "obtaining output fd from tombstoned";
273 tombstoned_connected = tombstoned_connect(target, &tombstoned_socket, &output_fd);
274
275 // Write a '\1' to stdout to tell the crashing process to resume.
276 if (TEMP_FAILURE_RETRY(write(STDOUT_FILENO, "\1", 1)) == -1) {
277 PLOG(ERROR) << "failed to communicate to target process";
278 }
279
280 if (tombstoned_connected) {
281 if (TEMP_FAILURE_RETRY(dup2(output_fd.get(), STDOUT_FILENO)) == -1) {
282 PLOG(ERROR) << "failed to dup2 output fd (" << output_fd.get() << ") to STDOUT_FILENO";
283 }
284 } else {
285 unique_fd devnull(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
286 TEMP_FAILURE_RETRY(dup2(devnull.get(), STDOUT_FILENO));
287 }
288
Josh Gaocbe70cb2016-10-18 18:17:52 -0700289 LOG(INFO) << "performing dump of process " << target << " (target tid = " << main_tid << ")";
290
Josh Gao122479f2017-01-22 16:42:32 -0800291 // At this point, the thread that made the request has been attached and is
292 // in ptrace-stopped state. After resumption, the triggering signal that has
293 // been queued will be delivered.
Josh Gaocbe70cb2016-10-18 18:17:52 -0700294 if (ptrace(PTRACE_CONT, main_tid, 0, 0) != 0) {
295 PLOG(ERROR) << "PTRACE_CONT(" << main_tid << ") failed";
296 exit(1);
297 }
298
299 siginfo_t siginfo = {};
300 if (!wait_for_signal(main_tid, &siginfo)) {
301 printf("failed to wait for signal in tid %d: %s\n", main_tid, strerror(errno));
302 exit(1);
303 }
304
305 int signo = siginfo.si_signo;
306 bool backtrace = false;
307 uintptr_t abort_address = 0;
308
309 // si_value can represent three things:
310 // 0: dump tombstone
311 // 1: dump backtrace
312 // everything else: abort message address (implies dump tombstone)
313 if (siginfo.si_value.sival_int == 1) {
314 backtrace = true;
315 } else if (siginfo.si_value.sival_ptr != nullptr) {
316 abort_address = reinterpret_cast<uintptr_t>(siginfo.si_value.sival_ptr);
317 }
318
319 // Now that we have the signal that kicked things off, attach all of the
320 // sibling threads, and then proceed.
321 bool fatal_signal = signo != DEBUGGER_SIGNAL;
Josh Gaocbe70cb2016-10-18 18:17:52 -0700322 std::set<pid_t> siblings;
Josh Gao42fd74b2017-01-20 12:51:11 -0800323 std::set<pid_t> attached_siblings;
Josh Gao7c6e3132017-01-22 17:59:02 -0800324 if (fatal_signal) {
Josh Gaocbe70cb2016-10-18 18:17:52 -0700325 if (!android::procinfo::GetProcessTids(target, &siblings)) {
326 PLOG(FATAL) << "failed to get process siblings";
327 }
328 siblings.erase(main_tid);
329
330 for (pid_t sibling_tid : siblings) {
Josh Gao122479f2017-01-22 16:42:32 -0800331 if (!ptrace_seize_thread(target, sibling_tid, &attach_error)) {
Josh Gao42fd74b2017-01-20 12:51:11 -0800332 LOG(WARNING) << attach_error;
333 } else {
334 attached_siblings.insert(sibling_tid);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700335 }
336 }
337 }
338
339 check_process(target_proc_fd, target);
340
341 // TODO: Use seccomp to lock ourselves down.
342
343 std::unique_ptr<BacktraceMap> backtrace_map(BacktraceMap::Create(main_tid));
344 std::string amfd_data;
345
346 if (backtrace) {
Josh Gao42fd74b2017-01-20 12:51:11 -0800347 dump_backtrace(output_fd.get(), backtrace_map.get(), target, main_tid, attached_siblings, 0);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700348 } else {
349 // Collect the list of open files.
350 OpenFilesList open_files;
351 populate_open_files_list(target, &open_files);
352
Josh Gao42fd74b2017-01-20 12:51:11 -0800353 engrave_tombstone(output_fd.get(), backtrace_map.get(), open_files, target, main_tid,
354 attached_siblings, abort_address, fatal_signal ? &amfd_data : nullptr);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700355 }
356
Josh Gao7c6e3132017-01-22 17:59:02 -0800357 // We don't actually need to PTRACE_DETACH, as long as our tracees aren't in
358 // group-stop state, which is true as long as no stopping signals are sent.
359
Josh Gaocbe70cb2016-10-18 18:17:52 -0700360 bool wait_for_gdb = android::base::GetBoolProperty("debug.debuggerd.wait_for_gdb", false);
Josh Gao7c6e3132017-01-22 17:59:02 -0800361 if (!fatal_signal || siginfo.si_code == SI_USER) {
Josh Gaocbe70cb2016-10-18 18:17:52 -0700362 // Don't wait_for_gdb when the process didn't actually crash.
Josh Gao7c6e3132017-01-22 17:59:02 -0800363 wait_for_gdb = false;
Josh Gaocbe70cb2016-10-18 18:17:52 -0700364 }
365
Josh Gao7c6e3132017-01-22 17:59:02 -0800366 // If the process crashed or we need to send it SIGSTOP for wait_for_gdb,
367 // get it in a state where it can receive signals, and then send the relevant
368 // signal.
369 if (wait_for_gdb || fatal_signal) {
370 if (ptrace(PTRACE_INTERRUPT, main_tid, 0, 0) != 0) {
371 PLOG(ERROR) << "failed to use PTRACE_INTERRUPT on " << main_tid;
Josh Gaocbe70cb2016-10-18 18:17:52 -0700372 }
Josh Gaocbe70cb2016-10-18 18:17:52 -0700373
Josh Gao7c6e3132017-01-22 17:59:02 -0800374 if (tgkill(target, main_tid, wait_for_gdb ? SIGSTOP : signo) != 0) {
375 PLOG(ERROR) << "failed to resend signal " << signo << " to " << main_tid;
376 }
Josh Gaocbe70cb2016-10-18 18:17:52 -0700377 }
378
379 if (wait_for_gdb) {
Josh Gao7c6e3132017-01-22 17:59:02 -0800380 // Use ALOGI to line up with output from engrave_tombstone.
381 ALOGI(
382 "***********************************************************\n"
383 "* Process %d has been suspended while crashing.\n"
384 "* To attach gdbserver and start gdb, run this on the host:\n"
385 "*\n"
386 "* gdbclient.py -p %d\n"
387 "*\n"
388 "***********************************************************",
389 target, main_tid);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700390 }
391
392 if (fatal_signal) {
393 activity_manager_notify(target, signo, amfd_data);
394 }
395
396 // Close stdout before we notify tombstoned of completion.
397 close(STDOUT_FILENO);
398 if (!tombstoned_notify_completion(tombstoned_socket.get())) {
399 LOG(ERROR) << "failed to notify tombstoned of completion";
400 }
401
402 return 0;
403}