1 /*
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 <fcntl.h>
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <sys/stat.h>
21 #include <sys/types.h>
22 #include <unistd.h>
23
24 #include <array>
25 #include <deque>
26 #include <string>
27 #include <unordered_map>
28 #include <utility>
29
30 #include <event2/event.h>
31 #include <event2/listener.h>
32 #include <event2/thread.h>
33
34 #include <android-base/cmsg.h>
35 #include <android-base/logging.h>
36 #include <android-base/properties.h>
37 #include <android-base/stringprintf.h>
38 #include <android-base/unique_fd.h>
39 #include <cutils/sockets.h>
40
41 #include "debuggerd/handler.h"
42 #include "dump_type.h"
43 #include "protocol.h"
44 #include "util.h"
45
46 #include "intercept_manager.h"
47
48 using android::base::GetIntProperty;
49 using android::base::SendFileDescriptors;
50 using android::base::StringPrintf;
51
52 using android::base::borrowed_fd;
53 using android::base::unique_fd;
54
55 static InterceptManager* intercept_manager;
56
57 enum CrashStatus {
58 kCrashStatusRunning,
59 kCrashStatusQueued,
60 };
61
62 struct CrashArtifact {
63 unique_fd fd;
64
devnullCrashArtifact65 static CrashArtifact devnull() {
66 CrashArtifact result;
67 result.fd.reset(open("/dev/null", O_WRONLY | O_CLOEXEC));
68 return result;
69 }
70 };
71
72 struct CrashArtifactPaths {
73 std::string text;
74 std::optional<std::string> proto;
75 };
76
77 struct CrashOutput {
78 CrashArtifact text;
79 std::optional<CrashArtifact> proto;
80 };
81
82 // Ownership of Crash is a bit messy.
83 // It's either owned by an active event that must have a timeout, or owned by
84 // queued_requests, in the case that multiple crashes come in at the same time.
85 struct Crash {
~CrashCrash86 ~Crash() { event_free(crash_event); }
87
88 CrashOutput output;
89 unique_fd crash_socket_fd;
90 pid_t crash_pid;
91 event* crash_event = nullptr;
92
93 DebuggerdDumpType crash_type;
94 };
95
96 class CrashQueue {
97 public:
CrashQueue(const std::string & dir_path,const std::string & file_name_prefix,size_t max_artifacts,size_t max_concurrent_dumps,bool supports_proto,bool world_readable)98 CrashQueue(const std::string& dir_path, const std::string& file_name_prefix, size_t max_artifacts,
99 size_t max_concurrent_dumps, bool supports_proto, bool world_readable)
100 : file_name_prefix_(file_name_prefix),
101 dir_path_(dir_path),
102 dir_fd_(open(dir_path.c_str(), O_DIRECTORY | O_RDONLY | O_CLOEXEC)),
103 max_artifacts_(max_artifacts),
104 next_artifact_(0),
105 max_concurrent_dumps_(max_concurrent_dumps),
106 num_concurrent_dumps_(0),
107 supports_proto_(supports_proto),
108 world_readable_(world_readable) {
109 if (dir_fd_ == -1) {
110 PLOG(FATAL) << "failed to open directory: " << dir_path;
111 }
112
113 // NOTE: If max_artifacts_ <= max_concurrent_dumps_, then theoretically the
114 // same filename could be handed out to multiple processes.
115 CHECK(max_artifacts_ > max_concurrent_dumps_);
116
117 find_oldest_artifact();
118 }
119
for_crash(const Crash * crash)120 static CrashQueue* for_crash(const Crash* crash) {
121 return (crash->crash_type == kDebuggerdJavaBacktrace) ? for_anrs() : for_tombstones();
122 }
123
for_crash(const std::unique_ptr<Crash> & crash)124 static CrashQueue* for_crash(const std::unique_ptr<Crash>& crash) {
125 return for_crash(crash.get());
126 }
127
for_tombstones()128 static CrashQueue* for_tombstones() {
129 static CrashQueue queue("/data/tombstones", "tombstone_" /* file_name_prefix */,
130 GetIntProperty("tombstoned.max_tombstone_count", 32),
131 1 /* max_concurrent_dumps */, true /* supports_proto */,
132 true /* world_readable */);
133 return &queue;
134 }
135
for_anrs()136 static CrashQueue* for_anrs() {
137 static CrashQueue queue("/data/anr", "trace_" /* file_name_prefix */,
138 GetIntProperty("tombstoned.max_anr_count", 64),
139 4 /* max_concurrent_dumps */, false /* supports_proto */,
140 false /* world_readable */);
141 return &queue;
142 }
143
create_temporary_file() const144 CrashArtifact create_temporary_file() const {
145 CrashArtifact result;
146
147 result.fd.reset(openat(dir_fd_, ".", O_WRONLY | O_APPEND | O_TMPFILE | O_CLOEXEC, 0660));
148 if (result.fd == -1) {
149 PLOG(FATAL) << "failed to create temporary tombstone in " << dir_path_;
150 }
151
152 if (world_readable_) {
153 // We need to fchmodat after creating to avoid getting the umask applied.
154 std::string fd_path = StringPrintf("/proc/self/fd/%d", result.fd.get());
155 if (fchmodat(dir_fd_, fd_path.c_str(), 0664, 0) != 0) {
156 PLOG(ERROR) << "Failed to make tombstone world-readable";
157 }
158 }
159
160 return result;
161 }
162
get_output(DebuggerdDumpType dump_type)163 std::optional<CrashOutput> get_output(DebuggerdDumpType dump_type) {
164 CrashOutput result;
165
166 switch (dump_type) {
167 case kDebuggerdNativeBacktrace:
168 // Don't generate tombstones for native backtrace requests.
169 return {};
170
171 case kDebuggerdTombstoneProto:
172 if (!supports_proto_) {
173 LOG(ERROR) << "received kDebuggerdTombstoneProto on a queue that doesn't support proto";
174 return {};
175 }
176 result.proto = create_temporary_file();
177 result.text = create_temporary_file();
178 break;
179
180 case kDebuggerdJavaBacktrace:
181 case kDebuggerdTombstone:
182 result.text = create_temporary_file();
183 break;
184
185 default:
186 LOG(ERROR) << "unexpected dump type: " << dump_type;
187 return {};
188 }
189
190 return result;
191 }
192
dir_fd()193 borrowed_fd dir_fd() { return dir_fd_; }
194
get_next_artifact_paths()195 CrashArtifactPaths get_next_artifact_paths() {
196 CrashArtifactPaths result;
197 result.text = StringPrintf("%s%02d", file_name_prefix_.c_str(), next_artifact_);
198
199 if (supports_proto_) {
200 result.proto = StringPrintf("%s%02d.pb", file_name_prefix_.c_str(), next_artifact_);
201 }
202
203 next_artifact_ = (next_artifact_ + 1) % max_artifacts_;
204 return result;
205 }
206
207 // Consumes crash if it returns true, otherwise leaves it untouched.
maybe_enqueue_crash(std::unique_ptr<Crash> && crash)208 bool maybe_enqueue_crash(std::unique_ptr<Crash>&& crash) {
209 if (num_concurrent_dumps_ == max_concurrent_dumps_) {
210 queued_requests_.emplace_back(std::move(crash));
211 return true;
212 }
213
214 return false;
215 }
216
maybe_dequeue_crashes(void (* handler)(std::unique_ptr<Crash> crash))217 void maybe_dequeue_crashes(void (*handler)(std::unique_ptr<Crash> crash)) {
218 while (!queued_requests_.empty() && num_concurrent_dumps_ < max_concurrent_dumps_) {
219 std::unique_ptr<Crash> next_crash = std::move(queued_requests_.front());
220 queued_requests_.pop_front();
221 handler(std::move(next_crash));
222 }
223 }
224
on_crash_started()225 void on_crash_started() { ++num_concurrent_dumps_; }
226
on_crash_completed()227 void on_crash_completed() { --num_concurrent_dumps_; }
228
229 private:
find_oldest_artifact()230 void find_oldest_artifact() {
231 size_t oldest_tombstone = 0;
232 time_t oldest_time = std::numeric_limits<time_t>::max();
233
234 for (size_t i = 0; i < max_artifacts_; ++i) {
235 std::string path =
236 StringPrintf("%s/%s%02zu", dir_path_.c_str(), file_name_prefix_.c_str(), i);
237 struct stat st;
238 if (stat(path.c_str(), &st) != 0) {
239 if (errno == ENOENT) {
240 oldest_tombstone = i;
241 break;
242 } else {
243 PLOG(ERROR) << "failed to stat " << path;
244 continue;
245 }
246 }
247
248 if (st.st_mtime < oldest_time) {
249 oldest_tombstone = i;
250 oldest_time = st.st_mtime;
251 }
252 }
253
254 next_artifact_ = oldest_tombstone;
255 }
256
257 const std::string file_name_prefix_;
258
259 const std::string dir_path_;
260 const int dir_fd_;
261
262 const size_t max_artifacts_;
263 int next_artifact_;
264
265 const size_t max_concurrent_dumps_;
266 size_t num_concurrent_dumps_;
267
268 bool supports_proto_;
269 bool world_readable_;
270
271 std::deque<std::unique_ptr<Crash>> queued_requests_;
272
273 DISALLOW_COPY_AND_ASSIGN(CrashQueue);
274 };
275
276 // Whether java trace dumps are produced via tombstoned.
277 static constexpr bool kJavaTraceDumpsEnabled = true;
278
279 // Forward declare the callbacks so they can be placed in a sensible order.
280 static void crash_accept_cb(evconnlistener* listener, evutil_socket_t sockfd, sockaddr*, int,
281 void*);
282 static void crash_request_cb(evutil_socket_t sockfd, short ev, void* arg);
283 static void crash_completed_cb(evutil_socket_t sockfd, short ev, void* arg);
284
perform_request(std::unique_ptr<Crash> crash)285 static void perform_request(std::unique_ptr<Crash> crash) {
286 unique_fd output_fd;
287 if (intercept_manager->FindIntercept(crash->crash_pid, crash->crash_type, &output_fd)) {
288 if (crash->crash_type == kDebuggerdTombstoneProto) {
289 crash->output.proto = CrashArtifact::devnull();
290 }
291 } else {
292 if (auto o = CrashQueue::for_crash(crash.get())->get_output(crash->crash_type); o) {
293 crash->output = std::move(*o);
294 output_fd.reset(dup(crash->output.text.fd));
295 } else {
296 LOG(ERROR) << "failed to get crash output for type " << crash->crash_type;
297 return;
298 }
299 }
300
301 TombstonedCrashPacket response = {.packet_type = CrashPacketType::kPerformDump};
302
303 ssize_t rc = -1;
304 if (crash->output.proto) {
305 rc = SendFileDescriptors(crash->crash_socket_fd, &response, sizeof(response), output_fd.get(),
306 crash->output.proto->fd.get());
307 } else {
308 rc = SendFileDescriptors(crash->crash_socket_fd, &response, sizeof(response), output_fd.get());
309 }
310
311 output_fd.reset();
312
313 if (rc == -1) {
314 PLOG(WARNING) << "failed to send response to CrashRequest";
315 return;
316 } else if (rc != sizeof(response)) {
317 PLOG(WARNING) << "crash socket write returned short";
318 return;
319 }
320
321 // TODO: Make this configurable by the interceptor?
322 struct timeval timeout = {10 * android::base::HwTimeoutMultiplier(), 0};
323
324 event_base* base = event_get_base(crash->crash_event);
325
326 event_assign(crash->crash_event, base, crash->crash_socket_fd, EV_TIMEOUT | EV_READ,
327 crash_completed_cb, crash.get());
328 event_add(crash->crash_event, &timeout);
329 CrashQueue::for_crash(crash)->on_crash_started();
330
331 // The crash is now owned by the event loop.
332 crash.release();
333 }
334
crash_accept_cb(evconnlistener * listener,evutil_socket_t sockfd,sockaddr *,int,void *)335 static void crash_accept_cb(evconnlistener* listener, evutil_socket_t sockfd, sockaddr*, int,
336 void*) {
337 event_base* base = evconnlistener_get_base(listener);
338 Crash* crash = new Crash();
339
340 // TODO: Make sure that only java crashes come in on the java socket
341 // and only native crashes on the native socket.
342 struct timeval timeout = {1 * android::base::HwTimeoutMultiplier(), 0};
343 event* crash_event = event_new(base, sockfd, EV_TIMEOUT | EV_READ, crash_request_cb, crash);
344 crash->crash_socket_fd.reset(sockfd);
345 crash->crash_event = crash_event;
346 event_add(crash_event, &timeout);
347 }
348
crash_request_cb(evutil_socket_t sockfd,short ev,void * arg)349 static void crash_request_cb(evutil_socket_t sockfd, short ev, void* arg) {
350 std::unique_ptr<Crash> crash(static_cast<Crash*>(arg));
351 TombstonedCrashPacket request = {};
352
353 if ((ev & EV_TIMEOUT) != 0) {
354 LOG(WARNING) << "crash request timed out";
355 return;
356 } else if ((ev & EV_READ) == 0) {
357 LOG(WARNING) << "tombstoned received unexpected event from crash socket";
358 return;
359 }
360
361 ssize_t rc = TEMP_FAILURE_RETRY(read(sockfd, &request, sizeof(request)));
362 if (rc == -1) {
363 PLOG(WARNING) << "failed to read from crash socket";
364 return;
365 } else if (rc != sizeof(request)) {
366 LOG(WARNING) << "crash socket received short read of length " << rc << " (expected "
367 << sizeof(request) << ")";
368 return;
369 }
370
371 if (request.packet_type != CrashPacketType::kDumpRequest) {
372 LOG(WARNING) << "unexpected crash packet type, expected kDumpRequest, received "
373 << StringPrintf("%#2hhX", request.packet_type);
374 return;
375 }
376
377 crash->crash_type = request.packet.dump_request.dump_type;
378 if (crash->crash_type < 0 || crash->crash_type > kDebuggerdTombstoneProto) {
379 LOG(WARNING) << "unexpected crash dump type: " << crash->crash_type;
380 return;
381 }
382
383 if (crash->crash_type != kDebuggerdJavaBacktrace) {
384 crash->crash_pid = request.packet.dump_request.pid;
385 } else {
386 // Requests for java traces are sent from untrusted processes, so we
387 // must not trust the PID sent down with the request. Instead, we ask the
388 // kernel.
389 ucred cr = {};
390 socklen_t len = sizeof(cr);
391 int ret = getsockopt(sockfd, SOL_SOCKET, SO_PEERCRED, &cr, &len);
392 if (ret != 0) {
393 PLOG(ERROR) << "Failed to getsockopt(..SO_PEERCRED)";
394 return;
395 }
396
397 crash->crash_pid = cr.pid;
398 }
399
400 pid_t crash_pid = crash->crash_pid;
401 LOG(INFO) << "received crash request for pid " << crash_pid;
402
403 if (CrashQueue::for_crash(crash)->maybe_enqueue_crash(std::move(crash))) {
404 LOG(INFO) << "enqueueing crash request for pid " << crash_pid;
405 } else {
406 perform_request(std::move(crash));
407 }
408 }
409
rename_tombstone_fd(borrowed_fd fd,borrowed_fd dirfd,const std::string & path)410 static bool rename_tombstone_fd(borrowed_fd fd, borrowed_fd dirfd, const std::string& path) {
411 // Always try to unlink the tombstone file.
412 // linkat doesn't let us replace a file, so we need to unlink before linking
413 // our results onto disk, and if we fail for some reason, we should delete
414 // stale tombstones to avoid confusing inconsistency.
415 int rc = unlinkat(dirfd.get(), path.c_str(), 0);
416 if (rc != 0 && errno != ENOENT) {
417 PLOG(ERROR) << "failed to unlink tombstone at " << path;
418 return false;
419 }
420
421 // This fd is created inside of dirfd in CrashQueue::create_temporary_file.
422 std::string fd_path = StringPrintf("/proc/self/fd/%d", fd.get());
423 rc = linkat(AT_FDCWD, fd_path.c_str(), dirfd.get(), path.c_str(), AT_SYMLINK_FOLLOW);
424 if (rc != 0) {
425 PLOG(ERROR) << "failed to link tombstone at " << path;
426 return false;
427 }
428 return true;
429 }
430
crash_completed(borrowed_fd sockfd,std::unique_ptr<Crash> crash)431 static void crash_completed(borrowed_fd sockfd, std::unique_ptr<Crash> crash) {
432 TombstonedCrashPacket request = {};
433 CrashQueue* queue = CrashQueue::for_crash(crash);
434
435 ssize_t rc = TEMP_FAILURE_RETRY(read(sockfd.get(), &request, sizeof(request)));
436 if (rc == -1) {
437 PLOG(WARNING) << "failed to read from crash socket";
438 return;
439 } else if (rc != sizeof(request)) {
440 LOG(WARNING) << "crash socket received short read of length " << rc << " (expected "
441 << sizeof(request) << ")";
442 return;
443 }
444
445 if (request.packet_type != CrashPacketType::kCompletedDump) {
446 LOG(WARNING) << "unexpected crash packet type, expected kCompletedDump, received "
447 << uint32_t(request.packet_type);
448 return;
449 }
450
451 if (crash->output.text.fd == -1) {
452 LOG(WARNING) << "skipping tombstone file creation due to intercept";
453 return;
454 }
455
456 CrashArtifactPaths paths = queue->get_next_artifact_paths();
457
458 if (crash->output.proto && crash->output.proto->fd != -1) {
459 if (!paths.proto) {
460 LOG(ERROR) << "missing path for proto tombstone";
461 } else {
462 rename_tombstone_fd(crash->output.proto->fd, queue->dir_fd(), *paths.proto);
463 }
464 }
465
466 if (rename_tombstone_fd(crash->output.text.fd, queue->dir_fd(), paths.text)) {
467 if (crash->crash_type == kDebuggerdJavaBacktrace) {
468 LOG(ERROR) << "Traces for pid " << crash->crash_pid << " written to: " << paths.text;
469 } else {
470 // NOTE: Several tools parse this log message to figure out where the
471 // tombstone associated with a given native crash was written. Any changes
472 // to this message must be carefully considered.
473 LOG(ERROR) << "Tombstone written to: " << paths.text;
474 }
475 }
476 }
477
crash_completed_cb(evutil_socket_t sockfd,short ev,void * arg)478 static void crash_completed_cb(evutil_socket_t sockfd, short ev, void* arg) {
479 std::unique_ptr<Crash> crash(static_cast<Crash*>(arg));
480 CrashQueue* queue = CrashQueue::for_crash(crash);
481
482 queue->on_crash_completed();
483
484 if ((ev & EV_READ) == EV_READ) {
485 crash_completed(sockfd, std::move(crash));
486 }
487
488 // If there's something queued up, let them proceed.
489 queue->maybe_dequeue_crashes(perform_request);
490 }
491
main(int,char * [])492 int main(int, char* []) {
493 umask(0117);
494
495 // Don't try to connect to ourselves if we crash.
496 struct sigaction action = {};
497 action.sa_handler = [](int signal) {
498 LOG(ERROR) << "received fatal signal " << signal;
499 _exit(1);
500 };
501 debuggerd_register_handlers(&action);
502
503 int intercept_socket = android_get_control_socket(kTombstonedInterceptSocketName);
504 int crash_socket = android_get_control_socket(kTombstonedCrashSocketName);
505
506 if (intercept_socket == -1 || crash_socket == -1) {
507 PLOG(FATAL) << "failed to get socket from init";
508 }
509
510 evutil_make_socket_nonblocking(intercept_socket);
511 evutil_make_socket_nonblocking(crash_socket);
512
513 event_base* base = event_base_new();
514 if (!base) {
515 LOG(FATAL) << "failed to create event_base";
516 }
517
518 intercept_manager = new InterceptManager(base, intercept_socket);
519
520 evconnlistener* tombstone_listener =
521 evconnlistener_new(base, crash_accept_cb, CrashQueue::for_tombstones(), LEV_OPT_CLOSE_ON_FREE,
522 -1 /* backlog */, crash_socket);
523 if (!tombstone_listener) {
524 LOG(FATAL) << "failed to create evconnlistener for tombstones.";
525 }
526
527 if (kJavaTraceDumpsEnabled) {
528 const int java_trace_socket = android_get_control_socket(kTombstonedJavaTraceSocketName);
529 if (java_trace_socket == -1) {
530 PLOG(FATAL) << "failed to get socket from init";
531 }
532
533 evutil_make_socket_nonblocking(java_trace_socket);
534 evconnlistener* java_trace_listener =
535 evconnlistener_new(base, crash_accept_cb, CrashQueue::for_anrs(), LEV_OPT_CLOSE_ON_FREE,
536 -1 /* backlog */, java_trace_socket);
537 if (!java_trace_listener) {
538 LOG(FATAL) << "failed to create evconnlistener for java traces.";
539 }
540 }
541
542 LOG(INFO) << "tombstoned successfully initialized";
543 event_base_dispatch(base);
544 }
545