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 <dirent.h>
18 #include <dlfcn.h>
19 #include <err.h>
20 #include <fcntl.h>
21 #include <malloc.h>
22 #include <stdlib.h>
23 #include <sys/capability.h>
24 #include <sys/mman.h>
25 #include <sys/prctl.h>
26 #include <sys/ptrace.h>
27 #include <sys/resource.h>
28 #include <sys/syscall.h>
29 #include <sys/types.h>
30 #include <unistd.h>
31
32 #include <chrono>
33 #include <regex>
34 #include <string>
35 #include <thread>
36
37 #include <android/fdsan.h>
38 #include <android/set_abort_message.h>
39 #include <bionic/malloc.h>
40 #include <bionic/mte.h>
41 #include <bionic/reserved_signals.h>
42
43 #include <android-base/cmsg.h>
44 #include <android-base/file.h>
45 #include <android-base/logging.h>
46 #include <android-base/macros.h>
47 #include <android-base/parseint.h>
48 #include <android-base/properties.h>
49 #include <android-base/stringprintf.h>
50 #include <android-base/strings.h>
51 #include <android-base/test_utils.h>
52 #include <android-base/unique_fd.h>
53 #include <cutils/sockets.h>
54 #include <gmock/gmock.h>
55 #include <gtest/gtest.h>
56
57 #include <libminijail.h>
58 #include <scoped_minijail.h>
59
60 #include "debuggerd/handler.h"
61 #include "libdebuggerd/utility.h"
62 #include "protocol.h"
63 #include "tombstoned/tombstoned.h"
64 #include "util.h"
65
66 using namespace std::chrono_literals;
67
68 using android::base::SendFileDescriptors;
69 using android::base::unique_fd;
70 using ::testing::HasSubstr;
71
72 #if defined(__LP64__)
73 #define ARCH_SUFFIX "64"
74 #else
75 #define ARCH_SUFFIX ""
76 #endif
77
78 constexpr char kWaitForDebuggerKey[] = "debug.debuggerd.wait_for_debugger";
79
80 #define TIMEOUT(seconds, expr) \
81 [&]() { \
82 struct sigaction old_sigaction; \
83 struct sigaction new_sigaction = {}; \
84 new_sigaction.sa_handler = [](int) {}; \
85 if (sigaction(SIGALRM, &new_sigaction, &new_sigaction) != 0) { \
86 err(1, "sigaction failed"); \
87 } \
88 alarm(seconds); \
89 auto value = expr; \
90 int saved_errno = errno; \
91 if (sigaction(SIGALRM, &old_sigaction, nullptr) != 0) { \
92 err(1, "sigaction failed"); \
93 } \
94 alarm(0); \
95 errno = saved_errno; \
96 return value; \
97 }()
98
99 // Backtrace frame dump could contain:
100 // #01 pc 0001cded /data/tmp/debuggerd_test32 (raise_debugger_signal+80)
101 // or
102 // #01 pc 00022a09 /data/tmp/debuggerd_test32 (offset 0x12000) (raise_debugger_signal+80)
103 #define ASSERT_BACKTRACE_FRAME(result, frame_name) \
104 ASSERT_MATCH(result, \
105 R"(#\d\d pc [0-9a-f]+\s+ \S+ (\(offset 0x[0-9a-f]+\) )?\()" frame_name R"(\+)");
106
107 // Enable GWP-ASan at the start of this process. GWP-ASan is enabled using
108 // process sampling, so we need to ensure we force GWP-ASan on.
enable_gwp_asan()109 __attribute__((constructor)) static void enable_gwp_asan() {
110 bool force = true;
111 android_mallopt(M_INITIALIZE_GWP_ASAN, &force, sizeof(force));
112 }
113
tombstoned_intercept(pid_t target_pid,unique_fd * intercept_fd,unique_fd * output_fd,InterceptStatus * status,DebuggerdDumpType intercept_type)114 static void tombstoned_intercept(pid_t target_pid, unique_fd* intercept_fd, unique_fd* output_fd,
115 InterceptStatus* status, DebuggerdDumpType intercept_type) {
116 intercept_fd->reset(socket_local_client(kTombstonedInterceptSocketName,
117 ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_SEQPACKET));
118 if (intercept_fd->get() == -1) {
119 FAIL() << "failed to contact tombstoned: " << strerror(errno);
120 }
121
122 InterceptRequest req = {
123 .dump_type = intercept_type,
124 .pid = target_pid,
125 };
126
127 unique_fd output_pipe_write;
128 if (!Pipe(output_fd, &output_pipe_write)) {
129 FAIL() << "failed to create output pipe: " << strerror(errno);
130 }
131
132 std::string pipe_size_str;
133 int pipe_buffer_size;
134 if (!android::base::ReadFileToString("/proc/sys/fs/pipe-max-size", &pipe_size_str)) {
135 FAIL() << "failed to read /proc/sys/fs/pipe-max-size: " << strerror(errno);
136 }
137
138 pipe_size_str = android::base::Trim(pipe_size_str);
139
140 if (!android::base::ParseInt(pipe_size_str.c_str(), &pipe_buffer_size, 0)) {
141 FAIL() << "failed to parse pipe max size";
142 }
143
144 if (fcntl(output_fd->get(), F_SETPIPE_SZ, pipe_buffer_size) != pipe_buffer_size) {
145 FAIL() << "failed to set pipe size: " << strerror(errno);
146 }
147
148 ASSERT_GE(pipe_buffer_size, 1024 * 1024);
149
150 ssize_t rc = SendFileDescriptors(intercept_fd->get(), &req, sizeof(req), output_pipe_write.get());
151 output_pipe_write.reset();
152 if (rc != sizeof(req)) {
153 FAIL() << "failed to send output fd to tombstoned: " << strerror(errno);
154 }
155
156 InterceptResponse response;
157 rc = TEMP_FAILURE_RETRY(read(intercept_fd->get(), &response, sizeof(response)));
158 if (rc == -1) {
159 FAIL() << "failed to read response from tombstoned: " << strerror(errno);
160 } else if (rc == 0) {
161 FAIL() << "failed to read response from tombstoned (EOF)";
162 } else if (rc != sizeof(response)) {
163 FAIL() << "received packet of unexpected length from tombstoned: expected " << sizeof(response)
164 << ", received " << rc;
165 }
166
167 *status = response.status;
168 }
169
170 class CrasherTest : public ::testing::Test {
171 public:
172 pid_t crasher_pid = -1;
173 bool previous_wait_for_debugger;
174 unique_fd crasher_pipe;
175 unique_fd intercept_fd;
176
177 CrasherTest();
178 ~CrasherTest();
179
180 void StartIntercept(unique_fd* output_fd, DebuggerdDumpType intercept_type = kDebuggerdTombstone);
181
182 // Returns -1 if we fail to read a response from tombstoned, otherwise the received return code.
183 void FinishIntercept(int* result);
184
185 void StartProcess(std::function<void()> function, std::function<pid_t()> forker = fork);
186 void StartCrasher(const std::string& crash_type);
187 void FinishCrasher();
188 void AssertDeath(int signo);
189
190 static void Trap(void* ptr);
191 };
192
CrasherTest()193 CrasherTest::CrasherTest() {
194 previous_wait_for_debugger = android::base::GetBoolProperty(kWaitForDebuggerKey, false);
195 android::base::SetProperty(kWaitForDebuggerKey, "0");
196
197 // Clear the old property too, just in case someone's been using it
198 // on this device. (We only document the new name, but we still support
199 // the old name so we don't break anyone's existing setups.)
200 android::base::SetProperty("debug.debuggerd.wait_for_gdb", "0");
201 }
202
~CrasherTest()203 CrasherTest::~CrasherTest() {
204 if (crasher_pid != -1) {
205 kill(crasher_pid, SIGKILL);
206 int status;
207 TEMP_FAILURE_RETRY(waitpid(crasher_pid, &status, WUNTRACED));
208 }
209
210 android::base::SetProperty(kWaitForDebuggerKey, previous_wait_for_debugger ? "1" : "0");
211 }
212
StartIntercept(unique_fd * output_fd,DebuggerdDumpType intercept_type)213 void CrasherTest::StartIntercept(unique_fd* output_fd, DebuggerdDumpType intercept_type) {
214 if (crasher_pid == -1) {
215 FAIL() << "crasher hasn't been started";
216 }
217
218 InterceptStatus status;
219 tombstoned_intercept(crasher_pid, &this->intercept_fd, output_fd, &status, intercept_type);
220 ASSERT_EQ(InterceptStatus::kRegistered, status);
221 }
222
FinishIntercept(int * result)223 void CrasherTest::FinishIntercept(int* result) {
224 InterceptResponse response;
225
226 ssize_t rc = TIMEOUT(30, read(intercept_fd.get(), &response, sizeof(response)));
227 if (rc == -1) {
228 FAIL() << "failed to read response from tombstoned: " << strerror(errno);
229 } else if (rc == 0) {
230 *result = -1;
231 } else if (rc != sizeof(response)) {
232 FAIL() << "received packet of unexpected length from tombstoned: expected " << sizeof(response)
233 << ", received " << rc;
234 } else {
235 *result = response.status == InterceptStatus::kStarted ? 1 : 0;
236 }
237 }
238
StartProcess(std::function<void ()> function,std::function<pid_t ()> forker)239 void CrasherTest::StartProcess(std::function<void()> function, std::function<pid_t()> forker) {
240 unique_fd read_pipe;
241 unique_fd crasher_read_pipe;
242 if (!Pipe(&crasher_read_pipe, &crasher_pipe)) {
243 FAIL() << "failed to create pipe: " << strerror(errno);
244 }
245
246 crasher_pid = forker();
247 if (crasher_pid == -1) {
248 FAIL() << "fork failed: " << strerror(errno);
249 } else if (crasher_pid == 0) {
250 char dummy;
251 crasher_pipe.reset();
252 TEMP_FAILURE_RETRY(read(crasher_read_pipe.get(), &dummy, 1));
253 function();
254 _exit(0);
255 }
256 }
257
FinishCrasher()258 void CrasherTest::FinishCrasher() {
259 if (crasher_pipe == -1) {
260 FAIL() << "crasher pipe uninitialized";
261 }
262
263 ssize_t rc = TEMP_FAILURE_RETRY(write(crasher_pipe.get(), "\n", 1));
264 if (rc == -1) {
265 FAIL() << "failed to write to crasher pipe: " << strerror(errno);
266 } else if (rc == 0) {
267 FAIL() << "crasher pipe was closed";
268 }
269 }
270
AssertDeath(int signo)271 void CrasherTest::AssertDeath(int signo) {
272 int status;
273 pid_t pid = TIMEOUT(30, waitpid(crasher_pid, &status, 0));
274 if (pid != crasher_pid) {
275 printf("failed to wait for crasher (expected pid %d, return value %d): %s\n", crasher_pid, pid,
276 strerror(errno));
277 sleep(100);
278 FAIL() << "failed to wait for crasher: " << strerror(errno);
279 }
280
281 if (signo == 0) {
282 ASSERT_TRUE(WIFEXITED(status)) << "Terminated due to unexpected signal " << WTERMSIG(status);
283 ASSERT_EQ(0, WEXITSTATUS(signo));
284 } else {
285 ASSERT_FALSE(WIFEXITED(status));
286 ASSERT_TRUE(WIFSIGNALED(status)) << "crasher didn't terminate via a signal";
287 ASSERT_EQ(signo, WTERMSIG(status));
288 }
289 crasher_pid = -1;
290 }
291
ConsumeFd(unique_fd fd,std::string * output)292 static void ConsumeFd(unique_fd fd, std::string* output) {
293 constexpr size_t read_length = PAGE_SIZE;
294 std::string result;
295
296 while (true) {
297 size_t offset = result.size();
298 result.resize(result.size() + PAGE_SIZE);
299 ssize_t rc = TEMP_FAILURE_RETRY(read(fd.get(), &result[offset], read_length));
300 if (rc == -1) {
301 FAIL() << "read failed: " << strerror(errno);
302 } else if (rc == 0) {
303 result.resize(result.size() - PAGE_SIZE);
304 break;
305 }
306
307 result.resize(result.size() - PAGE_SIZE + rc);
308 }
309
310 *output = std::move(result);
311 }
312
313 class LogcatCollector {
314 public:
LogcatCollector()315 LogcatCollector() { system("logcat -c"); }
316
Collect(std::string * output)317 void Collect(std::string* output) {
318 FILE* cmd_stdout = popen("logcat -d '*:S DEBUG'", "r");
319 ASSERT_NE(cmd_stdout, nullptr);
320 unique_fd tmp_fd(TEMP_FAILURE_RETRY(dup(fileno(cmd_stdout))));
321 ConsumeFd(std::move(tmp_fd), output);
322 pclose(cmd_stdout);
323 }
324 };
325
TEST_F(CrasherTest,smoke)326 TEST_F(CrasherTest, smoke) {
327 int intercept_result;
328 unique_fd output_fd;
329 StartProcess([]() {
330 *reinterpret_cast<volatile char*>(0xdead) = '1';
331 });
332
333 StartIntercept(&output_fd);
334 FinishCrasher();
335 AssertDeath(SIGSEGV);
336 FinishIntercept(&intercept_result);
337
338 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
339
340 std::string result;
341 ConsumeFd(std::move(output_fd), &result);
342 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\), code 1 \(SEGV_MAPERR\), fault addr 0xdead)");
343
344 if (mte_supported()) {
345 // Test that the default TAGGED_ADDR_CTRL value is set.
346 ASSERT_MATCH(result, R"(tagged_addr_ctrl: 000000000007fff3)");
347 }
348 }
349
TEST_F(CrasherTest,tagged_fault_addr)350 TEST_F(CrasherTest, tagged_fault_addr) {
351 #if !defined(__aarch64__)
352 GTEST_SKIP() << "Requires aarch64";
353 #endif
354 int intercept_result;
355 unique_fd output_fd;
356 StartProcess([]() {
357 *reinterpret_cast<volatile char*>(0x100000000000dead) = '1';
358 });
359
360 StartIntercept(&output_fd);
361 FinishCrasher();
362 AssertDeath(SIGSEGV);
363 FinishIntercept(&intercept_result);
364
365 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
366
367 std::string result;
368 ConsumeFd(std::move(output_fd), &result);
369
370 // The address can either be tagged (new kernels) or untagged (old kernels).
371 ASSERT_MATCH(
372 result,
373 R"(signal 11 \(SIGSEGV\), code 1 \(SEGV_MAPERR\), fault addr (0x100000000000dead|0xdead))");
374 }
375
376 // Marked as weak to prevent the compiler from removing the malloc in the caller. In theory, the
377 // compiler could still clobber the argument register before trapping, but that's unlikely.
Trap(void * ptr ATTRIBUTE_UNUSED)378 __attribute__((weak)) void CrasherTest::Trap(void* ptr ATTRIBUTE_UNUSED) {
379 __builtin_trap();
380 }
381
TEST_F(CrasherTest,heap_addr_in_register)382 TEST_F(CrasherTest, heap_addr_in_register) {
383 #if defined(__i386__)
384 GTEST_SKIP() << "architecture does not pass arguments in registers";
385 #endif
386 int intercept_result;
387 unique_fd output_fd;
388 StartProcess([]() {
389 // Crash with a heap pointer in the first argument register.
390 Trap(malloc(1));
391 });
392
393 StartIntercept(&output_fd);
394 FinishCrasher();
395 int status;
396 ASSERT_EQ(crasher_pid, TIMEOUT(30, waitpid(crasher_pid, &status, 0)));
397 ASSERT_TRUE(WIFSIGNALED(status)) << "crasher didn't terminate via a signal";
398 // Don't test the signal number because different architectures use different signals for
399 // __builtin_trap().
400 FinishIntercept(&intercept_result);
401
402 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
403
404 std::string result;
405 ConsumeFd(std::move(output_fd), &result);
406
407 #if defined(__aarch64__)
408 ASSERT_MATCH(result, "memory near x0 \\(\\[anon:");
409 #elif defined(__arm__)
410 ASSERT_MATCH(result, "memory near r0 \\(\\[anon:");
411 #elif defined(__x86_64__)
412 ASSERT_MATCH(result, "memory near rdi \\(\\[anon:");
413 #else
414 ASSERT_TRUE(false) << "unsupported architecture";
415 #endif
416 }
417
418 #if defined(__aarch64__)
SetTagCheckingLevelSync()419 static void SetTagCheckingLevelSync() {
420 if (mallopt(M_BIONIC_SET_HEAP_TAGGING_LEVEL, M_HEAP_TAGGING_LEVEL_SYNC) == 0) {
421 abort();
422 }
423 }
424 #endif
425
426 // Number of iterations required to reliably guarantee a GWP-ASan crash.
427 // GWP-ASan's sample rate is not truly nondeterministic, it initialises a
428 // thread-local counter at 2*SampleRate, and decrements on each malloc(). Once
429 // the counter reaches zero, we provide a sampled allocation. Then, double that
430 // figure to allow for left/right allocation alignment, as this is done randomly
431 // without bias.
432 #define GWP_ASAN_ITERATIONS_TO_ENSURE_CRASH (0x20000)
433
434 struct GwpAsanTestParameters {
435 size_t alloc_size;
436 bool free_before_access;
437 int access_offset;
438 std::string cause_needle; // Needle to be found in the "Cause: [GWP-ASan]" line.
439 };
440
441 struct GwpAsanCrasherTest : CrasherTest, testing::WithParamInterface<GwpAsanTestParameters> {};
442
443 GwpAsanTestParameters gwp_asan_tests[] = {
444 {/* alloc_size */ 7, /* free_before_access */ true, /* access_offset */ 0, "Use After Free, 0 bytes into a 7-byte allocation"},
445 {/* alloc_size */ 7, /* free_before_access */ true, /* access_offset */ 1, "Use After Free, 1 byte into a 7-byte allocation"},
446 {/* alloc_size */ 7, /* free_before_access */ false, /* access_offset */ 16, "Buffer Overflow, 9 bytes right of a 7-byte allocation"},
447 {/* alloc_size */ 16, /* free_before_access */ false, /* access_offset */ -1, "Buffer Underflow, 1 byte left of a 16-byte allocation"},
448 };
449
450 INSTANTIATE_TEST_SUITE_P(GwpAsanTests, GwpAsanCrasherTest, testing::ValuesIn(gwp_asan_tests));
451
TEST_P(GwpAsanCrasherTest,gwp_asan_uaf)452 TEST_P(GwpAsanCrasherTest, gwp_asan_uaf) {
453 if (mte_supported()) {
454 // Skip this test on MTE hardware, as MTE will reliably catch these errors
455 // instead of GWP-ASan.
456 GTEST_SKIP() << "Skipped on MTE.";
457 }
458
459 GwpAsanTestParameters params = GetParam();
460 LogcatCollector logcat_collector;
461
462 int intercept_result;
463 unique_fd output_fd;
464 StartProcess([¶ms]() {
465 for (unsigned i = 0; i < GWP_ASAN_ITERATIONS_TO_ENSURE_CRASH; ++i) {
466 volatile char* p = reinterpret_cast<volatile char*>(malloc(params.alloc_size));
467 if (params.free_before_access) free(static_cast<void*>(const_cast<char*>(p)));
468 p[params.access_offset] = 42;
469 if (!params.free_before_access) free(static_cast<void*>(const_cast<char*>(p)));
470 }
471 });
472
473 StartIntercept(&output_fd);
474 FinishCrasher();
475 AssertDeath(SIGSEGV);
476 FinishIntercept(&intercept_result);
477
478 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
479
480 std::vector<std::string> log_sources(2);
481 ConsumeFd(std::move(output_fd), &log_sources[0]);
482 logcat_collector.Collect(&log_sources[1]);
483
484 for (const auto& result : log_sources) {
485 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\), code 2 \(SEGV_ACCERR\))");
486 ASSERT_MATCH(result, R"(Cause: \[GWP-ASan\]: )" + params.cause_needle);
487 if (params.free_before_access) {
488 ASSERT_MATCH(result, R"(deallocated by thread .*\n.*#00 pc)");
489 }
490 ASSERT_MATCH(result, R"((^|\s)allocated by thread .*\n.*#00 pc)");
491 }
492 }
493
494 struct SizeParamCrasherTest : CrasherTest, testing::WithParamInterface<size_t> {};
495
496 INSTANTIATE_TEST_SUITE_P(Sizes, SizeParamCrasherTest, testing::Values(0, 16, 131072));
497
TEST_P(SizeParamCrasherTest,mte_uaf)498 TEST_P(SizeParamCrasherTest, mte_uaf) {
499 #if defined(__aarch64__)
500 if (!mte_supported()) {
501 GTEST_SKIP() << "Requires MTE";
502 }
503
504 // Any UAF on a zero-sized allocation will be out-of-bounds so it won't be reported.
505 if (GetParam() == 0) {
506 return;
507 }
508
509 LogcatCollector logcat_collector;
510
511 int intercept_result;
512 unique_fd output_fd;
513 StartProcess([&]() {
514 SetTagCheckingLevelSync();
515 volatile int* p = (volatile int*)malloc(GetParam());
516 free((void *)p);
517 p[0] = 42;
518 });
519
520 StartIntercept(&output_fd);
521 FinishCrasher();
522 AssertDeath(SIGSEGV);
523 FinishIntercept(&intercept_result);
524
525 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
526
527 std::vector<std::string> log_sources(2);
528 ConsumeFd(std::move(output_fd), &log_sources[0]);
529 logcat_collector.Collect(&log_sources[1]);
530 // Tag dump only available in the tombstone, not logcat.
531 ASSERT_MATCH(log_sources[0], "Memory tags around the fault address");
532
533 for (const auto& result : log_sources) {
534 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\))");
535 ASSERT_MATCH(result, R"(Cause: \[MTE\]: Use After Free, 0 bytes into a )" +
536 std::to_string(GetParam()) + R"(-byte allocation)");
537 ASSERT_MATCH(result, R"(deallocated by thread .*?\n.*#00 pc)");
538 ASSERT_MATCH(result, R"((^|\s)allocated by thread .*?\n.*#00 pc)");
539 }
540 #else
541 GTEST_SKIP() << "Requires aarch64";
542 #endif
543 }
544
TEST_P(SizeParamCrasherTest,mte_oob_uaf)545 TEST_P(SizeParamCrasherTest, mte_oob_uaf) {
546 #if defined(__aarch64__)
547 if (!mte_supported()) {
548 GTEST_SKIP() << "Requires MTE";
549 }
550
551 int intercept_result;
552 unique_fd output_fd;
553 StartProcess([&]() {
554 SetTagCheckingLevelSync();
555 volatile int* p = (volatile int*)malloc(GetParam());
556 free((void *)p);
557 p[-1] = 42;
558 });
559
560 StartIntercept(&output_fd);
561 FinishCrasher();
562 AssertDeath(SIGSEGV);
563 FinishIntercept(&intercept_result);
564
565 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
566
567 std::string result;
568 ConsumeFd(std::move(output_fd), &result);
569
570 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\))");
571 ASSERT_NOT_MATCH(result, R"(Cause: \[MTE\]: Use After Free, 4 bytes left)");
572 #else
573 GTEST_SKIP() << "Requires aarch64";
574 #endif
575 }
576
TEST_P(SizeParamCrasherTest,mte_overflow)577 TEST_P(SizeParamCrasherTest, mte_overflow) {
578 #if defined(__aarch64__)
579 if (!mte_supported()) {
580 GTEST_SKIP() << "Requires MTE";
581 }
582
583 LogcatCollector logcat_collector;
584 int intercept_result;
585 unique_fd output_fd;
586 StartProcess([&]() {
587 SetTagCheckingLevelSync();
588 volatile char* p = (volatile char*)malloc(GetParam());
589 p[GetParam()] = 42;
590 });
591
592 StartIntercept(&output_fd);
593 FinishCrasher();
594 AssertDeath(SIGSEGV);
595 FinishIntercept(&intercept_result);
596
597 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
598
599 std::vector<std::string> log_sources(2);
600 ConsumeFd(std::move(output_fd), &log_sources[0]);
601 logcat_collector.Collect(&log_sources[1]);
602
603 // Tag dump only in tombstone, not logcat, and tagging is not used for
604 // overflow protection in the scudo secondary (guard pages are used instead).
605 if (GetParam() < 0x10000) {
606 ASSERT_MATCH(log_sources[0], "Memory tags around the fault address");
607 }
608
609 for (const auto& result : log_sources) {
610 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\))");
611 ASSERT_MATCH(result, R"(Cause: \[MTE\]: Buffer Overflow, 0 bytes right of a )" +
612 std::to_string(GetParam()) + R"(-byte allocation)");
613 ASSERT_MATCH(result, R"((^|\s)allocated by thread .*?\n.*#00 pc)");
614 }
615 #else
616 GTEST_SKIP() << "Requires aarch64";
617 #endif
618 }
619
TEST_P(SizeParamCrasherTest,mte_underflow)620 TEST_P(SizeParamCrasherTest, mte_underflow) {
621 #if defined(__aarch64__)
622 if (!mte_supported()) {
623 GTEST_SKIP() << "Requires MTE";
624 }
625
626 int intercept_result;
627 unique_fd output_fd;
628 StartProcess([&]() {
629 SetTagCheckingLevelSync();
630 volatile int* p = (volatile int*)malloc(GetParam());
631 p[-1] = 42;
632 });
633
634 StartIntercept(&output_fd);
635 FinishCrasher();
636 AssertDeath(SIGSEGV);
637 FinishIntercept(&intercept_result);
638
639 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
640
641 std::string result;
642 ConsumeFd(std::move(output_fd), &result);
643
644 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\), code 9 \(SEGV_MTESERR\))");
645 ASSERT_MATCH(result, R"(Cause: \[MTE\]: Buffer Underflow, 4 bytes left of a )" +
646 std::to_string(GetParam()) + R"(-byte allocation)");
647 ASSERT_MATCH(result, R"((^|\s)allocated by thread .*
648 #00 pc)");
649 ASSERT_MATCH(result, "Memory tags around the fault address");
650 #else
651 GTEST_SKIP() << "Requires aarch64";
652 #endif
653 }
654
TEST_F(CrasherTest,mte_multiple_causes)655 TEST_F(CrasherTest, mte_multiple_causes) {
656 #if defined(__aarch64__)
657 if (!mte_supported()) {
658 GTEST_SKIP() << "Requires MTE";
659 }
660
661 LogcatCollector logcat_collector;
662
663 int intercept_result;
664 unique_fd output_fd;
665 StartProcess([]() {
666 SetTagCheckingLevelSync();
667
668 // Make two allocations with the same tag and close to one another. Check for both properties
669 // with a bounds check -- this relies on the fact that only if the allocations have the same tag
670 // would they be measured as closer than 128 bytes to each other. Otherwise they would be about
671 // (some non-zero value << 56) apart.
672 //
673 // The out-of-bounds access will be considered either an overflow of one or an underflow of the
674 // other.
675 std::set<uintptr_t> allocs;
676 for (int i = 0; i != 4096; ++i) {
677 uintptr_t alloc = reinterpret_cast<uintptr_t>(malloc(16));
678 auto it = allocs.insert(alloc).first;
679 if (it != allocs.begin() && *std::prev(it) + 128 > alloc) {
680 *reinterpret_cast<int*>(*std::prev(it) + 16) = 42;
681 }
682 if (std::next(it) != allocs.end() && alloc + 128 > *std::next(it)) {
683 *reinterpret_cast<int*>(alloc + 16) = 42;
684 }
685 }
686 });
687
688 StartIntercept(&output_fd);
689 FinishCrasher();
690 AssertDeath(SIGSEGV);
691 FinishIntercept(&intercept_result);
692
693 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
694
695 std::vector<std::string> log_sources(2);
696 ConsumeFd(std::move(output_fd), &log_sources[0]);
697 logcat_collector.Collect(&log_sources[1]);
698
699 // Tag dump only in the tombstone, not logcat.
700 ASSERT_MATCH(log_sources[0], "Memory tags around the fault address");
701
702 for (const auto& result : log_sources) {
703 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\))");
704 ASSERT_THAT(result, HasSubstr("Note: multiple potential causes for this crash were detected, "
705 "listing them in decreasing order of probability."));
706 // Adjacent untracked allocations may cause us to see the wrong underflow here (or only
707 // overflows), so we can't match explicitly for an underflow message.
708 ASSERT_MATCH(result,
709 R"(Cause: \[MTE\]: Buffer Overflow, 0 bytes right of a 16-byte allocation)");
710 // Ensure there's at least two allocation traces (one for each cause).
711 ASSERT_MATCH(
712 result,
713 R"((^|\s)allocated by thread .*?\n.*#00 pc(.|\n)*?(^|\s)allocated by thread .*?\n.*#00 pc)");
714 }
715 #else
716 GTEST_SKIP() << "Requires aarch64";
717 #endif
718 }
719
720 #if defined(__aarch64__)
CreateTagMapping()721 static uintptr_t CreateTagMapping() {
722 // Some of the MTE tag dump tests assert that there is an inaccessible page to the left and right
723 // of the PROT_MTE page, so map three pages and set the two guard pages to PROT_NONE.
724 size_t page_size = getpagesize();
725 void* mapping = mmap(nullptr, page_size * 3, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
726 uintptr_t mapping_uptr = reinterpret_cast<uintptr_t>(mapping);
727 if (mapping == MAP_FAILED) {
728 return 0;
729 }
730 mprotect(reinterpret_cast<void*>(mapping_uptr + page_size), page_size,
731 PROT_READ | PROT_WRITE | PROT_MTE);
732 // Stripe the mapping, where even granules get tag '1', and odd granules get tag '0'.
733 for (uintptr_t offset = 0; offset < page_size; offset += 2 * kTagGranuleSize) {
734 uintptr_t tagged_addr = mapping_uptr + page_size + offset + (1ULL << 56);
735 __asm__ __volatile__(".arch_extension mte; stg %0, [%0]" : : "r"(tagged_addr) : "memory");
736 }
737 return mapping_uptr + page_size;
738 }
739 #endif
740
TEST_F(CrasherTest,mte_register_tag_dump)741 TEST_F(CrasherTest, mte_register_tag_dump) {
742 #if defined(__aarch64__)
743 if (!mte_supported()) {
744 GTEST_SKIP() << "Requires MTE";
745 }
746
747 int intercept_result;
748 unique_fd output_fd;
749 StartProcess([&]() {
750 SetTagCheckingLevelSync();
751 Trap(reinterpret_cast<void *>(CreateTagMapping()));
752 });
753
754 StartIntercept(&output_fd);
755 FinishCrasher();
756 AssertDeath(SIGTRAP);
757 FinishIntercept(&intercept_result);
758
759 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
760
761 std::string result;
762 ConsumeFd(std::move(output_fd), &result);
763
764 ASSERT_MATCH(result, R"(memory near x0:
765 .*
766 .*
767 01.............0 0000000000000000 0000000000000000 ................
768 00.............0)");
769 #else
770 GTEST_SKIP() << "Requires aarch64";
771 #endif
772 }
773
TEST_F(CrasherTest,mte_fault_tag_dump_front_truncated)774 TEST_F(CrasherTest, mte_fault_tag_dump_front_truncated) {
775 #if defined(__aarch64__)
776 if (!mte_supported()) {
777 GTEST_SKIP() << "Requires MTE";
778 }
779
780 int intercept_result;
781 unique_fd output_fd;
782 StartProcess([&]() {
783 SetTagCheckingLevelSync();
784 volatile char* p = reinterpret_cast<char*>(CreateTagMapping());
785 p[0] = 0; // Untagged pointer, tagged memory.
786 });
787
788 StartIntercept(&output_fd);
789 FinishCrasher();
790 AssertDeath(SIGSEGV);
791 FinishIntercept(&intercept_result);
792
793 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
794
795 std::string result;
796 ConsumeFd(std::move(output_fd), &result);
797
798 ASSERT_MATCH(result, R"(Memory tags around the fault address.*
799 \s*=>0x[0-9a-f]+000:\[1\] 0 1 0)");
800 #else
801 GTEST_SKIP() << "Requires aarch64";
802 #endif
803 }
804
TEST_F(CrasherTest,mte_fault_tag_dump)805 TEST_F(CrasherTest, mte_fault_tag_dump) {
806 #if defined(__aarch64__)
807 if (!mte_supported()) {
808 GTEST_SKIP() << "Requires MTE";
809 }
810
811 int intercept_result;
812 unique_fd output_fd;
813 StartProcess([&]() {
814 SetTagCheckingLevelSync();
815 volatile char* p = reinterpret_cast<char*>(CreateTagMapping());
816 p[320] = 0; // Untagged pointer, tagged memory.
817 });
818
819 StartIntercept(&output_fd);
820 FinishCrasher();
821 AssertDeath(SIGSEGV);
822 FinishIntercept(&intercept_result);
823
824 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
825
826 std::string result;
827 ConsumeFd(std::move(output_fd), &result);
828
829 ASSERT_MATCH(result, R"(Memory tags around the fault address.*
830 \s*0x[0-9a-f]+: 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0
831 \s*=>0x[0-9a-f]+: 1 0 1 0 \[1\] 0 1 0 1 0 1 0 1 0 1 0
832 \s*0x[0-9a-f]+: 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0
833 )");
834 #else
835 GTEST_SKIP() << "Requires aarch64";
836 #endif
837 }
838
TEST_F(CrasherTest,mte_fault_tag_dump_rear_truncated)839 TEST_F(CrasherTest, mte_fault_tag_dump_rear_truncated) {
840 #if defined(__aarch64__)
841 if (!mte_supported()) {
842 GTEST_SKIP() << "Requires MTE";
843 }
844
845 int intercept_result;
846 unique_fd output_fd;
847 StartProcess([&]() {
848 SetTagCheckingLevelSync();
849 size_t page_size = getpagesize();
850 volatile char* p = reinterpret_cast<char*>(CreateTagMapping());
851 p[page_size - kTagGranuleSize * 2] = 0; // Untagged pointer, tagged memory.
852 });
853
854 StartIntercept(&output_fd);
855 FinishCrasher();
856 AssertDeath(SIGSEGV);
857 FinishIntercept(&intercept_result);
858
859 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
860
861 std::string result;
862 ConsumeFd(std::move(output_fd), &result);
863
864 ASSERT_MATCH(result, R"(Memory tags around the fault address)");
865 ASSERT_MATCH(result,
866 R"(\s*0x[0-9a-f]+: 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0
867 \s*=>0x[0-9a-f]+: 1 0 1 0 1 0 1 0 1 0 1 0 1 0 \[1\] 0
868
869 )"); // Ensure truncation happened and there's a newline after the tag fault.
870 #else
871 GTEST_SKIP() << "Requires aarch64";
872 #endif
873 }
874
TEST_F(CrasherTest,LD_PRELOAD)875 TEST_F(CrasherTest, LD_PRELOAD) {
876 int intercept_result;
877 unique_fd output_fd;
878 StartProcess([]() {
879 setenv("LD_PRELOAD", "nonexistent.so", 1);
880 *reinterpret_cast<volatile char*>(0xdead) = '1';
881 });
882
883 StartIntercept(&output_fd);
884 FinishCrasher();
885 AssertDeath(SIGSEGV);
886 FinishIntercept(&intercept_result);
887
888 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
889
890 std::string result;
891 ConsumeFd(std::move(output_fd), &result);
892 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\), code 1 \(SEGV_MAPERR\), fault addr 0xdead)");
893 }
894
TEST_F(CrasherTest,abort)895 TEST_F(CrasherTest, abort) {
896 int intercept_result;
897 unique_fd output_fd;
898 StartProcess([]() {
899 abort();
900 });
901 StartIntercept(&output_fd);
902 FinishCrasher();
903 AssertDeath(SIGABRT);
904 FinishIntercept(&intercept_result);
905
906 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
907
908 std::string result;
909 ConsumeFd(std::move(output_fd), &result);
910 ASSERT_BACKTRACE_FRAME(result, "abort");
911 }
912
TEST_F(CrasherTest,signal)913 TEST_F(CrasherTest, signal) {
914 int intercept_result;
915 unique_fd output_fd;
916 StartProcess([]() {
917 while (true) {
918 sleep(1);
919 }
920 });
921 StartIntercept(&output_fd);
922 FinishCrasher();
923 ASSERT_EQ(0, kill(crasher_pid, SIGSEGV));
924
925 AssertDeath(SIGSEGV);
926 FinishIntercept(&intercept_result);
927
928 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
929
930 std::string result;
931 ConsumeFd(std::move(output_fd), &result);
932 ASSERT_MATCH(
933 result,
934 R"(signal 11 \(SIGSEGV\), code 0 \(SI_USER from pid \d+, uid \d+\), fault addr --------)");
935 ASSERT_MATCH(result, R"(backtrace:)");
936 }
937
TEST_F(CrasherTest,abort_message)938 TEST_F(CrasherTest, abort_message) {
939 int intercept_result;
940 unique_fd output_fd;
941 StartProcess([]() {
942 // Arrived at experimentally;
943 // logd truncates at 4062.
944 // strlen("Abort message: ''") is 17.
945 // That's 4045, but we also want a NUL.
946 char buf[4045 + 1];
947 memset(buf, 'x', sizeof(buf));
948 buf[sizeof(buf) - 1] = '\0';
949 android_set_abort_message(buf);
950 abort();
951 });
952 StartIntercept(&output_fd);
953 FinishCrasher();
954 AssertDeath(SIGABRT);
955 FinishIntercept(&intercept_result);
956
957 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
958
959 std::string result;
960 ConsumeFd(std::move(output_fd), &result);
961 ASSERT_MATCH(result, R"(Abort message: 'x{4045}')");
962 }
963
TEST_F(CrasherTest,abort_message_backtrace)964 TEST_F(CrasherTest, abort_message_backtrace) {
965 int intercept_result;
966 unique_fd output_fd;
967 StartProcess([]() {
968 android_set_abort_message("not actually aborting");
969 raise(BIONIC_SIGNAL_DEBUGGER);
970 exit(0);
971 });
972 StartIntercept(&output_fd);
973 FinishCrasher();
974 AssertDeath(0);
975 FinishIntercept(&intercept_result);
976
977 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
978
979 std::string result;
980 ConsumeFd(std::move(output_fd), &result);
981 ASSERT_NOT_MATCH(result, R"(Abort message:)");
982 }
983
TEST_F(CrasherTest,intercept_timeout)984 TEST_F(CrasherTest, intercept_timeout) {
985 int intercept_result;
986 unique_fd output_fd;
987 StartProcess([]() {
988 abort();
989 });
990 StartIntercept(&output_fd);
991
992 // Don't let crasher finish until we timeout.
993 FinishIntercept(&intercept_result);
994
995 ASSERT_NE(1, intercept_result) << "tombstoned reported success? (intercept_result = "
996 << intercept_result << ")";
997
998 FinishCrasher();
999 AssertDeath(SIGABRT);
1000 }
1001
TEST_F(CrasherTest,wait_for_debugger)1002 TEST_F(CrasherTest, wait_for_debugger) {
1003 if (!android::base::SetProperty(kWaitForDebuggerKey, "1")) {
1004 FAIL() << "failed to enable wait_for_debugger";
1005 }
1006 sleep(1);
1007
1008 StartProcess([]() {
1009 abort();
1010 });
1011 FinishCrasher();
1012
1013 int status;
1014 ASSERT_EQ(crasher_pid, TEMP_FAILURE_RETRY(waitpid(crasher_pid, &status, WUNTRACED)));
1015 ASSERT_TRUE(WIFSTOPPED(status));
1016 ASSERT_EQ(SIGSTOP, WSTOPSIG(status));
1017
1018 ASSERT_EQ(0, kill(crasher_pid, SIGCONT));
1019
1020 AssertDeath(SIGABRT);
1021 }
1022
TEST_F(CrasherTest,backtrace)1023 TEST_F(CrasherTest, backtrace) {
1024 std::string result;
1025 int intercept_result;
1026 unique_fd output_fd;
1027
1028 StartProcess([]() {
1029 abort();
1030 });
1031 StartIntercept(&output_fd, kDebuggerdNativeBacktrace);
1032
1033 std::this_thread::sleep_for(500ms);
1034
1035 sigval val;
1036 val.sival_int = 1;
1037 ASSERT_EQ(0, sigqueue(crasher_pid, BIONIC_SIGNAL_DEBUGGER, val)) << strerror(errno);
1038 FinishIntercept(&intercept_result);
1039 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1040 ConsumeFd(std::move(output_fd), &result);
1041 ASSERT_BACKTRACE_FRAME(result, "read");
1042
1043 int status;
1044 ASSERT_EQ(0, waitpid(crasher_pid, &status, WNOHANG | WUNTRACED));
1045
1046 StartIntercept(&output_fd);
1047 FinishCrasher();
1048 AssertDeath(SIGABRT);
1049 FinishIntercept(&intercept_result);
1050 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1051 ConsumeFd(std::move(output_fd), &result);
1052 ASSERT_BACKTRACE_FRAME(result, "abort");
1053 }
1054
TEST_F(CrasherTest,PR_SET_DUMPABLE_0_crash)1055 TEST_F(CrasherTest, PR_SET_DUMPABLE_0_crash) {
1056 int intercept_result;
1057 unique_fd output_fd;
1058 StartProcess([]() {
1059 prctl(PR_SET_DUMPABLE, 0);
1060 abort();
1061 });
1062
1063 StartIntercept(&output_fd);
1064 FinishCrasher();
1065 AssertDeath(SIGABRT);
1066 FinishIntercept(&intercept_result);
1067
1068 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1069
1070 std::string result;
1071 ConsumeFd(std::move(output_fd), &result);
1072 ASSERT_BACKTRACE_FRAME(result, "abort");
1073 }
1074
TEST_F(CrasherTest,capabilities)1075 TEST_F(CrasherTest, capabilities) {
1076 ASSERT_EQ(0U, getuid()) << "capability test requires root";
1077
1078 StartProcess([]() {
1079 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) != 0) {
1080 err(1, "failed to set PR_SET_KEEPCAPS");
1081 }
1082
1083 if (setresuid(1, 1, 1) != 0) {
1084 err(1, "setresuid failed");
1085 }
1086
1087 __user_cap_header_struct capheader;
1088 __user_cap_data_struct capdata[2];
1089 memset(&capheader, 0, sizeof(capheader));
1090 memset(&capdata, 0, sizeof(capdata));
1091
1092 capheader.version = _LINUX_CAPABILITY_VERSION_3;
1093 capheader.pid = 0;
1094
1095 // Turn on every third capability.
1096 static_assert(CAP_LAST_CAP > 33, "CAP_LAST_CAP <= 32");
1097 for (int i = 0; i < CAP_LAST_CAP; i += 3) {
1098 capdata[CAP_TO_INDEX(i)].permitted |= CAP_TO_MASK(i);
1099 capdata[CAP_TO_INDEX(i)].effective |= CAP_TO_MASK(i);
1100 }
1101
1102 // Make sure CAP_SYS_PTRACE is off.
1103 capdata[CAP_TO_INDEX(CAP_SYS_PTRACE)].permitted &= ~(CAP_TO_MASK(CAP_SYS_PTRACE));
1104 capdata[CAP_TO_INDEX(CAP_SYS_PTRACE)].effective &= ~(CAP_TO_MASK(CAP_SYS_PTRACE));
1105
1106 if (capset(&capheader, &capdata[0]) != 0) {
1107 err(1, "capset failed");
1108 }
1109
1110 if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_CLEAR_ALL, 0, 0, 0) != 0) {
1111 err(1, "failed to drop ambient capabilities");
1112 }
1113
1114 pthread_setname_np(pthread_self(), "thread_name");
1115 raise(SIGSYS);
1116 });
1117
1118 unique_fd output_fd;
1119 StartIntercept(&output_fd);
1120 FinishCrasher();
1121 AssertDeath(SIGSYS);
1122
1123 std::string result;
1124 int intercept_result;
1125 FinishIntercept(&intercept_result);
1126 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1127 ConsumeFd(std::move(output_fd), &result);
1128 ASSERT_MATCH(result, R"(name: thread_name\s+>>> .+debuggerd_test(32|64) <<<)");
1129 ASSERT_BACKTRACE_FRAME(result, "tgkill");
1130 }
1131
TEST_F(CrasherTest,fake_pid)1132 TEST_F(CrasherTest, fake_pid) {
1133 int intercept_result;
1134 unique_fd output_fd;
1135
1136 // Prime the getpid/gettid caches.
1137 UNUSED(getpid());
1138 UNUSED(gettid());
1139
1140 std::function<pid_t()> clone_fn = []() {
1141 return syscall(__NR_clone, SIGCHLD, nullptr, nullptr, nullptr, nullptr);
1142 };
1143 StartProcess(
1144 []() {
1145 ASSERT_NE(getpid(), syscall(__NR_getpid));
1146 ASSERT_NE(gettid(), syscall(__NR_gettid));
1147 raise(SIGSEGV);
1148 },
1149 clone_fn);
1150
1151 StartIntercept(&output_fd);
1152 FinishCrasher();
1153 AssertDeath(SIGSEGV);
1154 FinishIntercept(&intercept_result);
1155
1156 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1157
1158 std::string result;
1159 ConsumeFd(std::move(output_fd), &result);
1160 ASSERT_BACKTRACE_FRAME(result, "tgkill");
1161 }
1162
1163 static const char* const kDebuggerdSeccompPolicy =
1164 "/system/etc/seccomp_policy/crash_dump." ABI_STRING ".policy";
1165
seccomp_fork_impl(void (* prejail)())1166 static pid_t seccomp_fork_impl(void (*prejail)()) {
1167 std::string policy;
1168 if (!android::base::ReadFileToString(kDebuggerdSeccompPolicy, &policy)) {
1169 PLOG(FATAL) << "failed to read policy file";
1170 }
1171
1172 // Allow a bunch of syscalls used by the tests.
1173 policy += "\nclone: 1";
1174 policy += "\nsigaltstack: 1";
1175 policy += "\nnanosleep: 1";
1176 policy += "\ngetrlimit: 1";
1177 policy += "\nugetrlimit: 1";
1178
1179 FILE* tmp_file = tmpfile();
1180 if (!tmp_file) {
1181 PLOG(FATAL) << "tmpfile failed";
1182 }
1183
1184 unique_fd tmp_fd(TEMP_FAILURE_RETRY(dup(fileno(tmp_file))));
1185 if (!android::base::WriteStringToFd(policy, tmp_fd.get())) {
1186 PLOG(FATAL) << "failed to write policy to tmpfile";
1187 }
1188
1189 if (lseek(tmp_fd.get(), 0, SEEK_SET) != 0) {
1190 PLOG(FATAL) << "failed to seek tmp_fd";
1191 }
1192
1193 ScopedMinijail jail{minijail_new()};
1194 if (!jail) {
1195 LOG(FATAL) << "failed to create minijail";
1196 }
1197
1198 minijail_no_new_privs(jail.get());
1199 minijail_log_seccomp_filter_failures(jail.get());
1200 minijail_use_seccomp_filter(jail.get());
1201 minijail_parse_seccomp_filters_from_fd(jail.get(), tmp_fd.release());
1202
1203 pid_t result = fork();
1204 if (result == -1) {
1205 return result;
1206 } else if (result != 0) {
1207 return result;
1208 }
1209
1210 // Spawn and detach a thread that spins forever.
1211 std::atomic<bool> thread_ready(false);
1212 std::thread thread([&jail, &thread_ready]() {
1213 minijail_enter(jail.get());
1214 thread_ready = true;
1215 for (;;)
1216 ;
1217 });
1218 thread.detach();
1219
1220 while (!thread_ready) {
1221 continue;
1222 }
1223
1224 if (prejail) {
1225 prejail();
1226 }
1227
1228 minijail_enter(jail.get());
1229 return result;
1230 }
1231
seccomp_fork()1232 static pid_t seccomp_fork() {
1233 return seccomp_fork_impl(nullptr);
1234 }
1235
TEST_F(CrasherTest,seccomp_crash)1236 TEST_F(CrasherTest, seccomp_crash) {
1237 int intercept_result;
1238 unique_fd output_fd;
1239
1240 StartProcess([]() { abort(); }, &seccomp_fork);
1241
1242 StartIntercept(&output_fd);
1243 FinishCrasher();
1244 AssertDeath(SIGABRT);
1245 FinishIntercept(&intercept_result);
1246 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1247
1248 std::string result;
1249 ConsumeFd(std::move(output_fd), &result);
1250 ASSERT_BACKTRACE_FRAME(result, "abort");
1251 }
1252
seccomp_fork_rlimit()1253 static pid_t seccomp_fork_rlimit() {
1254 return seccomp_fork_impl([]() {
1255 struct rlimit rlim = {
1256 .rlim_cur = 512 * 1024 * 1024,
1257 .rlim_max = 512 * 1024 * 1024,
1258 };
1259
1260 if (setrlimit(RLIMIT_AS, &rlim) != 0) {
1261 raise(SIGINT);
1262 }
1263 });
1264 }
1265
TEST_F(CrasherTest,seccomp_crash_oom)1266 TEST_F(CrasherTest, seccomp_crash_oom) {
1267 int intercept_result;
1268 unique_fd output_fd;
1269
1270 StartProcess(
1271 []() {
1272 std::vector<void*> vec;
1273 for (int i = 0; i < 512; ++i) {
1274 char* buf = static_cast<char*>(malloc(1024 * 1024));
1275 if (!buf) {
1276 abort();
1277 }
1278 memset(buf, 0xff, 1024 * 1024);
1279 vec.push_back(buf);
1280 }
1281 },
1282 &seccomp_fork_rlimit);
1283
1284 StartIntercept(&output_fd);
1285 FinishCrasher();
1286 AssertDeath(SIGABRT);
1287 FinishIntercept(&intercept_result);
1288 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1289
1290 // We can't actually generate a backtrace, just make sure that the process terminates.
1291 }
1292
raise_debugger_signal(DebuggerdDumpType dump_type)1293 __attribute__((noinline)) extern "C" bool raise_debugger_signal(DebuggerdDumpType dump_type) {
1294 siginfo_t siginfo;
1295 siginfo.si_code = SI_QUEUE;
1296 siginfo.si_pid = getpid();
1297 siginfo.si_uid = getuid();
1298
1299 if (dump_type != kDebuggerdNativeBacktrace && dump_type != kDebuggerdTombstone) {
1300 PLOG(FATAL) << "invalid dump type";
1301 }
1302
1303 siginfo.si_value.sival_int = dump_type == kDebuggerdNativeBacktrace;
1304
1305 if (syscall(__NR_rt_tgsigqueueinfo, getpid(), gettid(), BIONIC_SIGNAL_DEBUGGER, &siginfo) != 0) {
1306 PLOG(ERROR) << "libdebuggerd_client: failed to send signal to self";
1307 return false;
1308 }
1309
1310 return true;
1311 }
1312
TEST_F(CrasherTest,seccomp_tombstone)1313 TEST_F(CrasherTest, seccomp_tombstone) {
1314 int intercept_result;
1315 unique_fd output_fd;
1316
1317 static const auto dump_type = kDebuggerdTombstone;
1318 StartProcess(
1319 []() {
1320 raise_debugger_signal(dump_type);
1321 _exit(0);
1322 },
1323 &seccomp_fork);
1324
1325 StartIntercept(&output_fd, dump_type);
1326 FinishCrasher();
1327 AssertDeath(0);
1328 FinishIntercept(&intercept_result);
1329 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1330
1331 std::string result;
1332 ConsumeFd(std::move(output_fd), &result);
1333 ASSERT_BACKTRACE_FRAME(result, "raise_debugger_signal");
1334 }
1335
foo()1336 extern "C" void foo() {
1337 LOG(INFO) << "foo";
1338 std::this_thread::sleep_for(1s);
1339 }
1340
bar()1341 extern "C" void bar() {
1342 LOG(INFO) << "bar";
1343 std::this_thread::sleep_for(1s);
1344 }
1345
TEST_F(CrasherTest,seccomp_backtrace)1346 TEST_F(CrasherTest, seccomp_backtrace) {
1347 int intercept_result;
1348 unique_fd output_fd;
1349
1350 static const auto dump_type = kDebuggerdNativeBacktrace;
1351 StartProcess(
1352 []() {
1353 std::thread a(foo);
1354 std::thread b(bar);
1355
1356 std::this_thread::sleep_for(100ms);
1357
1358 raise_debugger_signal(dump_type);
1359 _exit(0);
1360 },
1361 &seccomp_fork);
1362
1363 StartIntercept(&output_fd, dump_type);
1364 FinishCrasher();
1365 AssertDeath(0);
1366 FinishIntercept(&intercept_result);
1367 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1368
1369 std::string result;
1370 ConsumeFd(std::move(output_fd), &result);
1371 ASSERT_BACKTRACE_FRAME(result, "raise_debugger_signal");
1372 ASSERT_BACKTRACE_FRAME(result, "foo");
1373 ASSERT_BACKTRACE_FRAME(result, "bar");
1374 }
1375
TEST_F(CrasherTest,seccomp_crash_logcat)1376 TEST_F(CrasherTest, seccomp_crash_logcat) {
1377 StartProcess([]() { abort(); }, &seccomp_fork);
1378 FinishCrasher();
1379
1380 // Make sure we don't get SIGSYS when trying to dump a crash to logcat.
1381 AssertDeath(SIGABRT);
1382 }
1383
TEST_F(CrasherTest,competing_tracer)1384 TEST_F(CrasherTest, competing_tracer) {
1385 int intercept_result;
1386 unique_fd output_fd;
1387 StartProcess([]() {
1388 raise(SIGABRT);
1389 });
1390
1391 StartIntercept(&output_fd);
1392
1393 ASSERT_EQ(0, ptrace(PTRACE_SEIZE, crasher_pid, 0, 0));
1394 FinishCrasher();
1395
1396 int status;
1397 ASSERT_EQ(crasher_pid, TEMP_FAILURE_RETRY(waitpid(crasher_pid, &status, 0)));
1398 ASSERT_TRUE(WIFSTOPPED(status));
1399 ASSERT_EQ(SIGABRT, WSTOPSIG(status));
1400
1401 ASSERT_EQ(0, ptrace(PTRACE_CONT, crasher_pid, 0, SIGABRT));
1402 FinishIntercept(&intercept_result);
1403 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1404
1405 std::string result;
1406 ConsumeFd(std::move(output_fd), &result);
1407 std::string regex = R"(failed to attach to thread \d+, already traced by )";
1408 regex += std::to_string(gettid());
1409 regex += R"( \(.+debuggerd_test)";
1410 ASSERT_MATCH(result, regex.c_str());
1411
1412 ASSERT_EQ(crasher_pid, TEMP_FAILURE_RETRY(waitpid(crasher_pid, &status, 0)));
1413 ASSERT_TRUE(WIFSTOPPED(status));
1414 ASSERT_EQ(SIGABRT, WSTOPSIG(status));
1415
1416 ASSERT_EQ(0, ptrace(PTRACE_DETACH, crasher_pid, 0, SIGABRT));
1417 AssertDeath(SIGABRT);
1418 }
1419
TEST_F(CrasherTest,fdsan_warning_abort_message)1420 TEST_F(CrasherTest, fdsan_warning_abort_message) {
1421 int intercept_result;
1422 unique_fd output_fd;
1423
1424 StartProcess([]() {
1425 android_fdsan_set_error_level(ANDROID_FDSAN_ERROR_LEVEL_WARN_ONCE);
1426 unique_fd fd(TEMP_FAILURE_RETRY(open("/dev/null", O_RDONLY | O_CLOEXEC)));
1427 if (fd == -1) {
1428 abort();
1429 }
1430 close(fd.get());
1431 _exit(0);
1432 });
1433
1434 StartIntercept(&output_fd);
1435 FinishCrasher();
1436 AssertDeath(0);
1437 FinishIntercept(&intercept_result);
1438 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1439
1440 std::string result;
1441 ConsumeFd(std::move(output_fd), &result);
1442 ASSERT_MATCH(result, "Abort message: 'attempted to close");
1443 }
1444
TEST(crash_dump,zombie)1445 TEST(crash_dump, zombie) {
1446 pid_t forkpid = fork();
1447
1448 pid_t rc;
1449 int status;
1450
1451 if (forkpid == 0) {
1452 errno = 0;
1453 rc = waitpid(-1, &status, WNOHANG | __WALL | __WNOTHREAD);
1454 if (rc != -1 || errno != ECHILD) {
1455 errx(2, "first waitpid returned %d (%s), expected failure with ECHILD", rc, strerror(errno));
1456 }
1457
1458 raise(BIONIC_SIGNAL_DEBUGGER);
1459
1460 errno = 0;
1461 rc = TEMP_FAILURE_RETRY(waitpid(-1, &status, __WALL | __WNOTHREAD));
1462 if (rc != -1 || errno != ECHILD) {
1463 errx(2, "second waitpid returned %d (%s), expected failure with ECHILD", rc, strerror(errno));
1464 }
1465 _exit(0);
1466 } else {
1467 rc = TEMP_FAILURE_RETRY(waitpid(forkpid, &status, 0));
1468 ASSERT_EQ(forkpid, rc);
1469 ASSERT_TRUE(WIFEXITED(status));
1470 ASSERT_EQ(0, WEXITSTATUS(status));
1471 }
1472 }
1473
TEST(tombstoned,no_notify)1474 TEST(tombstoned, no_notify) {
1475 // Do this a few times.
1476 for (int i = 0; i < 3; ++i) {
1477 pid_t pid = 123'456'789 + i;
1478
1479 unique_fd intercept_fd, output_fd;
1480 InterceptStatus status;
1481 tombstoned_intercept(pid, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
1482 ASSERT_EQ(InterceptStatus::kRegistered, status);
1483
1484 {
1485 unique_fd tombstoned_socket, input_fd;
1486 ASSERT_TRUE(tombstoned_connect(pid, &tombstoned_socket, &input_fd, kDebuggerdTombstone));
1487 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), &pid, sizeof(pid)));
1488 }
1489
1490 pid_t read_pid;
1491 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), &read_pid, sizeof(read_pid)));
1492 ASSERT_EQ(read_pid, pid);
1493 }
1494 }
1495
TEST(tombstoned,stress)1496 TEST(tombstoned, stress) {
1497 // Spawn threads to simultaneously do a bunch of failing dumps and a bunch of successful dumps.
1498 static constexpr int kDumpCount = 100;
1499
1500 std::atomic<bool> start(false);
1501 std::vector<std::thread> threads;
1502 threads.emplace_back([&start]() {
1503 while (!start) {
1504 continue;
1505 }
1506
1507 // Use a way out of range pid, to avoid stomping on an actual process.
1508 pid_t pid_base = 1'000'000;
1509
1510 for (int dump = 0; dump < kDumpCount; ++dump) {
1511 pid_t pid = pid_base + dump;
1512
1513 unique_fd intercept_fd, output_fd;
1514 InterceptStatus status;
1515 tombstoned_intercept(pid, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
1516 ASSERT_EQ(InterceptStatus::kRegistered, status);
1517
1518 // Pretend to crash, and then immediately close the socket.
1519 unique_fd sockfd(socket_local_client(kTombstonedCrashSocketName,
1520 ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_SEQPACKET));
1521 if (sockfd == -1) {
1522 FAIL() << "failed to connect to tombstoned: " << strerror(errno);
1523 }
1524 TombstonedCrashPacket packet = {};
1525 packet.packet_type = CrashPacketType::kDumpRequest;
1526 packet.packet.dump_request.pid = pid;
1527 if (TEMP_FAILURE_RETRY(write(sockfd, &packet, sizeof(packet))) != sizeof(packet)) {
1528 FAIL() << "failed to write to tombstoned: " << strerror(errno);
1529 }
1530
1531 continue;
1532 }
1533 });
1534
1535 threads.emplace_back([&start]() {
1536 while (!start) {
1537 continue;
1538 }
1539
1540 // Use a way out of range pid, to avoid stomping on an actual process.
1541 pid_t pid_base = 2'000'000;
1542
1543 for (int dump = 0; dump < kDumpCount; ++dump) {
1544 pid_t pid = pid_base + dump;
1545
1546 unique_fd intercept_fd, output_fd;
1547 InterceptStatus status;
1548 tombstoned_intercept(pid, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
1549 ASSERT_EQ(InterceptStatus::kRegistered, status);
1550
1551 {
1552 unique_fd tombstoned_socket, input_fd;
1553 ASSERT_TRUE(tombstoned_connect(pid, &tombstoned_socket, &input_fd, kDebuggerdTombstone));
1554 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), &pid, sizeof(pid)));
1555 tombstoned_notify_completion(tombstoned_socket.get());
1556 }
1557
1558 // TODO: Fix the race that requires this sleep.
1559 std::this_thread::sleep_for(50ms);
1560
1561 pid_t read_pid;
1562 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), &read_pid, sizeof(read_pid)));
1563 ASSERT_EQ(read_pid, pid);
1564 }
1565 });
1566
1567 start = true;
1568
1569 for (std::thread& thread : threads) {
1570 thread.join();
1571 }
1572 }
1573
TEST(tombstoned,java_trace_intercept_smoke)1574 TEST(tombstoned, java_trace_intercept_smoke) {
1575 // Using a "real" PID is a little dangerous here - if the test fails
1576 // or crashes, we might end up getting a bogus / unreliable stack
1577 // trace.
1578 const pid_t self = getpid();
1579
1580 unique_fd intercept_fd, output_fd;
1581 InterceptStatus status;
1582 tombstoned_intercept(self, &intercept_fd, &output_fd, &status, kDebuggerdJavaBacktrace);
1583 ASSERT_EQ(InterceptStatus::kRegistered, status);
1584
1585 // First connect to tombstoned requesting a native tombstone. This
1586 // should result in a "regular" FD and not the installed intercept.
1587 const char native[] = "native";
1588 unique_fd tombstoned_socket, input_fd;
1589 ASSERT_TRUE(tombstoned_connect(self, &tombstoned_socket, &input_fd, kDebuggerdTombstone));
1590 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), native, sizeof(native)));
1591 tombstoned_notify_completion(tombstoned_socket.get());
1592
1593 // Then, connect to tombstoned asking for a java backtrace. This *should*
1594 // trigger the intercept.
1595 const char java[] = "java";
1596 ASSERT_TRUE(tombstoned_connect(self, &tombstoned_socket, &input_fd, kDebuggerdJavaBacktrace));
1597 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), java, sizeof(java)));
1598 tombstoned_notify_completion(tombstoned_socket.get());
1599
1600 char outbuf[sizeof(java)];
1601 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), outbuf, sizeof(outbuf)));
1602 ASSERT_STREQ("java", outbuf);
1603 }
1604
TEST(tombstoned,multiple_intercepts)1605 TEST(tombstoned, multiple_intercepts) {
1606 const pid_t fake_pid = 1'234'567;
1607 unique_fd intercept_fd, output_fd;
1608 InterceptStatus status;
1609 tombstoned_intercept(fake_pid, &intercept_fd, &output_fd, &status, kDebuggerdJavaBacktrace);
1610 ASSERT_EQ(InterceptStatus::kRegistered, status);
1611
1612 unique_fd intercept_fd_2, output_fd_2;
1613 tombstoned_intercept(fake_pid, &intercept_fd_2, &output_fd_2, &status, kDebuggerdNativeBacktrace);
1614 ASSERT_EQ(InterceptStatus::kFailedAlreadyRegistered, status);
1615 }
1616
TEST(tombstoned,intercept_any)1617 TEST(tombstoned, intercept_any) {
1618 const pid_t fake_pid = 1'234'567;
1619
1620 unique_fd intercept_fd, output_fd;
1621 InterceptStatus status;
1622 tombstoned_intercept(fake_pid, &intercept_fd, &output_fd, &status, kDebuggerdNativeBacktrace);
1623 ASSERT_EQ(InterceptStatus::kRegistered, status);
1624
1625 const char any[] = "any";
1626 unique_fd tombstoned_socket, input_fd;
1627 ASSERT_TRUE(tombstoned_connect(fake_pid, &tombstoned_socket, &input_fd, kDebuggerdAnyIntercept));
1628 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), any, sizeof(any)));
1629 tombstoned_notify_completion(tombstoned_socket.get());
1630
1631 char outbuf[sizeof(any)];
1632 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), outbuf, sizeof(outbuf)));
1633 ASSERT_STREQ("any", outbuf);
1634 }
1635
TEST(tombstoned,interceptless_backtrace)1636 TEST(tombstoned, interceptless_backtrace) {
1637 // Generate 50 backtraces, and then check to see that we haven't created 50 new tombstones.
1638 auto get_tombstone_timestamps = []() -> std::map<int, time_t> {
1639 std::map<int, time_t> result;
1640 for (int i = 0; i < 99; ++i) {
1641 std::string path = android::base::StringPrintf("/data/tombstones/tombstone_%02d", i);
1642 struct stat st;
1643 if (stat(path.c_str(), &st) == 0) {
1644 result[i] = st.st_mtim.tv_sec;
1645 }
1646 }
1647 return result;
1648 };
1649
1650 auto before = get_tombstone_timestamps();
1651 for (int i = 0; i < 50; ++i) {
1652 raise_debugger_signal(kDebuggerdNativeBacktrace);
1653 }
1654 auto after = get_tombstone_timestamps();
1655
1656 int diff = 0;
1657 for (int i = 0; i < 99; ++i) {
1658 if (after.count(i) == 0) {
1659 continue;
1660 }
1661 if (before.count(i) == 0) {
1662 ++diff;
1663 continue;
1664 }
1665 if (before[i] != after[i]) {
1666 ++diff;
1667 }
1668 }
1669
1670 // We can't be sure that nothing's crash looping in the background.
1671 // This should be good enough, though...
1672 ASSERT_LT(diff, 10) << "too many new tombstones; is something crashing in the background?";
1673 }
1674
overflow_stack(void * p)1675 static __attribute__((__noinline__)) void overflow_stack(void* p) {
1676 void* buf[1];
1677 buf[0] = p;
1678 static volatile void* global = buf;
1679 if (global) {
1680 global = buf;
1681 overflow_stack(&buf);
1682 }
1683 }
1684
TEST_F(CrasherTest,stack_overflow)1685 TEST_F(CrasherTest, stack_overflow) {
1686 int intercept_result;
1687 unique_fd output_fd;
1688 StartProcess([]() { overflow_stack(nullptr); });
1689
1690 StartIntercept(&output_fd);
1691 FinishCrasher();
1692 AssertDeath(SIGSEGV);
1693 FinishIntercept(&intercept_result);
1694
1695 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1696
1697 std::string result;
1698 ConsumeFd(std::move(output_fd), &result);
1699 ASSERT_MATCH(result, R"(Cause: stack pointer[^\n]*stack overflow.\n)");
1700 }
1701
CopySharedLibrary(const char * tmp_dir,std::string * tmp_so_name)1702 static bool CopySharedLibrary(const char* tmp_dir, std::string* tmp_so_name) {
1703 std::string test_lib(testing::internal::GetArgvs()[0]);
1704 auto const value = test_lib.find_last_of('/');
1705 if (value == std::string::npos) {
1706 test_lib = "./";
1707 } else {
1708 test_lib = test_lib.substr(0, value + 1) + "./";
1709 }
1710 test_lib += "libcrash_test.so";
1711
1712 *tmp_so_name = std::string(tmp_dir) + "/libcrash_test.so";
1713 std::string cp_cmd = android::base::StringPrintf("cp %s %s", test_lib.c_str(), tmp_dir);
1714
1715 // Copy the shared so to a tempory directory.
1716 return system(cp_cmd.c_str()) == 0;
1717 }
1718
TEST_F(CrasherTest,unreadable_elf)1719 TEST_F(CrasherTest, unreadable_elf) {
1720 int intercept_result;
1721 unique_fd output_fd;
1722 StartProcess([]() {
1723 TemporaryDir td;
1724 std::string tmp_so_name;
1725 if (!CopySharedLibrary(td.path, &tmp_so_name)) {
1726 _exit(1);
1727 }
1728 void* handle = dlopen(tmp_so_name.c_str(), RTLD_NOW);
1729 if (handle == nullptr) {
1730 _exit(1);
1731 }
1732 // Delete the original shared library so that we get the warning
1733 // about unreadable elf files.
1734 if (unlink(tmp_so_name.c_str()) == -1) {
1735 _exit(1);
1736 }
1737 void (*crash_func)() = reinterpret_cast<void (*)()>(dlsym(handle, "crash"));
1738 if (crash_func == nullptr) {
1739 _exit(1);
1740 }
1741 crash_func();
1742 });
1743
1744 StartIntercept(&output_fd);
1745 FinishCrasher();
1746 AssertDeath(SIGSEGV);
1747 FinishIntercept(&intercept_result);
1748
1749 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1750
1751 std::string result;
1752 ConsumeFd(std::move(output_fd), &result);
1753 ASSERT_MATCH(result, R"(NOTE: Function names and BuildId information is missing )");
1754 }
1755
TEST(tombstoned,proto)1756 TEST(tombstoned, proto) {
1757 const pid_t self = getpid();
1758 unique_fd tombstoned_socket, text_fd, proto_fd;
1759 ASSERT_TRUE(
1760 tombstoned_connect(self, &tombstoned_socket, &text_fd, &proto_fd, kDebuggerdTombstoneProto));
1761
1762 tombstoned_notify_completion(tombstoned_socket.get());
1763
1764 ASSERT_NE(-1, text_fd.get());
1765 ASSERT_NE(-1, proto_fd.get());
1766
1767 struct stat text_st;
1768 ASSERT_EQ(0, fstat(text_fd.get(), &text_st));
1769
1770 // Give tombstoned some time to link the files into place.
1771 std::this_thread::sleep_for(100ms);
1772
1773 // Find the tombstone.
1774 std::optional<std::string> tombstone_file;
1775 std::unique_ptr<DIR, decltype(&closedir)> dir_h(opendir("/data/tombstones"), closedir);
1776 ASSERT_TRUE(dir_h != nullptr);
1777 std::regex tombstone_re("tombstone_\\d+");
1778 dirent* entry;
1779 while ((entry = readdir(dir_h.get())) != nullptr) {
1780 if (!std::regex_match(entry->d_name, tombstone_re)) {
1781 continue;
1782 }
1783 std::string path = android::base::StringPrintf("/data/tombstones/%s", entry->d_name);
1784
1785 struct stat st;
1786 if (TEMP_FAILURE_RETRY(stat(path.c_str(), &st)) != 0) {
1787 continue;
1788 }
1789
1790 if (st.st_dev == text_st.st_dev && st.st_ino == text_st.st_ino) {
1791 tombstone_file = path;
1792 break;
1793 }
1794 }
1795
1796 ASSERT_TRUE(tombstone_file);
1797 std::string proto_path = tombstone_file.value() + ".pb";
1798
1799 struct stat proto_fd_st;
1800 struct stat proto_file_st;
1801 ASSERT_EQ(0, fstat(proto_fd.get(), &proto_fd_st));
1802 ASSERT_EQ(0, stat(proto_path.c_str(), &proto_file_st));
1803
1804 ASSERT_EQ(proto_fd_st.st_dev, proto_file_st.st_dev);
1805 ASSERT_EQ(proto_fd_st.st_ino, proto_file_st.st_ino);
1806 }
1807
TEST(tombstoned,proto_intercept)1808 TEST(tombstoned, proto_intercept) {
1809 const pid_t self = getpid();
1810 unique_fd intercept_fd, output_fd;
1811 InterceptStatus status;
1812
1813 tombstoned_intercept(self, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
1814 ASSERT_EQ(InterceptStatus::kRegistered, status);
1815
1816 unique_fd tombstoned_socket, text_fd, proto_fd;
1817 ASSERT_TRUE(
1818 tombstoned_connect(self, &tombstoned_socket, &text_fd, &proto_fd, kDebuggerdTombstoneProto));
1819 ASSERT_TRUE(android::base::WriteStringToFd("foo", text_fd.get()));
1820 tombstoned_notify_completion(tombstoned_socket.get());
1821
1822 text_fd.reset();
1823
1824 std::string output;
1825 ASSERT_TRUE(android::base::ReadFdToString(output_fd, &output));
1826 ASSERT_EQ("foo", output);
1827 }
1828