blob: cd939ef886d35774d325a6701819c28ce91dc5b5 [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>
39#include <log/logger.h>
40#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 Gao42fd74b2017-01-20 12:51:11 -080060static bool ptrace_attach_thread(pid_t pid, pid_t tid, std::string* error) {
Josh Gaocbe70cb2016-10-18 18:17:52 -070061 if (ptrace(PTRACE_ATTACH, 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 }
74 return true;
75}
76
77static bool activity_manager_notify(int pid, int signal, const std::string& amfd_data) {
78 android::base::unique_fd amfd(socket_local_client("/data/system/ndebugsocket", ANDROID_SOCKET_NAMESPACE_FILESYSTEM, SOCK_STREAM));
79 if (amfd.get() == -1) {
80 PLOG(ERROR) << "unable to connect to activity manager";
81 return false;
82 }
83
84 struct timeval tv = {
85 .tv_sec = 1,
86 .tv_usec = 0,
87 };
88 if (setsockopt(amfd.get(), SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)) == -1) {
89 PLOG(ERROR) << "failed to set send timeout on activity manager socket";
90 return false;
91 }
92 tv.tv_sec = 3; // 3 seconds on handshake read
93 if (setsockopt(amfd.get(), SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) == -1) {
94 PLOG(ERROR) << "failed to set receive timeout on activity manager socket";
95 return false;
96 }
97
98 // Activity Manager protocol: binary 32-bit network-byte-order ints for the
99 // pid and signal number, followed by the raw text of the dump, culminating
100 // in a zero byte that marks end-of-data.
101 uint32_t datum = htonl(pid);
102 if (!android::base::WriteFully(amfd, &datum, 4)) {
103 PLOG(ERROR) << "AM pid write failed";
104 return false;
105 }
106 datum = htonl(signal);
107 if (!android::base::WriteFully(amfd, &datum, 4)) {
108 PLOG(ERROR) << "AM signal write failed";
109 return false;
110 }
111 if (!android::base::WriteFully(amfd, amfd_data.c_str(), amfd_data.size() + 1)) {
112 PLOG(ERROR) << "AM data write failed";
113 return false;
114 }
115
116 // 3 sec timeout reading the ack; we're fine if the read fails.
117 char ack;
118 android::base::ReadFully(amfd, &ack, 1);
119 return true;
120}
121
122static bool tombstoned_connect(pid_t pid, unique_fd* tombstoned_socket, unique_fd* output_fd) {
123 unique_fd sockfd(socket_local_client(kTombstonedCrashSocketName,
124 ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_SEQPACKET));
125 if (sockfd == -1) {
126 PLOG(ERROR) << "failed to connect to tombstoned";
127 return false;
128 }
129
130 TombstonedCrashPacket packet = {};
131 packet.packet_type = CrashPacketType::kDumpRequest;
132 packet.packet.dump_request.pid = pid;
133 if (TEMP_FAILURE_RETRY(write(sockfd, &packet, sizeof(packet))) != sizeof(packet)) {
134 PLOG(ERROR) << "failed to write DumpRequest packet";
135 return false;
136 }
137
138 unique_fd tmp_output_fd;
139 ssize_t rc = recv_fd(sockfd, &packet, sizeof(packet), &tmp_output_fd);
140 if (rc == -1) {
141 PLOG(ERROR) << "failed to read response to DumpRequest packet";
142 return false;
143 } else if (rc != sizeof(packet)) {
144 LOG(ERROR) << "read DumpRequest response packet of incorrect length (expected "
145 << sizeof(packet) << ", got " << rc << ")";
146 return false;
147 }
148
149 *tombstoned_socket = std::move(sockfd);
150 *output_fd = std::move(tmp_output_fd);
151 return true;
152}
153
154static bool tombstoned_notify_completion(int tombstoned_socket) {
155 TombstonedCrashPacket packet = {};
156 packet.packet_type = CrashPacketType::kCompletedDump;
157 if (TEMP_FAILURE_RETRY(write(tombstoned_socket, &packet, sizeof(packet))) != sizeof(packet)) {
158 return false;
159 }
160 return true;
161}
162
Josh Gao57594112017-01-22 17:41:15 -0800163static void signal_handler(int) {
164 // We can't log easily, because the heap might be corrupt.
165 // Just die and let the surrounding log context explain things.
166 _exit(1);
167}
168
Josh Gaocbe70cb2016-10-18 18:17:52 -0700169static void abort_handler(pid_t target, const bool& tombstoned_connected,
170 unique_fd& tombstoned_socket, unique_fd& output_fd,
171 const char* abort_msg) {
Josh Gaocbe70cb2016-10-18 18:17:52 -0700172 // If we abort before we get an output fd, contact tombstoned to let any
173 // potential listeners know that we failed.
174 if (!tombstoned_connected) {
175 if (!tombstoned_connect(target, &tombstoned_socket, &output_fd)) {
176 // We failed to connect, not much we can do.
177 LOG(ERROR) << "failed to connected to tombstoned to report failure";
178 _exit(1);
179 }
180 }
181
182 dprintf(output_fd.get(), "crash_dump failed to dump process %d: %s\n", target, abort_msg);
183
Josh Gaocbe70cb2016-10-18 18:17:52 -0700184 _exit(1);
185}
186
187static void check_process(int proc_fd, pid_t expected_pid) {
188 android::procinfo::ProcessInfo proc_info;
189 if (!android::procinfo::GetProcessInfoFromProcPidFd(proc_fd, &proc_info)) {
190 LOG(FATAL) << "failed to fetch process info";
191 }
192
193 if (proc_info.pid != expected_pid) {
194 LOG(FATAL) << "pid mismatch: expected " << expected_pid << ", actual " << proc_info.ppid;
195 }
196}
197
198int main(int argc, char** argv) {
199 pid_t target = getppid();
200 bool tombstoned_connected = false;
201 unique_fd tombstoned_socket;
202 unique_fd output_fd;
203
204 android::base::InitLogging(argv);
205 android::base::SetAborter([&](const char* abort_msg) {
206 abort_handler(target, tombstoned_connected, tombstoned_socket, output_fd, abort_msg);
207 });
208
Josh Gao57594112017-01-22 17:41:15 -0800209 // Don't try to dump ourselves.
210 struct sigaction action = {};
211 action.sa_handler = signal_handler;
212 debuggerd_register_handlers(&action);
213
Josh Gaocbe70cb2016-10-18 18:17:52 -0700214 if (argc != 2) {
215 return 1;
216 }
217
218 pid_t main_tid;
219
220 if (target == 1) {
221 LOG(FATAL) << "target died before we could attach";
222 }
223
224 if (!android::base::ParseInt(argv[1], &main_tid, 1, std::numeric_limits<pid_t>::max())) {
225 LOG(FATAL) << "invalid main tid: " << argv[1];
226 }
227
228 android::procinfo::ProcessInfo target_info;
229 if (!android::procinfo::GetProcessInfo(main_tid, &target_info)) {
230 LOG(FATAL) << "failed to fetch process info for target " << main_tid;
231 }
232
233 if (main_tid != target_info.tid || target != target_info.pid) {
234 LOG(FATAL) << "target info mismatch, expected pid " << target << ", tid " << main_tid
235 << ", received pid " << target_info.pid << ", tid " << target_info.tid;
236 }
237
238 // Open /proc/`getppid()` in the original process, and pass it down to the forked child.
239 std::string target_proc_path = "/proc/" + std::to_string(target);
240 int target_proc_fd = open(target_proc_path.c_str(), O_DIRECTORY | O_RDONLY);
241 if (target_proc_fd == -1) {
242 PLOG(FATAL) << "failed to open " << target_proc_path;
243 }
244
245 // Reparent ourselves to init, so that the signal handler can waitpid on the
246 // original process to avoid leaving a zombie for non-fatal dumps.
247 pid_t forkpid = fork();
248 if (forkpid == -1) {
249 PLOG(FATAL) << "fork failed";
250 } else if (forkpid != 0) {
251 exit(0);
252 }
253
254 check_process(target_proc_fd, target);
255
Josh Gao42fd74b2017-01-20 12:51:11 -0800256 std::string attach_error;
257 if (!ptrace_attach_thread(target, main_tid, &attach_error)) {
258 LOG(FATAL) << attach_error;
Josh Gaocbe70cb2016-10-18 18:17:52 -0700259 }
260
261 check_process(target_proc_fd, target);
262
263 LOG(INFO) << "obtaining output fd from tombstoned";
264 tombstoned_connected = tombstoned_connect(target, &tombstoned_socket, &output_fd);
265
266 // Write a '\1' to stdout to tell the crashing process to resume.
267 if (TEMP_FAILURE_RETRY(write(STDOUT_FILENO, "\1", 1)) == -1) {
268 PLOG(ERROR) << "failed to communicate to target process";
269 }
270
271 if (tombstoned_connected) {
272 if (TEMP_FAILURE_RETRY(dup2(output_fd.get(), STDOUT_FILENO)) == -1) {
273 PLOG(ERROR) << "failed to dup2 output fd (" << output_fd.get() << ") to STDOUT_FILENO";
274 }
275 } else {
276 unique_fd devnull(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
277 TEMP_FAILURE_RETRY(dup2(devnull.get(), STDOUT_FILENO));
278 }
279
Josh Gaocbe70cb2016-10-18 18:17:52 -0700280 LOG(INFO) << "performing dump of process " << target << " (target tid = " << main_tid << ")";
281
282 // At this point, the thread that made the request has been PTRACE_ATTACHed
283 // and has the signal that triggered things queued. Send PTRACE_CONT, and
284 // then wait for the signal.
285 if (ptrace(PTRACE_CONT, main_tid, 0, 0) != 0) {
286 PLOG(ERROR) << "PTRACE_CONT(" << main_tid << ") failed";
287 exit(1);
288 }
289
290 siginfo_t siginfo = {};
291 if (!wait_for_signal(main_tid, &siginfo)) {
292 printf("failed to wait for signal in tid %d: %s\n", main_tid, strerror(errno));
293 exit(1);
294 }
295
296 int signo = siginfo.si_signo;
297 bool backtrace = false;
298 uintptr_t abort_address = 0;
299
300 // si_value can represent three things:
301 // 0: dump tombstone
302 // 1: dump backtrace
303 // everything else: abort message address (implies dump tombstone)
304 if (siginfo.si_value.sival_int == 1) {
305 backtrace = true;
306 } else if (siginfo.si_value.sival_ptr != nullptr) {
307 abort_address = reinterpret_cast<uintptr_t>(siginfo.si_value.sival_ptr);
308 }
309
310 // Now that we have the signal that kicked things off, attach all of the
311 // sibling threads, and then proceed.
312 bool fatal_signal = signo != DEBUGGER_SIGNAL;
313 int resume_signal = fatal_signal ? signo : 0;
314 std::set<pid_t> siblings;
Josh Gao42fd74b2017-01-20 12:51:11 -0800315 std::set<pid_t> attached_siblings;
Josh Gaocbe70cb2016-10-18 18:17:52 -0700316 if (resume_signal == 0) {
317 if (!android::procinfo::GetProcessTids(target, &siblings)) {
318 PLOG(FATAL) << "failed to get process siblings";
319 }
320 siblings.erase(main_tid);
321
322 for (pid_t sibling_tid : siblings) {
Josh Gao42fd74b2017-01-20 12:51:11 -0800323 if (!ptrace_attach_thread(target, sibling_tid, &attach_error)) {
324 LOG(WARNING) << attach_error;
325 } else {
326 attached_siblings.insert(sibling_tid);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700327 }
328 }
329 }
330
331 check_process(target_proc_fd, target);
332
333 // TODO: Use seccomp to lock ourselves down.
334
335 std::unique_ptr<BacktraceMap> backtrace_map(BacktraceMap::Create(main_tid));
336 std::string amfd_data;
337
338 if (backtrace) {
Josh Gao42fd74b2017-01-20 12:51:11 -0800339 dump_backtrace(output_fd.get(), backtrace_map.get(), target, main_tid, attached_siblings, 0);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700340 } else {
341 // Collect the list of open files.
342 OpenFilesList open_files;
343 populate_open_files_list(target, &open_files);
344
Josh Gao42fd74b2017-01-20 12:51:11 -0800345 engrave_tombstone(output_fd.get(), backtrace_map.get(), open_files, target, main_tid,
346 attached_siblings, abort_address, fatal_signal ? &amfd_data : nullptr);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700347 }
348
349 bool wait_for_gdb = android::base::GetBoolProperty("debug.debuggerd.wait_for_gdb", false);
350 if (wait_for_gdb) {
351 // Don't wait_for_gdb when the process didn't actually crash.
352 if (!fatal_signal) {
353 wait_for_gdb = false;
354 } else {
355 // Use ALOGI to line up with output from engrave_tombstone.
356 ALOGI(
357 "***********************************************************\n"
358 "* Process %d has been suspended while crashing.\n"
359 "* To attach gdbserver and start gdb, run this on the host:\n"
360 "*\n"
361 "* gdbclient.py -p %d\n"
362 "*\n"
363 "***********************************************************",
364 target, main_tid);
365 }
366 }
367
Josh Gao42fd74b2017-01-20 12:51:11 -0800368 for (pid_t tid : attached_siblings) {
Josh Gaocbe70cb2016-10-18 18:17:52 -0700369 // Don't send the signal to sibling threads.
370 if (ptrace(PTRACE_DETACH, tid, 0, wait_for_gdb ? SIGSTOP : 0) != 0) {
371 PLOG(ERROR) << "ptrace detach from " << tid << " failed";
372 }
373 }
374
375 if (ptrace(PTRACE_DETACH, main_tid, 0, wait_for_gdb ? SIGSTOP : resume_signal)) {
376 PLOG(ERROR) << "ptrace detach from main thread " << main_tid << " failed";
377 }
378
379 if (wait_for_gdb) {
380 if (tgkill(target, main_tid, resume_signal) != 0) {
381 PLOG(ERROR) << "failed to resend signal to process " << target;
382 }
383 }
384
385 if (fatal_signal) {
386 activity_manager_notify(target, signo, amfd_data);
387 }
388
389 // Close stdout before we notify tombstoned of completion.
390 close(STDOUT_FILENO);
391 if (!tombstoned_notify_completion(tombstoned_socket.get())) {
392 LOG(ERROR) << "failed to notify tombstoned of completion";
393 }
394
395 return 0;
396}