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