blob: 4db13aaa5b61c8359c453a9bbc985f750072f5db [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
163static void abort_handler(pid_t target, const bool& tombstoned_connected,
164 unique_fd& tombstoned_socket, unique_fd& output_fd,
165 const char* abort_msg) {
Josh Gaocbe70cb2016-10-18 18:17:52 -0700166 // If we abort before we get an output fd, contact tombstoned to let any
167 // potential listeners know that we failed.
168 if (!tombstoned_connected) {
169 if (!tombstoned_connect(target, &tombstoned_socket, &output_fd)) {
170 // We failed to connect, not much we can do.
171 LOG(ERROR) << "failed to connected to tombstoned to report failure";
172 _exit(1);
173 }
174 }
175
176 dprintf(output_fd.get(), "crash_dump failed to dump process %d: %s\n", target, abort_msg);
177
178 // Don't dump ourselves.
179 _exit(1);
180}
181
182static void check_process(int proc_fd, pid_t expected_pid) {
183 android::procinfo::ProcessInfo proc_info;
184 if (!android::procinfo::GetProcessInfoFromProcPidFd(proc_fd, &proc_info)) {
185 LOG(FATAL) << "failed to fetch process info";
186 }
187
188 if (proc_info.pid != expected_pid) {
189 LOG(FATAL) << "pid mismatch: expected " << expected_pid << ", actual " << proc_info.ppid;
190 }
191}
192
193int main(int argc, char** argv) {
194 pid_t target = getppid();
195 bool tombstoned_connected = false;
196 unique_fd tombstoned_socket;
197 unique_fd output_fd;
198
199 android::base::InitLogging(argv);
200 android::base::SetAborter([&](const char* abort_msg) {
201 abort_handler(target, tombstoned_connected, tombstoned_socket, output_fd, abort_msg);
202 });
203
204 if (argc != 2) {
205 return 1;
206 }
207
208 pid_t main_tid;
209
210 if (target == 1) {
211 LOG(FATAL) << "target died before we could attach";
212 }
213
214 if (!android::base::ParseInt(argv[1], &main_tid, 1, std::numeric_limits<pid_t>::max())) {
215 LOG(FATAL) << "invalid main tid: " << argv[1];
216 }
217
218 android::procinfo::ProcessInfo target_info;
219 if (!android::procinfo::GetProcessInfo(main_tid, &target_info)) {
220 LOG(FATAL) << "failed to fetch process info for target " << main_tid;
221 }
222
223 if (main_tid != target_info.tid || target != target_info.pid) {
224 LOG(FATAL) << "target info mismatch, expected pid " << target << ", tid " << main_tid
225 << ", received pid " << target_info.pid << ", tid " << target_info.tid;
226 }
227
228 // Open /proc/`getppid()` in the original process, and pass it down to the forked child.
229 std::string target_proc_path = "/proc/" + std::to_string(target);
230 int target_proc_fd = open(target_proc_path.c_str(), O_DIRECTORY | O_RDONLY);
231 if (target_proc_fd == -1) {
232 PLOG(FATAL) << "failed to open " << target_proc_path;
233 }
234
235 // Reparent ourselves to init, so that the signal handler can waitpid on the
236 // original process to avoid leaving a zombie for non-fatal dumps.
237 pid_t forkpid = fork();
238 if (forkpid == -1) {
239 PLOG(FATAL) << "fork failed";
240 } else if (forkpid != 0) {
241 exit(0);
242 }
243
244 check_process(target_proc_fd, target);
245
Josh Gao42fd74b2017-01-20 12:51:11 -0800246 std::string attach_error;
247 if (!ptrace_attach_thread(target, main_tid, &attach_error)) {
248 LOG(FATAL) << attach_error;
Josh Gaocbe70cb2016-10-18 18:17:52 -0700249 }
250
251 check_process(target_proc_fd, target);
252
253 LOG(INFO) << "obtaining output fd from tombstoned";
254 tombstoned_connected = tombstoned_connect(target, &tombstoned_socket, &output_fd);
255
256 // Write a '\1' to stdout to tell the crashing process to resume.
257 if (TEMP_FAILURE_RETRY(write(STDOUT_FILENO, "\1", 1)) == -1) {
258 PLOG(ERROR) << "failed to communicate to target process";
259 }
260
261 if (tombstoned_connected) {
262 if (TEMP_FAILURE_RETRY(dup2(output_fd.get(), STDOUT_FILENO)) == -1) {
263 PLOG(ERROR) << "failed to dup2 output fd (" << output_fd.get() << ") to STDOUT_FILENO";
264 }
265 } else {
266 unique_fd devnull(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
267 TEMP_FAILURE_RETRY(dup2(devnull.get(), STDOUT_FILENO));
268 }
269
Josh Gaocbe70cb2016-10-18 18:17:52 -0700270 LOG(INFO) << "performing dump of process " << target << " (target tid = " << main_tid << ")";
271
272 // At this point, the thread that made the request has been PTRACE_ATTACHed
273 // and has the signal that triggered things queued. Send PTRACE_CONT, and
274 // then wait for the signal.
275 if (ptrace(PTRACE_CONT, main_tid, 0, 0) != 0) {
276 PLOG(ERROR) << "PTRACE_CONT(" << main_tid << ") failed";
277 exit(1);
278 }
279
280 siginfo_t siginfo = {};
281 if (!wait_for_signal(main_tid, &siginfo)) {
282 printf("failed to wait for signal in tid %d: %s\n", main_tid, strerror(errno));
283 exit(1);
284 }
285
286 int signo = siginfo.si_signo;
287 bool backtrace = false;
288 uintptr_t abort_address = 0;
289
290 // si_value can represent three things:
291 // 0: dump tombstone
292 // 1: dump backtrace
293 // everything else: abort message address (implies dump tombstone)
294 if (siginfo.si_value.sival_int == 1) {
295 backtrace = true;
296 } else if (siginfo.si_value.sival_ptr != nullptr) {
297 abort_address = reinterpret_cast<uintptr_t>(siginfo.si_value.sival_ptr);
298 }
299
300 // Now that we have the signal that kicked things off, attach all of the
301 // sibling threads, and then proceed.
302 bool fatal_signal = signo != DEBUGGER_SIGNAL;
303 int resume_signal = fatal_signal ? signo : 0;
304 std::set<pid_t> siblings;
Josh Gao42fd74b2017-01-20 12:51:11 -0800305 std::set<pid_t> attached_siblings;
Josh Gaocbe70cb2016-10-18 18:17:52 -0700306 if (resume_signal == 0) {
307 if (!android::procinfo::GetProcessTids(target, &siblings)) {
308 PLOG(FATAL) << "failed to get process siblings";
309 }
310 siblings.erase(main_tid);
311
312 for (pid_t sibling_tid : siblings) {
Josh Gao42fd74b2017-01-20 12:51:11 -0800313 if (!ptrace_attach_thread(target, sibling_tid, &attach_error)) {
314 LOG(WARNING) << attach_error;
315 } else {
316 attached_siblings.insert(sibling_tid);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700317 }
318 }
319 }
320
321 check_process(target_proc_fd, target);
322
323 // TODO: Use seccomp to lock ourselves down.
324
325 std::unique_ptr<BacktraceMap> backtrace_map(BacktraceMap::Create(main_tid));
326 std::string amfd_data;
327
328 if (backtrace) {
Josh Gao42fd74b2017-01-20 12:51:11 -0800329 dump_backtrace(output_fd.get(), backtrace_map.get(), target, main_tid, attached_siblings, 0);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700330 } else {
331 // Collect the list of open files.
332 OpenFilesList open_files;
333 populate_open_files_list(target, &open_files);
334
Josh Gao42fd74b2017-01-20 12:51:11 -0800335 engrave_tombstone(output_fd.get(), backtrace_map.get(), open_files, target, main_tid,
336 attached_siblings, abort_address, fatal_signal ? &amfd_data : nullptr);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700337 }
338
339 bool wait_for_gdb = android::base::GetBoolProperty("debug.debuggerd.wait_for_gdb", false);
340 if (wait_for_gdb) {
341 // Don't wait_for_gdb when the process didn't actually crash.
342 if (!fatal_signal) {
343 wait_for_gdb = false;
344 } else {
345 // Use ALOGI to line up with output from engrave_tombstone.
346 ALOGI(
347 "***********************************************************\n"
348 "* Process %d has been suspended while crashing.\n"
349 "* To attach gdbserver and start gdb, run this on the host:\n"
350 "*\n"
351 "* gdbclient.py -p %d\n"
352 "*\n"
353 "***********************************************************",
354 target, main_tid);
355 }
356 }
357
Josh Gao42fd74b2017-01-20 12:51:11 -0800358 for (pid_t tid : attached_siblings) {
Josh Gaocbe70cb2016-10-18 18:17:52 -0700359 // Don't send the signal to sibling threads.
360 if (ptrace(PTRACE_DETACH, tid, 0, wait_for_gdb ? SIGSTOP : 0) != 0) {
361 PLOG(ERROR) << "ptrace detach from " << tid << " failed";
362 }
363 }
364
365 if (ptrace(PTRACE_DETACH, main_tid, 0, wait_for_gdb ? SIGSTOP : resume_signal)) {
366 PLOG(ERROR) << "ptrace detach from main thread " << main_tid << " failed";
367 }
368
369 if (wait_for_gdb) {
370 if (tgkill(target, main_tid, resume_signal) != 0) {
371 PLOG(ERROR) << "failed to resend signal to process " << target;
372 }
373 }
374
375 if (fatal_signal) {
376 activity_manager_notify(target, signo, amfd_data);
377 }
378
379 // Close stdout before we notify tombstoned of completion.
380 close(STDOUT_FILENO);
381 if (!tombstoned_notify_completion(tombstoned_socket.get())) {
382 LOG(ERROR) << "failed to notify tombstoned of completion";
383 }
384
385 return 0;
386}