blob: 25417a985f421aeb7193519262544f25f3650420 [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 <err.h>
18#include <fcntl.h>
Josh Gaocdea7502017-11-01 15:00:40 -070019#include <stdlib.h>
Josh Gao502cfd22017-02-17 01:39:15 -080020#include <sys/capability.h>
Josh Gaofca7ca32017-01-23 12:05:35 -080021#include <sys/prctl.h>
Josh Gaofd13bf02017-08-18 15:37:26 -070022#include <sys/ptrace.h>
Josh Gao70adac62018-02-22 11:38:33 -080023#include <sys/resource.h>
Dan Albertc38057a2017-10-11 11:35:40 -070024#include <sys/syscall.h>
Josh Gaocbe70cb2016-10-18 18:17:52 -070025#include <sys/types.h>
Josh Gaofd13bf02017-08-18 15:37:26 -070026#include <unistd.h>
Josh Gaocbe70cb2016-10-18 18:17:52 -070027
28#include <chrono>
29#include <regex>
30#include <thread>
31
Josh Gaobf06a402018-08-27 16:34:01 -070032#include <android/fdsan.h>
Josh Gao502cfd22017-02-17 01:39:15 -080033#include <android/set_abort_message.h>
Peter Collingbournef8622522020-04-07 14:07:32 -070034#include <bionic/malloc.h>
35#include <bionic/mte.h>
36#include <bionic/mte_kernel.h>
Josh Gaoa48b41b2019-12-13 14:11:04 -080037#include <bionic/reserved_signals.h>
Josh Gao502cfd22017-02-17 01:39:15 -080038
Josh Gao5f87bbd2019-01-09 17:01:49 -080039#include <android-base/cmsg.h>
Josh Gaocbe70cb2016-10-18 18:17:52 -070040#include <android-base/file.h>
41#include <android-base/logging.h>
Josh Gao2e7b8e22017-05-04 17:12:57 -070042#include <android-base/macros.h>
Josh Gaocbe70cb2016-10-18 18:17:52 -070043#include <android-base/parseint.h>
44#include <android-base/properties.h>
Josh Gao2b22ae12018-09-12 14:51:03 -070045#include <android-base/stringprintf.h>
Josh Gaocbe70cb2016-10-18 18:17:52 -070046#include <android-base/strings.h>
Josh Gao30171a82017-04-27 19:48:44 -070047#include <android-base/test_utils.h>
Josh Gaocbe70cb2016-10-18 18:17:52 -070048#include <android-base/unique_fd.h>
49#include <cutils/sockets.h>
Josh Gaocbe70cb2016-10-18 18:17:52 -070050#include <gtest/gtest.h>
51
Josh Gaoe04ca272018-01-16 15:38:17 -080052#include <libminijail.h>
53#include <scoped_minijail.h>
54
Narayan Kamath2d377cd2017-05-10 10:58:59 +010055#include "debuggerd/handler.h"
56#include "protocol.h"
57#include "tombstoned/tombstoned.h"
58#include "util.h"
59
Josh Gaocbe70cb2016-10-18 18:17:52 -070060using namespace std::chrono_literals;
Josh Gao5f87bbd2019-01-09 17:01:49 -080061
62using android::base::SendFileDescriptors;
Josh Gaocbe70cb2016-10-18 18:17:52 -070063using android::base::unique_fd;
64
65#if defined(__LP64__)
Josh Gaocbe70cb2016-10-18 18:17:52 -070066#define ARCH_SUFFIX "64"
67#else
Josh Gaocbe70cb2016-10-18 18:17:52 -070068#define ARCH_SUFFIX ""
69#endif
70
71constexpr char kWaitForGdbKey[] = "debug.debuggerd.wait_for_gdb";
72
73#define TIMEOUT(seconds, expr) \
74 [&]() { \
75 struct sigaction old_sigaction; \
76 struct sigaction new_sigaction = {}; \
77 new_sigaction.sa_handler = [](int) {}; \
78 if (sigaction(SIGALRM, &new_sigaction, &new_sigaction) != 0) { \
79 err(1, "sigaction failed"); \
80 } \
81 alarm(seconds); \
82 auto value = expr; \
83 int saved_errno = errno; \
84 if (sigaction(SIGALRM, &old_sigaction, nullptr) != 0) { \
85 err(1, "sigaction failed"); \
86 } \
87 alarm(0); \
88 errno = saved_errno; \
89 return value; \
90 }()
91
Chih-Hung Hsieh3249b3a2018-05-11 16:01:21 -070092// Backtrace frame dump could contain:
93// #01 pc 0001cded /data/tmp/debuggerd_test32 (raise_debugger_signal+80)
94// or
95// #01 pc 00022a09 /data/tmp/debuggerd_test32 (offset 0x12000) (raise_debugger_signal+80)
Josh Gaoe04ca272018-01-16 15:38:17 -080096#define ASSERT_BACKTRACE_FRAME(result, frame_name) \
Chih-Hung Hsieh3249b3a2018-05-11 16:01:21 -070097 ASSERT_MATCH(result, \
98 R"(#\d\d pc [0-9a-f]+\s+ \S+ (\(offset 0x[0-9a-f]+\) )?\()" frame_name R"(\+)");
Jaesung Chung58778e12017-06-15 18:20:34 +090099
Narayan Kamatha73df602017-05-24 15:07:25 +0100100static void tombstoned_intercept(pid_t target_pid, unique_fd* intercept_fd, unique_fd* output_fd,
Narayan Kamathca5e9082017-06-02 15:42:06 +0100101 InterceptStatus* status, DebuggerdDumpType intercept_type) {
Josh Gao460b3362017-03-30 16:40:47 -0700102 intercept_fd->reset(socket_local_client(kTombstonedInterceptSocketName,
103 ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_SEQPACKET));
104 if (intercept_fd->get() == -1) {
105 FAIL() << "failed to contact tombstoned: " << strerror(errno);
106 }
107
Nick Desaulniers67d52aa2019-10-07 23:28:15 -0700108 InterceptRequest req = {
109 .dump_type = intercept_type,
110 .pid = target_pid,
111 };
Josh Gao460b3362017-03-30 16:40:47 -0700112
113 unique_fd output_pipe_write;
114 if (!Pipe(output_fd, &output_pipe_write)) {
115 FAIL() << "failed to create output pipe: " << strerror(errno);
116 }
117
118 std::string pipe_size_str;
119 int pipe_buffer_size;
120 if (!android::base::ReadFileToString("/proc/sys/fs/pipe-max-size", &pipe_size_str)) {
121 FAIL() << "failed to read /proc/sys/fs/pipe-max-size: " << strerror(errno);
122 }
123
124 pipe_size_str = android::base::Trim(pipe_size_str);
125
126 if (!android::base::ParseInt(pipe_size_str.c_str(), &pipe_buffer_size, 0)) {
127 FAIL() << "failed to parse pipe max size";
128 }
129
130 if (fcntl(output_fd->get(), F_SETPIPE_SZ, pipe_buffer_size) != pipe_buffer_size) {
131 FAIL() << "failed to set pipe size: " << strerror(errno);
132 }
133
Josh Gao5675f3c2017-06-01 12:19:53 -0700134 ASSERT_GE(pipe_buffer_size, 1024 * 1024);
135
Josh Gao5f87bbd2019-01-09 17:01:49 -0800136 ssize_t rc = SendFileDescriptors(intercept_fd->get(), &req, sizeof(req), output_pipe_write.get());
137 output_pipe_write.reset();
138 if (rc != sizeof(req)) {
Josh Gao460b3362017-03-30 16:40:47 -0700139 FAIL() << "failed to send output fd to tombstoned: " << strerror(errno);
140 }
141
142 InterceptResponse response;
Josh Gao5f87bbd2019-01-09 17:01:49 -0800143 rc = TEMP_FAILURE_RETRY(read(intercept_fd->get(), &response, sizeof(response)));
Josh Gao460b3362017-03-30 16:40:47 -0700144 if (rc == -1) {
145 FAIL() << "failed to read response from tombstoned: " << strerror(errno);
146 } else if (rc == 0) {
147 FAIL() << "failed to read response from tombstoned (EOF)";
148 } else if (rc != sizeof(response)) {
149 FAIL() << "received packet of unexpected length from tombstoned: expected " << sizeof(response)
150 << ", received " << rc;
151 }
152
Narayan Kamathca5e9082017-06-02 15:42:06 +0100153 *status = response.status;
Josh Gao460b3362017-03-30 16:40:47 -0700154}
155
Josh Gaocbe70cb2016-10-18 18:17:52 -0700156class CrasherTest : public ::testing::Test {
157 public:
158 pid_t crasher_pid = -1;
159 bool previous_wait_for_gdb;
160 unique_fd crasher_pipe;
161 unique_fd intercept_fd;
162
163 CrasherTest();
164 ~CrasherTest();
165
Narayan Kamatha73df602017-05-24 15:07:25 +0100166 void StartIntercept(unique_fd* output_fd, DebuggerdDumpType intercept_type = kDebuggerdTombstone);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700167
168 // Returns -1 if we fail to read a response from tombstoned, otherwise the received return code.
169 void FinishIntercept(int* result);
170
Josh Gao2e7b8e22017-05-04 17:12:57 -0700171 void StartProcess(std::function<void()> function, std::function<pid_t()> forker = fork);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700172 void StartCrasher(const std::string& crash_type);
173 void FinishCrasher();
174 void AssertDeath(int signo);
175};
176
177CrasherTest::CrasherTest() {
178 previous_wait_for_gdb = android::base::GetBoolProperty(kWaitForGdbKey, false);
179 android::base::SetProperty(kWaitForGdbKey, "0");
180}
181
182CrasherTest::~CrasherTest() {
183 if (crasher_pid != -1) {
184 kill(crasher_pid, SIGKILL);
185 int status;
Christopher Ferris172b0a02019-09-18 17:48:30 -0700186 TEMP_FAILURE_RETRY(waitpid(crasher_pid, &status, WUNTRACED));
Josh Gaocbe70cb2016-10-18 18:17:52 -0700187 }
188
189 android::base::SetProperty(kWaitForGdbKey, previous_wait_for_gdb ? "1" : "0");
190}
191
Narayan Kamatha73df602017-05-24 15:07:25 +0100192void CrasherTest::StartIntercept(unique_fd* output_fd, DebuggerdDumpType intercept_type) {
Josh Gaocbe70cb2016-10-18 18:17:52 -0700193 if (crasher_pid == -1) {
194 FAIL() << "crasher hasn't been started";
195 }
196
Narayan Kamathca5e9082017-06-02 15:42:06 +0100197 InterceptStatus status;
198 tombstoned_intercept(crasher_pid, &this->intercept_fd, output_fd, &status, intercept_type);
199 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700200}
201
202void CrasherTest::FinishIntercept(int* result) {
203 InterceptResponse response;
204
Christopher Ferris11555f02019-09-20 14:18:55 -0700205 ssize_t rc = TIMEOUT(30, read(intercept_fd.get(), &response, sizeof(response)));
Josh Gaocbe70cb2016-10-18 18:17:52 -0700206 if (rc == -1) {
207 FAIL() << "failed to read response from tombstoned: " << strerror(errno);
208 } else if (rc == 0) {
209 *result = -1;
210 } else if (rc != sizeof(response)) {
211 FAIL() << "received packet of unexpected length from tombstoned: expected " << sizeof(response)
212 << ", received " << rc;
213 } else {
Josh Gao460b3362017-03-30 16:40:47 -0700214 *result = response.status == InterceptStatus::kStarted ? 1 : 0;
Josh Gaocbe70cb2016-10-18 18:17:52 -0700215 }
216}
217
Josh Gao2e7b8e22017-05-04 17:12:57 -0700218void CrasherTest::StartProcess(std::function<void()> function, std::function<pid_t()> forker) {
Josh Gaofca7ca32017-01-23 12:05:35 -0800219 unique_fd read_pipe;
Josh Gaocbe70cb2016-10-18 18:17:52 -0700220 unique_fd crasher_read_pipe;
221 if (!Pipe(&crasher_read_pipe, &crasher_pipe)) {
222 FAIL() << "failed to create pipe: " << strerror(errno);
223 }
224
Josh Gao2e7b8e22017-05-04 17:12:57 -0700225 crasher_pid = forker();
Josh Gaocbe70cb2016-10-18 18:17:52 -0700226 if (crasher_pid == -1) {
227 FAIL() << "fork failed: " << strerror(errno);
228 } else if (crasher_pid == 0) {
Josh Gao502cfd22017-02-17 01:39:15 -0800229 char dummy;
230 crasher_pipe.reset();
231 TEMP_FAILURE_RETRY(read(crasher_read_pipe.get(), &dummy, 1));
Josh Gaofca7ca32017-01-23 12:05:35 -0800232 function();
233 _exit(0);
234 }
235}
236
Josh Gaocbe70cb2016-10-18 18:17:52 -0700237void CrasherTest::FinishCrasher() {
238 if (crasher_pipe == -1) {
239 FAIL() << "crasher pipe uninitialized";
240 }
241
Christopher Ferris172b0a02019-09-18 17:48:30 -0700242 ssize_t rc = TEMP_FAILURE_RETRY(write(crasher_pipe.get(), "\n", 1));
Josh Gaocbe70cb2016-10-18 18:17:52 -0700243 if (rc == -1) {
244 FAIL() << "failed to write to crasher pipe: " << strerror(errno);
245 } else if (rc == 0) {
246 FAIL() << "crasher pipe was closed";
247 }
248}
249
250void CrasherTest::AssertDeath(int signo) {
251 int status;
Christopher Ferris11555f02019-09-20 14:18:55 -0700252 pid_t pid = TIMEOUT(30, waitpid(crasher_pid, &status, 0));
Josh Gaocbe70cb2016-10-18 18:17:52 -0700253 if (pid != crasher_pid) {
Christopher Ferrisafc0ff72019-06-26 15:08:51 -0700254 printf("failed to wait for crasher (expected pid %d, return value %d): %s\n", crasher_pid, pid,
255 strerror(errno));
Josh Gao2b2ae0c2017-08-21 14:31:17 -0700256 sleep(100);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700257 FAIL() << "failed to wait for crasher: " << strerror(errno);
258 }
259
Josh Gaoe06f2a42017-04-27 16:50:38 -0700260 if (signo == 0) {
261 ASSERT_TRUE(WIFEXITED(status));
262 ASSERT_EQ(0, WEXITSTATUS(signo));
263 } else {
264 ASSERT_FALSE(WIFEXITED(status));
265 ASSERT_TRUE(WIFSIGNALED(status)) << "crasher didn't terminate via a signal";
266 ASSERT_EQ(signo, WTERMSIG(status));
Josh Gaocbe70cb2016-10-18 18:17:52 -0700267 }
Josh Gaocbe70cb2016-10-18 18:17:52 -0700268 crasher_pid = -1;
269}
270
271static void ConsumeFd(unique_fd fd, std::string* output) {
272 constexpr size_t read_length = PAGE_SIZE;
273 std::string result;
274
275 while (true) {
276 size_t offset = result.size();
277 result.resize(result.size() + PAGE_SIZE);
278 ssize_t rc = TEMP_FAILURE_RETRY(read(fd.get(), &result[offset], read_length));
279 if (rc == -1) {
280 FAIL() << "read failed: " << strerror(errno);
281 } else if (rc == 0) {
282 result.resize(result.size() - PAGE_SIZE);
283 break;
284 }
285
286 result.resize(result.size() - PAGE_SIZE + rc);
287 }
288
289 *output = std::move(result);
290}
291
292TEST_F(CrasherTest, smoke) {
293 int intercept_result;
294 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800295 StartProcess([]() {
296 *reinterpret_cast<volatile char*>(0xdead) = '1';
297 });
298
Josh Gaocbe70cb2016-10-18 18:17:52 -0700299 StartIntercept(&output_fd);
300 FinishCrasher();
301 AssertDeath(SIGSEGV);
302 FinishIntercept(&intercept_result);
303
304 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
305
306 std::string result;
307 ConsumeFd(std::move(output_fd), &result);
308 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\), code 1 \(SEGV_MAPERR\), fault addr 0xdead)");
309}
310
Peter Collingbournef03af882020-03-20 18:09:00 -0700311TEST_F(CrasherTest, tagged_fault_addr) {
312#if !defined(__aarch64__)
313 GTEST_SKIP() << "Requires aarch64";
314#endif
315 int intercept_result;
316 unique_fd output_fd;
317 StartProcess([]() {
318 *reinterpret_cast<volatile char*>(0x100000000000dead) = '1';
319 });
320
321 StartIntercept(&output_fd);
322 FinishCrasher();
323 AssertDeath(SIGSEGV);
324 FinishIntercept(&intercept_result);
325
326 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
327
328 std::string result;
329 ConsumeFd(std::move(output_fd), &result);
330
331 // The address can either be tagged (new kernels) or untagged (old kernels).
332 ASSERT_MATCH(
333 result,
334 R"(signal 11 \(SIGSEGV\), code 1 \(SEGV_MAPERR\), fault addr (0x100000000000dead|0xdead))");
335}
336
Peter Collingbournef8622522020-04-07 14:07:32 -0700337#if defined(__aarch64__) && defined(ANDROID_EXPERIMENTAL_MTE)
338static void SetTagCheckingLevelSync() {
339 int tagged_addr_ctrl = prctl(PR_GET_TAGGED_ADDR_CTRL, 0, 0, 0, 0);
340 if (tagged_addr_ctrl < 0) {
341 abort();
342 }
343
344 tagged_addr_ctrl = (tagged_addr_ctrl & ~PR_MTE_TCF_MASK) | PR_MTE_TCF_SYNC;
345 if (prctl(PR_SET_TAGGED_ADDR_CTRL, tagged_addr_ctrl, 0, 0, 0) != 0) {
346 abort();
347 }
348
349 HeapTaggingLevel heap_tagging_level = M_HEAP_TAGGING_LEVEL_SYNC;
350 if (!android_mallopt(M_SET_HEAP_TAGGING_LEVEL, &heap_tagging_level, sizeof(heap_tagging_level))) {
351 abort();
352 }
353}
354#endif
355
356TEST_F(CrasherTest, mte_uaf) {
357#if defined(__aarch64__) && defined(ANDROID_EXPERIMENTAL_MTE)
358 if (!mte_supported()) {
359 GTEST_SKIP() << "Requires MTE";
360 }
361
362 int intercept_result;
363 unique_fd output_fd;
364 StartProcess([]() {
365 SetTagCheckingLevelSync();
366 volatile int* p = (volatile int*)malloc(16);
367 free((void *)p);
368 p[0] = 42;
369 });
370
371 StartIntercept(&output_fd);
372 FinishCrasher();
373 AssertDeath(SIGSEGV);
374 FinishIntercept(&intercept_result);
375
376 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
377
378 std::string result;
379 ConsumeFd(std::move(output_fd), &result);
380
381 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\), code 9 \(SEGV_MTESERR\))");
382 ASSERT_MATCH(result, R"(Cause: \[MTE\]: Use After Free, 0 bytes into a 16-byte allocation)");
383#else
384 GTEST_SKIP() << "Requires aarch64 + ANDROID_EXPERIMENTAL_MTE";
385#endif
386}
387
388TEST_F(CrasherTest, mte_overflow) {
389#if defined(__aarch64__) && defined(ANDROID_EXPERIMENTAL_MTE)
390 if (!mte_supported()) {
391 GTEST_SKIP() << "Requires MTE";
392 }
393
394 int intercept_result;
395 unique_fd output_fd;
396 StartProcess([]() {
397 SetTagCheckingLevelSync();
398 volatile int* p = (volatile int*)malloc(16);
399 p[4] = 42;
400 });
401
402 StartIntercept(&output_fd);
403 FinishCrasher();
404 AssertDeath(SIGSEGV);
405 FinishIntercept(&intercept_result);
406
407 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
408
409 std::string result;
410 ConsumeFd(std::move(output_fd), &result);
411
412 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\))");
413 ASSERT_MATCH(result, R"(Cause: \[MTE\]: Buffer Overflow, 0 bytes right of a 16-byte allocation)");
414#else
415 GTEST_SKIP() << "Requires aarch64 + ANDROID_EXPERIMENTAL_MTE";
416#endif
417}
418
419TEST_F(CrasherTest, mte_underflow) {
420#if defined(__aarch64__) && defined(ANDROID_EXPERIMENTAL_MTE)
421 if (!mte_supported()) {
422 GTEST_SKIP() << "Requires MTE";
423 }
424
425 int intercept_result;
426 unique_fd output_fd;
427 StartProcess([]() {
428 SetTagCheckingLevelSync();
429 volatile int* p = (volatile int*)malloc(16);
430 p[-1] = 42;
431 });
432
433 StartIntercept(&output_fd);
434 FinishCrasher();
435 AssertDeath(SIGSEGV);
436 FinishIntercept(&intercept_result);
437
438 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
439
440 std::string result;
441 ConsumeFd(std::move(output_fd), &result);
442
443 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\), code 9 \(SEGV_MTESERR\))");
444 ASSERT_MATCH(result, R"(Cause: \[MTE\]: Buffer Underflow, 4 bytes left of a 16-byte allocation)");
445#else
446 GTEST_SKIP() << "Requires aarch64 + ANDROID_EXPERIMENTAL_MTE";
447#endif
448}
449
450TEST_F(CrasherTest, mte_multiple_causes) {
451#if defined(__aarch64__) && defined(ANDROID_EXPERIMENTAL_MTE)
452 if (!mte_supported()) {
453 GTEST_SKIP() << "Requires MTE";
454 }
455
456 int intercept_result;
457 unique_fd output_fd;
458 StartProcess([]() {
459 SetTagCheckingLevelSync();
460
461 // Make two allocations with the same tag and close to one another. Check for both properties
462 // with a bounds check -- this relies on the fact that only if the allocations have the same tag
463 // would they be measured as closer than 128 bytes to each other. Otherwise they would be about
464 // (some non-zero value << 56) apart.
465 //
466 // The out-of-bounds access will be considered either an overflow of one or an underflow of the
467 // other.
468 std::set<uintptr_t> allocs;
469 for (int i = 0; i != 4096; ++i) {
470 uintptr_t alloc = reinterpret_cast<uintptr_t>(malloc(16));
471 auto it = allocs.insert(alloc).first;
472 if (it != allocs.begin() && *std::prev(it) + 128 > alloc) {
473 *reinterpret_cast<int*>(*std::prev(it) + 16) = 42;
474 }
475 if (std::next(it) != allocs.end() && alloc + 128 > *std::next(it)) {
476 *reinterpret_cast<int*>(alloc + 16) = 42;
477 }
478 }
479 });
480
481 StartIntercept(&output_fd);
482 FinishCrasher();
483 AssertDeath(SIGSEGV);
484 FinishIntercept(&intercept_result);
485
486 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
487
488 std::string result;
489 ConsumeFd(std::move(output_fd), &result);
490
491 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\))");
492 ASSERT_MATCH(
493 result,
494 R"(Note: multiple potential causes for this crash were detected, listing them in decreasing order of probability.)");
495
496 // Adjacent untracked allocations may cause us to see the wrong underflow here (or only
497 // overflows), so we can't match explicitly for an underflow message.
498 ASSERT_MATCH(result, R"(Cause: \[MTE\]: Buffer Overflow, 0 bytes right of a 16-byte allocation)");
499#else
500 GTEST_SKIP() << "Requires aarch64 + ANDROID_EXPERIMENTAL_MTE";
501#endif
502}
503
Josh Gaocdea7502017-11-01 15:00:40 -0700504TEST_F(CrasherTest, LD_PRELOAD) {
505 int intercept_result;
506 unique_fd output_fd;
507 StartProcess([]() {
508 setenv("LD_PRELOAD", "nonexistent.so", 1);
509 *reinterpret_cast<volatile char*>(0xdead) = '1';
510 });
511
512 StartIntercept(&output_fd);
513 FinishCrasher();
514 AssertDeath(SIGSEGV);
515 FinishIntercept(&intercept_result);
516
517 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
518
519 std::string result;
520 ConsumeFd(std::move(output_fd), &result);
521 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\), code 1 \(SEGV_MAPERR\), fault addr 0xdead)");
522}
523
Josh Gaocbe70cb2016-10-18 18:17:52 -0700524TEST_F(CrasherTest, abort) {
525 int intercept_result;
526 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800527 StartProcess([]() {
528 abort();
529 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700530 StartIntercept(&output_fd);
531 FinishCrasher();
532 AssertDeath(SIGABRT);
533 FinishIntercept(&intercept_result);
534
535 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
536
537 std::string result;
538 ConsumeFd(std::move(output_fd), &result);
Andreas Gampe26cbafb2017-06-22 20:14:43 -0700539 ASSERT_BACKTRACE_FRAME(result, "abort");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700540}
541
542TEST_F(CrasherTest, signal) {
543 int intercept_result;
544 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800545 StartProcess([]() {
Josh Gao2b2ae0c2017-08-21 14:31:17 -0700546 while (true) {
547 sleep(1);
548 }
Josh Gao502cfd22017-02-17 01:39:15 -0800549 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700550 StartIntercept(&output_fd);
Josh Gao2b2ae0c2017-08-21 14:31:17 -0700551 FinishCrasher();
Josh Gaocbe70cb2016-10-18 18:17:52 -0700552 ASSERT_EQ(0, kill(crasher_pid, SIGSEGV));
553
554 AssertDeath(SIGSEGV);
555 FinishIntercept(&intercept_result);
556
557 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
558
559 std::string result;
560 ConsumeFd(std::move(output_fd), &result);
Elliott Hughes89722702018-05-02 10:47:00 -0700561 ASSERT_MATCH(
562 result,
563 R"(signal 11 \(SIGSEGV\), code 0 \(SI_USER from pid \d+, uid \d+\), fault addr --------)");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700564 ASSERT_MATCH(result, R"(backtrace:)");
565}
566
567TEST_F(CrasherTest, abort_message) {
568 int intercept_result;
569 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800570 StartProcess([]() {
Josh Gao1cc7bd82018-02-13 13:16:17 -0800571 // Arrived at experimentally;
572 // logd truncates at 4062.
573 // strlen("Abort message: ''") is 17.
574 // That's 4045, but we also want a NUL.
575 char buf[4045 + 1];
576 memset(buf, 'x', sizeof(buf));
577 buf[sizeof(buf) - 1] = '\0';
578 android_set_abort_message(buf);
Josh Gao502cfd22017-02-17 01:39:15 -0800579 abort();
580 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700581 StartIntercept(&output_fd);
582 FinishCrasher();
583 AssertDeath(SIGABRT);
584 FinishIntercept(&intercept_result);
585
586 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
587
588 std::string result;
589 ConsumeFd(std::move(output_fd), &result);
Josh Gao1cc7bd82018-02-13 13:16:17 -0800590 ASSERT_MATCH(result, R"(Abort message: 'x{4045}')");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700591}
592
Josh Gaoe06f2a42017-04-27 16:50:38 -0700593TEST_F(CrasherTest, abort_message_backtrace) {
594 int intercept_result;
595 unique_fd output_fd;
596 StartProcess([]() {
597 android_set_abort_message("not actually aborting");
Josh Gaoa48b41b2019-12-13 14:11:04 -0800598 raise(BIONIC_SIGNAL_DEBUGGER);
Josh Gaoe06f2a42017-04-27 16:50:38 -0700599 exit(0);
600 });
601 StartIntercept(&output_fd);
602 FinishCrasher();
603 AssertDeath(0);
604 FinishIntercept(&intercept_result);
605
606 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
607
608 std::string result;
609 ConsumeFd(std::move(output_fd), &result);
610 ASSERT_NOT_MATCH(result, R"(Abort message:)");
611}
612
Josh Gaocbe70cb2016-10-18 18:17:52 -0700613TEST_F(CrasherTest, intercept_timeout) {
614 int intercept_result;
615 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800616 StartProcess([]() {
617 abort();
618 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700619 StartIntercept(&output_fd);
620
621 // Don't let crasher finish until we timeout.
622 FinishIntercept(&intercept_result);
623
624 ASSERT_NE(1, intercept_result) << "tombstoned reported success? (intercept_result = "
625 << intercept_result << ")";
626
627 FinishCrasher();
628 AssertDeath(SIGABRT);
629}
630
631TEST_F(CrasherTest, wait_for_gdb) {
632 if (!android::base::SetProperty(kWaitForGdbKey, "1")) {
633 FAIL() << "failed to enable wait_for_gdb";
634 }
635 sleep(1);
636
Josh Gao502cfd22017-02-17 01:39:15 -0800637 StartProcess([]() {
638 abort();
639 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700640 FinishCrasher();
641
642 int status;
Christopher Ferris172b0a02019-09-18 17:48:30 -0700643 ASSERT_EQ(crasher_pid, TEMP_FAILURE_RETRY(waitpid(crasher_pid, &status, WUNTRACED)));
Josh Gaocbe70cb2016-10-18 18:17:52 -0700644 ASSERT_TRUE(WIFSTOPPED(status));
645 ASSERT_EQ(SIGSTOP, WSTOPSIG(status));
646
647 ASSERT_EQ(0, kill(crasher_pid, SIGCONT));
648
649 AssertDeath(SIGABRT);
650}
651
Josh Gaocbe70cb2016-10-18 18:17:52 -0700652TEST_F(CrasherTest, backtrace) {
653 std::string result;
654 int intercept_result;
655 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800656
657 StartProcess([]() {
658 abort();
659 });
Narayan Kamatha73df602017-05-24 15:07:25 +0100660 StartIntercept(&output_fd, kDebuggerdNativeBacktrace);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700661
662 std::this_thread::sleep_for(500ms);
663
664 sigval val;
665 val.sival_int = 1;
Josh Gaoa48b41b2019-12-13 14:11:04 -0800666 ASSERT_EQ(0, sigqueue(crasher_pid, BIONIC_SIGNAL_DEBUGGER, val)) << strerror(errno);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700667 FinishIntercept(&intercept_result);
668 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
669 ConsumeFd(std::move(output_fd), &result);
Jaesung Chung58778e12017-06-15 18:20:34 +0900670 ASSERT_BACKTRACE_FRAME(result, "read");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700671
672 int status;
673 ASSERT_EQ(0, waitpid(crasher_pid, &status, WNOHANG | WUNTRACED));
674
675 StartIntercept(&output_fd);
676 FinishCrasher();
677 AssertDeath(SIGABRT);
678 FinishIntercept(&intercept_result);
679 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
680 ConsumeFd(std::move(output_fd), &result);
Andreas Gampe26cbafb2017-06-22 20:14:43 -0700681 ASSERT_BACKTRACE_FRAME(result, "abort");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700682}
Josh Gaofca7ca32017-01-23 12:05:35 -0800683
684TEST_F(CrasherTest, PR_SET_DUMPABLE_0_crash) {
Josh Gao502cfd22017-02-17 01:39:15 -0800685 int intercept_result;
686 unique_fd output_fd;
Josh Gaofca7ca32017-01-23 12:05:35 -0800687 StartProcess([]() {
688 prctl(PR_SET_DUMPABLE, 0);
Josh Gao502cfd22017-02-17 01:39:15 -0800689 abort();
Josh Gaofca7ca32017-01-23 12:05:35 -0800690 });
Josh Gao502cfd22017-02-17 01:39:15 -0800691
692 StartIntercept(&output_fd);
693 FinishCrasher();
694 AssertDeath(SIGABRT);
695 FinishIntercept(&intercept_result);
696
697 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
698
699 std::string result;
700 ConsumeFd(std::move(output_fd), &result);
Andreas Gampe26cbafb2017-06-22 20:14:43 -0700701 ASSERT_BACKTRACE_FRAME(result, "abort");
Josh Gaofca7ca32017-01-23 12:05:35 -0800702}
703
Josh Gao502cfd22017-02-17 01:39:15 -0800704TEST_F(CrasherTest, capabilities) {
705 ASSERT_EQ(0U, getuid()) << "capability test requires root";
706
Josh Gaofca7ca32017-01-23 12:05:35 -0800707 StartProcess([]() {
Josh Gao502cfd22017-02-17 01:39:15 -0800708 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) != 0) {
709 err(1, "failed to set PR_SET_KEEPCAPS");
710 }
711
712 if (setresuid(1, 1, 1) != 0) {
713 err(1, "setresuid failed");
714 }
715
716 __user_cap_header_struct capheader;
717 __user_cap_data_struct capdata[2];
718 memset(&capheader, 0, sizeof(capheader));
719 memset(&capdata, 0, sizeof(capdata));
720
721 capheader.version = _LINUX_CAPABILITY_VERSION_3;
722 capheader.pid = 0;
723
724 // Turn on every third capability.
725 static_assert(CAP_LAST_CAP > 33, "CAP_LAST_CAP <= 32");
726 for (int i = 0; i < CAP_LAST_CAP; i += 3) {
727 capdata[CAP_TO_INDEX(i)].permitted |= CAP_TO_MASK(i);
728 capdata[CAP_TO_INDEX(i)].effective |= CAP_TO_MASK(i);
729 }
730
731 // Make sure CAP_SYS_PTRACE is off.
732 capdata[CAP_TO_INDEX(CAP_SYS_PTRACE)].permitted &= ~(CAP_TO_MASK(CAP_SYS_PTRACE));
733 capdata[CAP_TO_INDEX(CAP_SYS_PTRACE)].effective &= ~(CAP_TO_MASK(CAP_SYS_PTRACE));
734
735 if (capset(&capheader, &capdata[0]) != 0) {
736 err(1, "capset failed");
737 }
738
739 if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_CLEAR_ALL, 0, 0, 0) != 0) {
740 err(1, "failed to drop ambient capabilities");
741 }
742
Josh Gaoa5199a92017-04-03 13:18:34 -0700743 pthread_setname_np(pthread_self(), "thread_name");
Josh Gao502cfd22017-02-17 01:39:15 -0800744 raise(SIGSYS);
Josh Gaofca7ca32017-01-23 12:05:35 -0800745 });
Josh Gao502cfd22017-02-17 01:39:15 -0800746
747 unique_fd output_fd;
748 StartIntercept(&output_fd);
749 FinishCrasher();
750 AssertDeath(SIGSYS);
751
752 std::string result;
753 int intercept_result;
754 FinishIntercept(&intercept_result);
755 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
756 ConsumeFd(std::move(output_fd), &result);
Josh Gaoa5199a92017-04-03 13:18:34 -0700757 ASSERT_MATCH(result, R"(name: thread_name\s+>>> .+debuggerd_test(32|64) <<<)");
Jaesung Chung58778e12017-06-15 18:20:34 +0900758 ASSERT_BACKTRACE_FRAME(result, "tgkill");
Josh Gaofca7ca32017-01-23 12:05:35 -0800759}
Josh Gaoc3c8c022017-02-13 16:36:18 -0800760
Josh Gao2e7b8e22017-05-04 17:12:57 -0700761TEST_F(CrasherTest, fake_pid) {
762 int intercept_result;
763 unique_fd output_fd;
764
765 // Prime the getpid/gettid caches.
766 UNUSED(getpid());
767 UNUSED(gettid());
768
769 std::function<pid_t()> clone_fn = []() {
770 return syscall(__NR_clone, SIGCHLD, nullptr, nullptr, nullptr, nullptr);
771 };
772 StartProcess(
773 []() {
774 ASSERT_NE(getpid(), syscall(__NR_getpid));
775 ASSERT_NE(gettid(), syscall(__NR_gettid));
776 raise(SIGSEGV);
777 },
778 clone_fn);
779
780 StartIntercept(&output_fd);
781 FinishCrasher();
782 AssertDeath(SIGSEGV);
783 FinishIntercept(&intercept_result);
784
785 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
786
787 std::string result;
788 ConsumeFd(std::move(output_fd), &result);
Jaesung Chung58778e12017-06-15 18:20:34 +0900789 ASSERT_BACKTRACE_FRAME(result, "tgkill");
Josh Gao2e7b8e22017-05-04 17:12:57 -0700790}
791
Josh Gaoe04ca272018-01-16 15:38:17 -0800792static const char* const kDebuggerdSeccompPolicy =
793 "/system/etc/seccomp_policy/crash_dump." ABI_STRING ".policy";
794
Josh Gao70adac62018-02-22 11:38:33 -0800795static pid_t seccomp_fork_impl(void (*prejail)()) {
Josh Gao6f9eeec2018-09-12 13:55:47 -0700796 std::string policy;
797 if (!android::base::ReadFileToString(kDebuggerdSeccompPolicy, &policy)) {
798 PLOG(FATAL) << "failed to read policy file";
799 }
800
801 // Allow a bunch of syscalls used by the tests.
802 policy += "\nclone: 1";
803 policy += "\nsigaltstack: 1";
804 policy += "\nnanosleep: 1";
Christopher Ferrisab606682019-09-17 15:31:47 -0700805 policy += "\ngetrlimit: 1";
806 policy += "\nugetrlimit: 1";
Josh Gao6f9eeec2018-09-12 13:55:47 -0700807
808 FILE* tmp_file = tmpfile();
809 if (!tmp_file) {
810 PLOG(FATAL) << "tmpfile failed";
811 }
812
Christopher Ferris172b0a02019-09-18 17:48:30 -0700813 unique_fd tmp_fd(TEMP_FAILURE_RETRY(dup(fileno(tmp_file))));
Josh Gao6f9eeec2018-09-12 13:55:47 -0700814 if (!android::base::WriteStringToFd(policy, tmp_fd.get())) {
815 PLOG(FATAL) << "failed to write policy to tmpfile";
816 }
817
818 if (lseek(tmp_fd.get(), 0, SEEK_SET) != 0) {
819 PLOG(FATAL) << "failed to seek tmp_fd";
Josh Gaoe04ca272018-01-16 15:38:17 -0800820 }
821
822 ScopedMinijail jail{minijail_new()};
823 if (!jail) {
824 LOG(FATAL) << "failed to create minijail";
825 }
826
827 minijail_no_new_privs(jail.get());
828 minijail_log_seccomp_filter_failures(jail.get());
829 minijail_use_seccomp_filter(jail.get());
Josh Gao6f9eeec2018-09-12 13:55:47 -0700830 minijail_parse_seccomp_filters_from_fd(jail.get(), tmp_fd.release());
Josh Gaoe04ca272018-01-16 15:38:17 -0800831
832 pid_t result = fork();
833 if (result == -1) {
834 return result;
835 } else if (result != 0) {
836 return result;
837 }
838
839 // Spawn and detach a thread that spins forever.
840 std::atomic<bool> thread_ready(false);
841 std::thread thread([&jail, &thread_ready]() {
842 minijail_enter(jail.get());
843 thread_ready = true;
844 for (;;)
845 ;
846 });
847 thread.detach();
848
849 while (!thread_ready) {
850 continue;
851 }
852
Josh Gao70adac62018-02-22 11:38:33 -0800853 if (prejail) {
854 prejail();
855 }
856
Josh Gaoe04ca272018-01-16 15:38:17 -0800857 minijail_enter(jail.get());
858 return result;
859}
860
Josh Gao70adac62018-02-22 11:38:33 -0800861static pid_t seccomp_fork() {
862 return seccomp_fork_impl(nullptr);
863}
864
Josh Gaoe04ca272018-01-16 15:38:17 -0800865TEST_F(CrasherTest, seccomp_crash) {
866 int intercept_result;
867 unique_fd output_fd;
868
869 StartProcess([]() { abort(); }, &seccomp_fork);
870
871 StartIntercept(&output_fd);
872 FinishCrasher();
873 AssertDeath(SIGABRT);
874 FinishIntercept(&intercept_result);
875 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
876
877 std::string result;
878 ConsumeFd(std::move(output_fd), &result);
879 ASSERT_BACKTRACE_FRAME(result, "abort");
880}
881
Josh Gao70adac62018-02-22 11:38:33 -0800882static pid_t seccomp_fork_rlimit() {
883 return seccomp_fork_impl([]() {
884 struct rlimit rlim = {
885 .rlim_cur = 512 * 1024 * 1024,
886 .rlim_max = 512 * 1024 * 1024,
887 };
888
889 if (setrlimit(RLIMIT_AS, &rlim) != 0) {
890 raise(SIGINT);
891 }
892 });
893}
894
895TEST_F(CrasherTest, seccomp_crash_oom) {
896 int intercept_result;
897 unique_fd output_fd;
898
899 StartProcess(
900 []() {
901 std::vector<void*> vec;
902 for (int i = 0; i < 512; ++i) {
903 char* buf = static_cast<char*>(malloc(1024 * 1024));
904 if (!buf) {
905 abort();
906 }
907 memset(buf, 0xff, 1024 * 1024);
908 vec.push_back(buf);
909 }
910 },
911 &seccomp_fork_rlimit);
912
913 StartIntercept(&output_fd);
914 FinishCrasher();
915 AssertDeath(SIGABRT);
916 FinishIntercept(&intercept_result);
917 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
918
919 // We can't actually generate a backtrace, just make sure that the process terminates.
920}
921
Josh Gaoe04ca272018-01-16 15:38:17 -0800922__attribute__((noinline)) extern "C" bool raise_debugger_signal(DebuggerdDumpType dump_type) {
923 siginfo_t siginfo;
924 siginfo.si_code = SI_QUEUE;
925 siginfo.si_pid = getpid();
926 siginfo.si_uid = getuid();
927
928 if (dump_type != kDebuggerdNativeBacktrace && dump_type != kDebuggerdTombstone) {
929 PLOG(FATAL) << "invalid dump type";
930 }
931
932 siginfo.si_value.sival_int = dump_type == kDebuggerdNativeBacktrace;
933
Josh Gaoa48b41b2019-12-13 14:11:04 -0800934 if (syscall(__NR_rt_tgsigqueueinfo, getpid(), gettid(), BIONIC_SIGNAL_DEBUGGER, &siginfo) != 0) {
Josh Gaoe04ca272018-01-16 15:38:17 -0800935 PLOG(ERROR) << "libdebuggerd_client: failed to send signal to self";
936 return false;
937 }
938
939 return true;
940}
941
942TEST_F(CrasherTest, seccomp_tombstone) {
943 int intercept_result;
944 unique_fd output_fd;
945
946 static const auto dump_type = kDebuggerdTombstone;
947 StartProcess(
948 []() {
949 raise_debugger_signal(dump_type);
950 _exit(0);
951 },
952 &seccomp_fork);
953
954 StartIntercept(&output_fd, dump_type);
955 FinishCrasher();
956 AssertDeath(0);
957 FinishIntercept(&intercept_result);
958 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
959
960 std::string result;
961 ConsumeFd(std::move(output_fd), &result);
962 ASSERT_BACKTRACE_FRAME(result, "raise_debugger_signal");
963}
964
Josh Gao6f9eeec2018-09-12 13:55:47 -0700965extern "C" void foo() {
966 LOG(INFO) << "foo";
967 std::this_thread::sleep_for(1s);
968}
969
970extern "C" void bar() {
971 LOG(INFO) << "bar";
972 std::this_thread::sleep_for(1s);
973}
974
Josh Gaoe04ca272018-01-16 15:38:17 -0800975TEST_F(CrasherTest, seccomp_backtrace) {
976 int intercept_result;
977 unique_fd output_fd;
978
979 static const auto dump_type = kDebuggerdNativeBacktrace;
980 StartProcess(
981 []() {
Josh Gao6f9eeec2018-09-12 13:55:47 -0700982 std::thread a(foo);
983 std::thread b(bar);
984
985 std::this_thread::sleep_for(100ms);
986
Josh Gaoe04ca272018-01-16 15:38:17 -0800987 raise_debugger_signal(dump_type);
988 _exit(0);
989 },
990 &seccomp_fork);
991
992 StartIntercept(&output_fd, dump_type);
993 FinishCrasher();
994 AssertDeath(0);
995 FinishIntercept(&intercept_result);
996 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
997
998 std::string result;
999 ConsumeFd(std::move(output_fd), &result);
1000 ASSERT_BACKTRACE_FRAME(result, "raise_debugger_signal");
Josh Gao6f9eeec2018-09-12 13:55:47 -07001001 ASSERT_BACKTRACE_FRAME(result, "foo");
1002 ASSERT_BACKTRACE_FRAME(result, "bar");
Josh Gaoe04ca272018-01-16 15:38:17 -08001003}
1004
1005TEST_F(CrasherTest, seccomp_crash_logcat) {
1006 StartProcess([]() { abort(); }, &seccomp_fork);
1007 FinishCrasher();
1008
1009 // Make sure we don't get SIGSYS when trying to dump a crash to logcat.
1010 AssertDeath(SIGABRT);
1011}
1012
Josh Gaofd13bf02017-08-18 15:37:26 -07001013TEST_F(CrasherTest, competing_tracer) {
1014 int intercept_result;
1015 unique_fd output_fd;
1016 StartProcess([]() {
Josh Gao2b2ae0c2017-08-21 14:31:17 -07001017 raise(SIGABRT);
Josh Gaofd13bf02017-08-18 15:37:26 -07001018 });
1019
1020 StartIntercept(&output_fd);
Josh Gaofd13bf02017-08-18 15:37:26 -07001021
1022 ASSERT_EQ(0, ptrace(PTRACE_SEIZE, crasher_pid, 0, 0));
Josh Gao2b2ae0c2017-08-21 14:31:17 -07001023 FinishCrasher();
Josh Gaofd13bf02017-08-18 15:37:26 -07001024
1025 int status;
Christopher Ferris172b0a02019-09-18 17:48:30 -07001026 ASSERT_EQ(crasher_pid, TEMP_FAILURE_RETRY(waitpid(crasher_pid, &status, 0)));
Josh Gaofd13bf02017-08-18 15:37:26 -07001027 ASSERT_TRUE(WIFSTOPPED(status));
1028 ASSERT_EQ(SIGABRT, WSTOPSIG(status));
1029
1030 ASSERT_EQ(0, ptrace(PTRACE_CONT, crasher_pid, 0, SIGABRT));
1031 FinishIntercept(&intercept_result);
1032 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1033
1034 std::string result;
1035 ConsumeFd(std::move(output_fd), &result);
1036 std::string regex = R"(failed to attach to thread \d+, already traced by )";
1037 regex += std::to_string(gettid());
1038 regex += R"( \(.+debuggerd_test)";
1039 ASSERT_MATCH(result, regex.c_str());
1040
Christopher Ferris172b0a02019-09-18 17:48:30 -07001041 ASSERT_EQ(crasher_pid, TEMP_FAILURE_RETRY(waitpid(crasher_pid, &status, 0)));
Josh Gao2b2ae0c2017-08-21 14:31:17 -07001042 ASSERT_TRUE(WIFSTOPPED(status));
1043 ASSERT_EQ(SIGABRT, WSTOPSIG(status));
1044
Josh Gaofd13bf02017-08-18 15:37:26 -07001045 ASSERT_EQ(0, ptrace(PTRACE_DETACH, crasher_pid, 0, SIGABRT));
1046 AssertDeath(SIGABRT);
1047}
1048
Josh Gaobf06a402018-08-27 16:34:01 -07001049TEST_F(CrasherTest, fdsan_warning_abort_message) {
1050 int intercept_result;
1051 unique_fd output_fd;
1052
1053 StartProcess([]() {
1054 android_fdsan_set_error_level(ANDROID_FDSAN_ERROR_LEVEL_WARN_ONCE);
Christopher Ferris172b0a02019-09-18 17:48:30 -07001055 unique_fd fd(TEMP_FAILURE_RETRY(open("/dev/null", O_RDONLY | O_CLOEXEC)));
Josh Gaobf06a402018-08-27 16:34:01 -07001056 if (fd == -1) {
1057 abort();
1058 }
1059 close(fd.get());
1060 _exit(0);
1061 });
1062
1063 StartIntercept(&output_fd);
1064 FinishCrasher();
1065 AssertDeath(0);
1066 FinishIntercept(&intercept_result);
1067 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1068
1069 std::string result;
1070 ConsumeFd(std::move(output_fd), &result);
1071 ASSERT_MATCH(result, "Abort message: 'attempted to close");
1072}
1073
Josh Gaoc3c8c022017-02-13 16:36:18 -08001074TEST(crash_dump, zombie) {
1075 pid_t forkpid = fork();
1076
Josh Gaoc3c8c022017-02-13 16:36:18 -08001077 pid_t rc;
1078 int status;
1079
1080 if (forkpid == 0) {
1081 errno = 0;
1082 rc = waitpid(-1, &status, WNOHANG | __WALL | __WNOTHREAD);
1083 if (rc != -1 || errno != ECHILD) {
1084 errx(2, "first waitpid returned %d (%s), expected failure with ECHILD", rc, strerror(errno));
1085 }
1086
Josh Gaoa48b41b2019-12-13 14:11:04 -08001087 raise(BIONIC_SIGNAL_DEBUGGER);
Josh Gaoc3c8c022017-02-13 16:36:18 -08001088
1089 errno = 0;
Christopher Ferris172b0a02019-09-18 17:48:30 -07001090 rc = TEMP_FAILURE_RETRY(waitpid(-1, &status, __WALL | __WNOTHREAD));
Josh Gaoc3c8c022017-02-13 16:36:18 -08001091 if (rc != -1 || errno != ECHILD) {
1092 errx(2, "second waitpid returned %d (%s), expected failure with ECHILD", rc, strerror(errno));
1093 }
1094 _exit(0);
1095 } else {
Christopher Ferris172b0a02019-09-18 17:48:30 -07001096 rc = TEMP_FAILURE_RETRY(waitpid(forkpid, &status, 0));
Josh Gaoc3c8c022017-02-13 16:36:18 -08001097 ASSERT_EQ(forkpid, rc);
1098 ASSERT_TRUE(WIFEXITED(status));
1099 ASSERT_EQ(0, WEXITSTATUS(status));
1100 }
1101}
Josh Gao352a8452017-03-30 16:46:21 -07001102
1103TEST(tombstoned, no_notify) {
1104 // Do this a few times.
1105 for (int i = 0; i < 3; ++i) {
1106 pid_t pid = 123'456'789 + i;
1107
1108 unique_fd intercept_fd, output_fd;
Narayan Kamathca5e9082017-06-02 15:42:06 +01001109 InterceptStatus status;
1110 tombstoned_intercept(pid, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
1111 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gao352a8452017-03-30 16:46:21 -07001112
1113 {
1114 unique_fd tombstoned_socket, input_fd;
Narayan Kamatha73df602017-05-24 15:07:25 +01001115 ASSERT_TRUE(tombstoned_connect(pid, &tombstoned_socket, &input_fd, kDebuggerdTombstone));
Josh Gao352a8452017-03-30 16:46:21 -07001116 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), &pid, sizeof(pid)));
1117 }
1118
1119 pid_t read_pid;
1120 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), &read_pid, sizeof(read_pid)));
1121 ASSERT_EQ(read_pid, pid);
1122 }
1123}
1124
1125TEST(tombstoned, stress) {
1126 // Spawn threads to simultaneously do a bunch of failing dumps and a bunch of successful dumps.
1127 static constexpr int kDumpCount = 100;
1128
1129 std::atomic<bool> start(false);
1130 std::vector<std::thread> threads;
1131 threads.emplace_back([&start]() {
1132 while (!start) {
1133 continue;
1134 }
1135
1136 // Use a way out of range pid, to avoid stomping on an actual process.
1137 pid_t pid_base = 1'000'000;
1138
1139 for (int dump = 0; dump < kDumpCount; ++dump) {
1140 pid_t pid = pid_base + dump;
1141
1142 unique_fd intercept_fd, output_fd;
Narayan Kamathca5e9082017-06-02 15:42:06 +01001143 InterceptStatus status;
1144 tombstoned_intercept(pid, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
1145 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gao352a8452017-03-30 16:46:21 -07001146
1147 // Pretend to crash, and then immediately close the socket.
1148 unique_fd sockfd(socket_local_client(kTombstonedCrashSocketName,
1149 ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_SEQPACKET));
1150 if (sockfd == -1) {
1151 FAIL() << "failed to connect to tombstoned: " << strerror(errno);
1152 }
1153 TombstonedCrashPacket packet = {};
1154 packet.packet_type = CrashPacketType::kDumpRequest;
1155 packet.packet.dump_request.pid = pid;
1156 if (TEMP_FAILURE_RETRY(write(sockfd, &packet, sizeof(packet))) != sizeof(packet)) {
1157 FAIL() << "failed to write to tombstoned: " << strerror(errno);
1158 }
1159
1160 continue;
1161 }
1162 });
1163
1164 threads.emplace_back([&start]() {
1165 while (!start) {
1166 continue;
1167 }
1168
1169 // Use a way out of range pid, to avoid stomping on an actual process.
1170 pid_t pid_base = 2'000'000;
1171
1172 for (int dump = 0; dump < kDumpCount; ++dump) {
1173 pid_t pid = pid_base + dump;
1174
1175 unique_fd intercept_fd, output_fd;
Narayan Kamathca5e9082017-06-02 15:42:06 +01001176 InterceptStatus status;
1177 tombstoned_intercept(pid, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
1178 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gao352a8452017-03-30 16:46:21 -07001179
1180 {
1181 unique_fd tombstoned_socket, input_fd;
Narayan Kamatha73df602017-05-24 15:07:25 +01001182 ASSERT_TRUE(tombstoned_connect(pid, &tombstoned_socket, &input_fd, kDebuggerdTombstone));
Josh Gao352a8452017-03-30 16:46:21 -07001183 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), &pid, sizeof(pid)));
1184 tombstoned_notify_completion(tombstoned_socket.get());
1185 }
1186
1187 // TODO: Fix the race that requires this sleep.
1188 std::this_thread::sleep_for(50ms);
1189
1190 pid_t read_pid;
1191 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), &read_pid, sizeof(read_pid)));
1192 ASSERT_EQ(read_pid, pid);
1193 }
1194 });
1195
1196 start = true;
1197
1198 for (std::thread& thread : threads) {
1199 thread.join();
1200 }
1201}
Narayan Kamathca5e9082017-06-02 15:42:06 +01001202
1203TEST(tombstoned, java_trace_intercept_smoke) {
1204 // Using a "real" PID is a little dangerous here - if the test fails
1205 // or crashes, we might end up getting a bogus / unreliable stack
1206 // trace.
1207 const pid_t self = getpid();
1208
1209 unique_fd intercept_fd, output_fd;
1210 InterceptStatus status;
1211 tombstoned_intercept(self, &intercept_fd, &output_fd, &status, kDebuggerdJavaBacktrace);
1212 ASSERT_EQ(InterceptStatus::kRegistered, status);
1213
1214 // First connect to tombstoned requesting a native backtrace. This
1215 // should result in a "regular" FD and not the installed intercept.
1216 const char native[] = "native";
1217 unique_fd tombstoned_socket, input_fd;
1218 ASSERT_TRUE(tombstoned_connect(self, &tombstoned_socket, &input_fd, kDebuggerdNativeBacktrace));
1219 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), native, sizeof(native)));
1220 tombstoned_notify_completion(tombstoned_socket.get());
1221
1222 // Then, connect to tombstoned asking for a java backtrace. This *should*
1223 // trigger the intercept.
1224 const char java[] = "java";
1225 ASSERT_TRUE(tombstoned_connect(self, &tombstoned_socket, &input_fd, kDebuggerdJavaBacktrace));
1226 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), java, sizeof(java)));
1227 tombstoned_notify_completion(tombstoned_socket.get());
1228
1229 char outbuf[sizeof(java)];
1230 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), outbuf, sizeof(outbuf)));
1231 ASSERT_STREQ("java", outbuf);
1232}
1233
1234TEST(tombstoned, multiple_intercepts) {
1235 const pid_t fake_pid = 1'234'567;
1236 unique_fd intercept_fd, output_fd;
1237 InterceptStatus status;
1238 tombstoned_intercept(fake_pid, &intercept_fd, &output_fd, &status, kDebuggerdJavaBacktrace);
1239 ASSERT_EQ(InterceptStatus::kRegistered, status);
1240
1241 unique_fd intercept_fd_2, output_fd_2;
1242 tombstoned_intercept(fake_pid, &intercept_fd_2, &output_fd_2, &status, kDebuggerdNativeBacktrace);
1243 ASSERT_EQ(InterceptStatus::kFailedAlreadyRegistered, status);
1244}
1245
1246TEST(tombstoned, intercept_any) {
1247 const pid_t fake_pid = 1'234'567;
1248
1249 unique_fd intercept_fd, output_fd;
1250 InterceptStatus status;
1251 tombstoned_intercept(fake_pid, &intercept_fd, &output_fd, &status, kDebuggerdNativeBacktrace);
1252 ASSERT_EQ(InterceptStatus::kRegistered, status);
1253
1254 const char any[] = "any";
1255 unique_fd tombstoned_socket, input_fd;
1256 ASSERT_TRUE(tombstoned_connect(fake_pid, &tombstoned_socket, &input_fd, kDebuggerdAnyIntercept));
1257 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), any, sizeof(any)));
1258 tombstoned_notify_completion(tombstoned_socket.get());
1259
1260 char outbuf[sizeof(any)];
1261 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), outbuf, sizeof(outbuf)));
1262 ASSERT_STREQ("any", outbuf);
1263}
Josh Gao2b22ae12018-09-12 14:51:03 -07001264
1265TEST(tombstoned, interceptless_backtrace) {
1266 // Generate 50 backtraces, and then check to see that we haven't created 50 new tombstones.
1267 auto get_tombstone_timestamps = []() -> std::map<int, time_t> {
1268 std::map<int, time_t> result;
1269 for (int i = 0; i < 99; ++i) {
1270 std::string path = android::base::StringPrintf("/data/tombstones/tombstone_%02d", i);
1271 struct stat st;
1272 if (stat(path.c_str(), &st) == 0) {
1273 result[i] = st.st_mtim.tv_sec;
1274 }
1275 }
1276 return result;
1277 };
1278
1279 auto before = get_tombstone_timestamps();
1280 for (int i = 0; i < 50; ++i) {
1281 raise_debugger_signal(kDebuggerdNativeBacktrace);
1282 }
1283 auto after = get_tombstone_timestamps();
1284
1285 int diff = 0;
1286 for (int i = 0; i < 99; ++i) {
1287 if (after.count(i) == 0) {
1288 continue;
1289 }
1290 if (before.count(i) == 0) {
1291 ++diff;
1292 continue;
1293 }
1294 if (before[i] != after[i]) {
1295 ++diff;
1296 }
1297 }
1298
1299 // We can't be sure that nothing's crash looping in the background.
1300 // This should be good enough, though...
1301 ASSERT_LT(diff, 10) << "too many new tombstones; is something crashing in the background?";
1302}
Christopher Ferris481e8372019-07-15 17:13:24 -07001303
1304static __attribute__((__noinline__)) void overflow_stack(void* p) {
1305 void* buf[1];
1306 buf[0] = p;
1307 static volatile void* global = buf;
1308 if (global) {
1309 global = buf;
1310 overflow_stack(&buf);
1311 }
1312}
1313
1314TEST_F(CrasherTest, stack_overflow) {
1315 int intercept_result;
1316 unique_fd output_fd;
1317 StartProcess([]() { overflow_stack(nullptr); });
1318
1319 StartIntercept(&output_fd);
1320 FinishCrasher();
1321 AssertDeath(SIGSEGV);
1322 FinishIntercept(&intercept_result);
1323
1324 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1325
1326 std::string result;
1327 ConsumeFd(std::move(output_fd), &result);
1328 ASSERT_MATCH(result, R"(Cause: stack pointer[^\n]*stack overflow.\n)");
1329}