blob: 9d7658eb0370948ca7b9b970335a26b0f1911e0a [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\))");
Peter Collingbournebbe69052020-05-08 10:11:19 -0700382 ASSERT_MATCH(result, R"(Cause: \[MTE\]: Use After Free, 0 bytes into a 16-byte allocation.*
383
384allocated by thread .*
385 #00 pc)");
386 ASSERT_MATCH(result, R"(deallocated by thread .*
387 #00 pc)");
Peter Collingbournef8622522020-04-07 14:07:32 -0700388#else
389 GTEST_SKIP() << "Requires aarch64 + ANDROID_EXPERIMENTAL_MTE";
390#endif
391}
392
393TEST_F(CrasherTest, mte_overflow) {
394#if defined(__aarch64__) && defined(ANDROID_EXPERIMENTAL_MTE)
395 if (!mte_supported()) {
396 GTEST_SKIP() << "Requires MTE";
397 }
398
399 int intercept_result;
400 unique_fd output_fd;
401 StartProcess([]() {
402 SetTagCheckingLevelSync();
403 volatile int* p = (volatile int*)malloc(16);
404 p[4] = 42;
405 });
406
407 StartIntercept(&output_fd);
408 FinishCrasher();
409 AssertDeath(SIGSEGV);
410 FinishIntercept(&intercept_result);
411
412 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
413
414 std::string result;
415 ConsumeFd(std::move(output_fd), &result);
416
417 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\))");
Peter Collingbournebbe69052020-05-08 10:11:19 -0700418 ASSERT_MATCH(result, R"(Cause: \[MTE\]: Buffer Overflow, 0 bytes right of a 16-byte allocation.*
419
420allocated by thread .*
421 #00 pc)");
Peter Collingbournef8622522020-04-07 14:07:32 -0700422#else
423 GTEST_SKIP() << "Requires aarch64 + ANDROID_EXPERIMENTAL_MTE";
424#endif
425}
426
427TEST_F(CrasherTest, mte_underflow) {
428#if defined(__aarch64__) && defined(ANDROID_EXPERIMENTAL_MTE)
429 if (!mte_supported()) {
430 GTEST_SKIP() << "Requires MTE";
431 }
432
433 int intercept_result;
434 unique_fd output_fd;
435 StartProcess([]() {
436 SetTagCheckingLevelSync();
437 volatile int* p = (volatile int*)malloc(16);
438 p[-1] = 42;
439 });
440
441 StartIntercept(&output_fd);
442 FinishCrasher();
443 AssertDeath(SIGSEGV);
444 FinishIntercept(&intercept_result);
445
446 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
447
448 std::string result;
449 ConsumeFd(std::move(output_fd), &result);
450
451 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\), code 9 \(SEGV_MTESERR\))");
Peter Collingbournebbe69052020-05-08 10:11:19 -0700452 ASSERT_MATCH(result, R"(Cause: \[MTE\]: Buffer Underflow, 4 bytes left of a 16-byte allocation.*
453
454allocated by thread .*
455 #00 pc)");
Peter Collingbournef8622522020-04-07 14:07:32 -0700456#else
457 GTEST_SKIP() << "Requires aarch64 + ANDROID_EXPERIMENTAL_MTE";
458#endif
459}
460
461TEST_F(CrasherTest, mte_multiple_causes) {
462#if defined(__aarch64__) && defined(ANDROID_EXPERIMENTAL_MTE)
463 if (!mte_supported()) {
464 GTEST_SKIP() << "Requires MTE";
465 }
466
467 int intercept_result;
468 unique_fd output_fd;
469 StartProcess([]() {
470 SetTagCheckingLevelSync();
471
472 // Make two allocations with the same tag and close to one another. Check for both properties
473 // with a bounds check -- this relies on the fact that only if the allocations have the same tag
474 // would they be measured as closer than 128 bytes to each other. Otherwise they would be about
475 // (some non-zero value << 56) apart.
476 //
477 // The out-of-bounds access will be considered either an overflow of one or an underflow of the
478 // other.
479 std::set<uintptr_t> allocs;
480 for (int i = 0; i != 4096; ++i) {
481 uintptr_t alloc = reinterpret_cast<uintptr_t>(malloc(16));
482 auto it = allocs.insert(alloc).first;
483 if (it != allocs.begin() && *std::prev(it) + 128 > alloc) {
484 *reinterpret_cast<int*>(*std::prev(it) + 16) = 42;
485 }
486 if (std::next(it) != allocs.end() && alloc + 128 > *std::next(it)) {
487 *reinterpret_cast<int*>(alloc + 16) = 42;
488 }
489 }
490 });
491
492 StartIntercept(&output_fd);
493 FinishCrasher();
494 AssertDeath(SIGSEGV);
495 FinishIntercept(&intercept_result);
496
497 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
498
499 std::string result;
500 ConsumeFd(std::move(output_fd), &result);
501
502 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\))");
503 ASSERT_MATCH(
504 result,
505 R"(Note: multiple potential causes for this crash were detected, listing them in decreasing order of probability.)");
506
507 // Adjacent untracked allocations may cause us to see the wrong underflow here (or only
508 // overflows), so we can't match explicitly for an underflow message.
509 ASSERT_MATCH(result, R"(Cause: \[MTE\]: Buffer Overflow, 0 bytes right of a 16-byte allocation)");
510#else
511 GTEST_SKIP() << "Requires aarch64 + ANDROID_EXPERIMENTAL_MTE";
512#endif
513}
514
Josh Gaocdea7502017-11-01 15:00:40 -0700515TEST_F(CrasherTest, LD_PRELOAD) {
516 int intercept_result;
517 unique_fd output_fd;
518 StartProcess([]() {
519 setenv("LD_PRELOAD", "nonexistent.so", 1);
520 *reinterpret_cast<volatile char*>(0xdead) = '1';
521 });
522
523 StartIntercept(&output_fd);
524 FinishCrasher();
525 AssertDeath(SIGSEGV);
526 FinishIntercept(&intercept_result);
527
528 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
529
530 std::string result;
531 ConsumeFd(std::move(output_fd), &result);
532 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\), code 1 \(SEGV_MAPERR\), fault addr 0xdead)");
533}
534
Josh Gaocbe70cb2016-10-18 18:17:52 -0700535TEST_F(CrasherTest, abort) {
536 int intercept_result;
537 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800538 StartProcess([]() {
539 abort();
540 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700541 StartIntercept(&output_fd);
542 FinishCrasher();
543 AssertDeath(SIGABRT);
544 FinishIntercept(&intercept_result);
545
546 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
547
548 std::string result;
549 ConsumeFd(std::move(output_fd), &result);
Andreas Gampe26cbafb2017-06-22 20:14:43 -0700550 ASSERT_BACKTRACE_FRAME(result, "abort");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700551}
552
553TEST_F(CrasherTest, signal) {
554 int intercept_result;
555 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800556 StartProcess([]() {
Josh Gao2b2ae0c2017-08-21 14:31:17 -0700557 while (true) {
558 sleep(1);
559 }
Josh Gao502cfd22017-02-17 01:39:15 -0800560 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700561 StartIntercept(&output_fd);
Josh Gao2b2ae0c2017-08-21 14:31:17 -0700562 FinishCrasher();
Josh Gaocbe70cb2016-10-18 18:17:52 -0700563 ASSERT_EQ(0, kill(crasher_pid, SIGSEGV));
564
565 AssertDeath(SIGSEGV);
566 FinishIntercept(&intercept_result);
567
568 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
569
570 std::string result;
571 ConsumeFd(std::move(output_fd), &result);
Elliott Hughes89722702018-05-02 10:47:00 -0700572 ASSERT_MATCH(
573 result,
574 R"(signal 11 \(SIGSEGV\), code 0 \(SI_USER from pid \d+, uid \d+\), fault addr --------)");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700575 ASSERT_MATCH(result, R"(backtrace:)");
576}
577
578TEST_F(CrasherTest, abort_message) {
579 int intercept_result;
580 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800581 StartProcess([]() {
Josh Gao1cc7bd82018-02-13 13:16:17 -0800582 // Arrived at experimentally;
583 // logd truncates at 4062.
584 // strlen("Abort message: ''") is 17.
585 // That's 4045, but we also want a NUL.
586 char buf[4045 + 1];
587 memset(buf, 'x', sizeof(buf));
588 buf[sizeof(buf) - 1] = '\0';
589 android_set_abort_message(buf);
Josh Gao502cfd22017-02-17 01:39:15 -0800590 abort();
591 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700592 StartIntercept(&output_fd);
593 FinishCrasher();
594 AssertDeath(SIGABRT);
595 FinishIntercept(&intercept_result);
596
597 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
598
599 std::string result;
600 ConsumeFd(std::move(output_fd), &result);
Josh Gao1cc7bd82018-02-13 13:16:17 -0800601 ASSERT_MATCH(result, R"(Abort message: 'x{4045}')");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700602}
603
Josh Gaoe06f2a42017-04-27 16:50:38 -0700604TEST_F(CrasherTest, abort_message_backtrace) {
605 int intercept_result;
606 unique_fd output_fd;
607 StartProcess([]() {
608 android_set_abort_message("not actually aborting");
Josh Gaoa48b41b2019-12-13 14:11:04 -0800609 raise(BIONIC_SIGNAL_DEBUGGER);
Josh Gaoe06f2a42017-04-27 16:50:38 -0700610 exit(0);
611 });
612 StartIntercept(&output_fd);
613 FinishCrasher();
614 AssertDeath(0);
615 FinishIntercept(&intercept_result);
616
617 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
618
619 std::string result;
620 ConsumeFd(std::move(output_fd), &result);
621 ASSERT_NOT_MATCH(result, R"(Abort message:)");
622}
623
Josh Gaocbe70cb2016-10-18 18:17:52 -0700624TEST_F(CrasherTest, intercept_timeout) {
625 int intercept_result;
626 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800627 StartProcess([]() {
628 abort();
629 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700630 StartIntercept(&output_fd);
631
632 // Don't let crasher finish until we timeout.
633 FinishIntercept(&intercept_result);
634
635 ASSERT_NE(1, intercept_result) << "tombstoned reported success? (intercept_result = "
636 << intercept_result << ")";
637
638 FinishCrasher();
639 AssertDeath(SIGABRT);
640}
641
642TEST_F(CrasherTest, wait_for_gdb) {
643 if (!android::base::SetProperty(kWaitForGdbKey, "1")) {
644 FAIL() << "failed to enable wait_for_gdb";
645 }
646 sleep(1);
647
Josh Gao502cfd22017-02-17 01:39:15 -0800648 StartProcess([]() {
649 abort();
650 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700651 FinishCrasher();
652
653 int status;
Christopher Ferris172b0a02019-09-18 17:48:30 -0700654 ASSERT_EQ(crasher_pid, TEMP_FAILURE_RETRY(waitpid(crasher_pid, &status, WUNTRACED)));
Josh Gaocbe70cb2016-10-18 18:17:52 -0700655 ASSERT_TRUE(WIFSTOPPED(status));
656 ASSERT_EQ(SIGSTOP, WSTOPSIG(status));
657
658 ASSERT_EQ(0, kill(crasher_pid, SIGCONT));
659
660 AssertDeath(SIGABRT);
661}
662
Josh Gaocbe70cb2016-10-18 18:17:52 -0700663TEST_F(CrasherTest, backtrace) {
664 std::string result;
665 int intercept_result;
666 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800667
668 StartProcess([]() {
669 abort();
670 });
Narayan Kamatha73df602017-05-24 15:07:25 +0100671 StartIntercept(&output_fd, kDebuggerdNativeBacktrace);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700672
673 std::this_thread::sleep_for(500ms);
674
675 sigval val;
676 val.sival_int = 1;
Josh Gaoa48b41b2019-12-13 14:11:04 -0800677 ASSERT_EQ(0, sigqueue(crasher_pid, BIONIC_SIGNAL_DEBUGGER, val)) << strerror(errno);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700678 FinishIntercept(&intercept_result);
679 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
680 ConsumeFd(std::move(output_fd), &result);
Jaesung Chung58778e12017-06-15 18:20:34 +0900681 ASSERT_BACKTRACE_FRAME(result, "read");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700682
683 int status;
684 ASSERT_EQ(0, waitpid(crasher_pid, &status, WNOHANG | WUNTRACED));
685
686 StartIntercept(&output_fd);
687 FinishCrasher();
688 AssertDeath(SIGABRT);
689 FinishIntercept(&intercept_result);
690 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
691 ConsumeFd(std::move(output_fd), &result);
Andreas Gampe26cbafb2017-06-22 20:14:43 -0700692 ASSERT_BACKTRACE_FRAME(result, "abort");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700693}
Josh Gaofca7ca32017-01-23 12:05:35 -0800694
695TEST_F(CrasherTest, PR_SET_DUMPABLE_0_crash) {
Josh Gao502cfd22017-02-17 01:39:15 -0800696 int intercept_result;
697 unique_fd output_fd;
Josh Gaofca7ca32017-01-23 12:05:35 -0800698 StartProcess([]() {
699 prctl(PR_SET_DUMPABLE, 0);
Josh Gao502cfd22017-02-17 01:39:15 -0800700 abort();
Josh Gaofca7ca32017-01-23 12:05:35 -0800701 });
Josh Gao502cfd22017-02-17 01:39:15 -0800702
703 StartIntercept(&output_fd);
704 FinishCrasher();
705 AssertDeath(SIGABRT);
706 FinishIntercept(&intercept_result);
707
708 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
709
710 std::string result;
711 ConsumeFd(std::move(output_fd), &result);
Andreas Gampe26cbafb2017-06-22 20:14:43 -0700712 ASSERT_BACKTRACE_FRAME(result, "abort");
Josh Gaofca7ca32017-01-23 12:05:35 -0800713}
714
Josh Gao502cfd22017-02-17 01:39:15 -0800715TEST_F(CrasherTest, capabilities) {
716 ASSERT_EQ(0U, getuid()) << "capability test requires root";
717
Josh Gaofca7ca32017-01-23 12:05:35 -0800718 StartProcess([]() {
Josh Gao502cfd22017-02-17 01:39:15 -0800719 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) != 0) {
720 err(1, "failed to set PR_SET_KEEPCAPS");
721 }
722
723 if (setresuid(1, 1, 1) != 0) {
724 err(1, "setresuid failed");
725 }
726
727 __user_cap_header_struct capheader;
728 __user_cap_data_struct capdata[2];
729 memset(&capheader, 0, sizeof(capheader));
730 memset(&capdata, 0, sizeof(capdata));
731
732 capheader.version = _LINUX_CAPABILITY_VERSION_3;
733 capheader.pid = 0;
734
735 // Turn on every third capability.
736 static_assert(CAP_LAST_CAP > 33, "CAP_LAST_CAP <= 32");
737 for (int i = 0; i < CAP_LAST_CAP; i += 3) {
738 capdata[CAP_TO_INDEX(i)].permitted |= CAP_TO_MASK(i);
739 capdata[CAP_TO_INDEX(i)].effective |= CAP_TO_MASK(i);
740 }
741
742 // Make sure CAP_SYS_PTRACE is off.
743 capdata[CAP_TO_INDEX(CAP_SYS_PTRACE)].permitted &= ~(CAP_TO_MASK(CAP_SYS_PTRACE));
744 capdata[CAP_TO_INDEX(CAP_SYS_PTRACE)].effective &= ~(CAP_TO_MASK(CAP_SYS_PTRACE));
745
746 if (capset(&capheader, &capdata[0]) != 0) {
747 err(1, "capset failed");
748 }
749
750 if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_CLEAR_ALL, 0, 0, 0) != 0) {
751 err(1, "failed to drop ambient capabilities");
752 }
753
Josh Gaoa5199a92017-04-03 13:18:34 -0700754 pthread_setname_np(pthread_self(), "thread_name");
Josh Gao502cfd22017-02-17 01:39:15 -0800755 raise(SIGSYS);
Josh Gaofca7ca32017-01-23 12:05:35 -0800756 });
Josh Gao502cfd22017-02-17 01:39:15 -0800757
758 unique_fd output_fd;
759 StartIntercept(&output_fd);
760 FinishCrasher();
761 AssertDeath(SIGSYS);
762
763 std::string result;
764 int intercept_result;
765 FinishIntercept(&intercept_result);
766 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
767 ConsumeFd(std::move(output_fd), &result);
Josh Gaoa5199a92017-04-03 13:18:34 -0700768 ASSERT_MATCH(result, R"(name: thread_name\s+>>> .+debuggerd_test(32|64) <<<)");
Jaesung Chung58778e12017-06-15 18:20:34 +0900769 ASSERT_BACKTRACE_FRAME(result, "tgkill");
Josh Gaofca7ca32017-01-23 12:05:35 -0800770}
Josh Gaoc3c8c022017-02-13 16:36:18 -0800771
Josh Gao2e7b8e22017-05-04 17:12:57 -0700772TEST_F(CrasherTest, fake_pid) {
773 int intercept_result;
774 unique_fd output_fd;
775
776 // Prime the getpid/gettid caches.
777 UNUSED(getpid());
778 UNUSED(gettid());
779
780 std::function<pid_t()> clone_fn = []() {
781 return syscall(__NR_clone, SIGCHLD, nullptr, nullptr, nullptr, nullptr);
782 };
783 StartProcess(
784 []() {
785 ASSERT_NE(getpid(), syscall(__NR_getpid));
786 ASSERT_NE(gettid(), syscall(__NR_gettid));
787 raise(SIGSEGV);
788 },
789 clone_fn);
790
791 StartIntercept(&output_fd);
792 FinishCrasher();
793 AssertDeath(SIGSEGV);
794 FinishIntercept(&intercept_result);
795
796 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
797
798 std::string result;
799 ConsumeFd(std::move(output_fd), &result);
Jaesung Chung58778e12017-06-15 18:20:34 +0900800 ASSERT_BACKTRACE_FRAME(result, "tgkill");
Josh Gao2e7b8e22017-05-04 17:12:57 -0700801}
802
Josh Gaoe04ca272018-01-16 15:38:17 -0800803static const char* const kDebuggerdSeccompPolicy =
804 "/system/etc/seccomp_policy/crash_dump." ABI_STRING ".policy";
805
Josh Gao70adac62018-02-22 11:38:33 -0800806static pid_t seccomp_fork_impl(void (*prejail)()) {
Josh Gao6f9eeec2018-09-12 13:55:47 -0700807 std::string policy;
808 if (!android::base::ReadFileToString(kDebuggerdSeccompPolicy, &policy)) {
809 PLOG(FATAL) << "failed to read policy file";
810 }
811
812 // Allow a bunch of syscalls used by the tests.
813 policy += "\nclone: 1";
814 policy += "\nsigaltstack: 1";
815 policy += "\nnanosleep: 1";
Christopher Ferrisab606682019-09-17 15:31:47 -0700816 policy += "\ngetrlimit: 1";
817 policy += "\nugetrlimit: 1";
Josh Gao6f9eeec2018-09-12 13:55:47 -0700818
819 FILE* tmp_file = tmpfile();
820 if (!tmp_file) {
821 PLOG(FATAL) << "tmpfile failed";
822 }
823
Christopher Ferris172b0a02019-09-18 17:48:30 -0700824 unique_fd tmp_fd(TEMP_FAILURE_RETRY(dup(fileno(tmp_file))));
Josh Gao6f9eeec2018-09-12 13:55:47 -0700825 if (!android::base::WriteStringToFd(policy, tmp_fd.get())) {
826 PLOG(FATAL) << "failed to write policy to tmpfile";
827 }
828
829 if (lseek(tmp_fd.get(), 0, SEEK_SET) != 0) {
830 PLOG(FATAL) << "failed to seek tmp_fd";
Josh Gaoe04ca272018-01-16 15:38:17 -0800831 }
832
833 ScopedMinijail jail{minijail_new()};
834 if (!jail) {
835 LOG(FATAL) << "failed to create minijail";
836 }
837
838 minijail_no_new_privs(jail.get());
839 minijail_log_seccomp_filter_failures(jail.get());
840 minijail_use_seccomp_filter(jail.get());
Josh Gao6f9eeec2018-09-12 13:55:47 -0700841 minijail_parse_seccomp_filters_from_fd(jail.get(), tmp_fd.release());
Josh Gaoe04ca272018-01-16 15:38:17 -0800842
843 pid_t result = fork();
844 if (result == -1) {
845 return result;
846 } else if (result != 0) {
847 return result;
848 }
849
850 // Spawn and detach a thread that spins forever.
851 std::atomic<bool> thread_ready(false);
852 std::thread thread([&jail, &thread_ready]() {
853 minijail_enter(jail.get());
854 thread_ready = true;
855 for (;;)
856 ;
857 });
858 thread.detach();
859
860 while (!thread_ready) {
861 continue;
862 }
863
Josh Gao70adac62018-02-22 11:38:33 -0800864 if (prejail) {
865 prejail();
866 }
867
Josh Gaoe04ca272018-01-16 15:38:17 -0800868 minijail_enter(jail.get());
869 return result;
870}
871
Josh Gao70adac62018-02-22 11:38:33 -0800872static pid_t seccomp_fork() {
873 return seccomp_fork_impl(nullptr);
874}
875
Josh Gaoe04ca272018-01-16 15:38:17 -0800876TEST_F(CrasherTest, seccomp_crash) {
877 int intercept_result;
878 unique_fd output_fd;
879
880 StartProcess([]() { abort(); }, &seccomp_fork);
881
882 StartIntercept(&output_fd);
883 FinishCrasher();
884 AssertDeath(SIGABRT);
885 FinishIntercept(&intercept_result);
886 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
887
888 std::string result;
889 ConsumeFd(std::move(output_fd), &result);
890 ASSERT_BACKTRACE_FRAME(result, "abort");
891}
892
Josh Gao70adac62018-02-22 11:38:33 -0800893static pid_t seccomp_fork_rlimit() {
894 return seccomp_fork_impl([]() {
895 struct rlimit rlim = {
896 .rlim_cur = 512 * 1024 * 1024,
897 .rlim_max = 512 * 1024 * 1024,
898 };
899
900 if (setrlimit(RLIMIT_AS, &rlim) != 0) {
901 raise(SIGINT);
902 }
903 });
904}
905
906TEST_F(CrasherTest, seccomp_crash_oom) {
907 int intercept_result;
908 unique_fd output_fd;
909
910 StartProcess(
911 []() {
912 std::vector<void*> vec;
913 for (int i = 0; i < 512; ++i) {
914 char* buf = static_cast<char*>(malloc(1024 * 1024));
915 if (!buf) {
916 abort();
917 }
918 memset(buf, 0xff, 1024 * 1024);
919 vec.push_back(buf);
920 }
921 },
922 &seccomp_fork_rlimit);
923
924 StartIntercept(&output_fd);
925 FinishCrasher();
926 AssertDeath(SIGABRT);
927 FinishIntercept(&intercept_result);
928 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
929
930 // We can't actually generate a backtrace, just make sure that the process terminates.
931}
932
Josh Gaoe04ca272018-01-16 15:38:17 -0800933__attribute__((noinline)) extern "C" bool raise_debugger_signal(DebuggerdDumpType dump_type) {
934 siginfo_t siginfo;
935 siginfo.si_code = SI_QUEUE;
936 siginfo.si_pid = getpid();
937 siginfo.si_uid = getuid();
938
939 if (dump_type != kDebuggerdNativeBacktrace && dump_type != kDebuggerdTombstone) {
940 PLOG(FATAL) << "invalid dump type";
941 }
942
943 siginfo.si_value.sival_int = dump_type == kDebuggerdNativeBacktrace;
944
Josh Gaoa48b41b2019-12-13 14:11:04 -0800945 if (syscall(__NR_rt_tgsigqueueinfo, getpid(), gettid(), BIONIC_SIGNAL_DEBUGGER, &siginfo) != 0) {
Josh Gaoe04ca272018-01-16 15:38:17 -0800946 PLOG(ERROR) << "libdebuggerd_client: failed to send signal to self";
947 return false;
948 }
949
950 return true;
951}
952
953TEST_F(CrasherTest, seccomp_tombstone) {
954 int intercept_result;
955 unique_fd output_fd;
956
957 static const auto dump_type = kDebuggerdTombstone;
958 StartProcess(
959 []() {
960 raise_debugger_signal(dump_type);
961 _exit(0);
962 },
963 &seccomp_fork);
964
965 StartIntercept(&output_fd, dump_type);
966 FinishCrasher();
967 AssertDeath(0);
968 FinishIntercept(&intercept_result);
969 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
970
971 std::string result;
972 ConsumeFd(std::move(output_fd), &result);
973 ASSERT_BACKTRACE_FRAME(result, "raise_debugger_signal");
974}
975
Josh Gao6f9eeec2018-09-12 13:55:47 -0700976extern "C" void foo() {
977 LOG(INFO) << "foo";
978 std::this_thread::sleep_for(1s);
979}
980
981extern "C" void bar() {
982 LOG(INFO) << "bar";
983 std::this_thread::sleep_for(1s);
984}
985
Josh Gaoe04ca272018-01-16 15:38:17 -0800986TEST_F(CrasherTest, seccomp_backtrace) {
987 int intercept_result;
988 unique_fd output_fd;
989
990 static const auto dump_type = kDebuggerdNativeBacktrace;
991 StartProcess(
992 []() {
Josh Gao6f9eeec2018-09-12 13:55:47 -0700993 std::thread a(foo);
994 std::thread b(bar);
995
996 std::this_thread::sleep_for(100ms);
997
Josh Gaoe04ca272018-01-16 15:38:17 -0800998 raise_debugger_signal(dump_type);
999 _exit(0);
1000 },
1001 &seccomp_fork);
1002
1003 StartIntercept(&output_fd, dump_type);
1004 FinishCrasher();
1005 AssertDeath(0);
1006 FinishIntercept(&intercept_result);
1007 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1008
1009 std::string result;
1010 ConsumeFd(std::move(output_fd), &result);
1011 ASSERT_BACKTRACE_FRAME(result, "raise_debugger_signal");
Josh Gao6f9eeec2018-09-12 13:55:47 -07001012 ASSERT_BACKTRACE_FRAME(result, "foo");
1013 ASSERT_BACKTRACE_FRAME(result, "bar");
Josh Gaoe04ca272018-01-16 15:38:17 -08001014}
1015
1016TEST_F(CrasherTest, seccomp_crash_logcat) {
1017 StartProcess([]() { abort(); }, &seccomp_fork);
1018 FinishCrasher();
1019
1020 // Make sure we don't get SIGSYS when trying to dump a crash to logcat.
1021 AssertDeath(SIGABRT);
1022}
1023
Josh Gaofd13bf02017-08-18 15:37:26 -07001024TEST_F(CrasherTest, competing_tracer) {
1025 int intercept_result;
1026 unique_fd output_fd;
1027 StartProcess([]() {
Josh Gao2b2ae0c2017-08-21 14:31:17 -07001028 raise(SIGABRT);
Josh Gaofd13bf02017-08-18 15:37:26 -07001029 });
1030
1031 StartIntercept(&output_fd);
Josh Gaofd13bf02017-08-18 15:37:26 -07001032
1033 ASSERT_EQ(0, ptrace(PTRACE_SEIZE, crasher_pid, 0, 0));
Josh Gao2b2ae0c2017-08-21 14:31:17 -07001034 FinishCrasher();
Josh Gaofd13bf02017-08-18 15:37:26 -07001035
1036 int status;
Christopher Ferris172b0a02019-09-18 17:48:30 -07001037 ASSERT_EQ(crasher_pid, TEMP_FAILURE_RETRY(waitpid(crasher_pid, &status, 0)));
Josh Gaofd13bf02017-08-18 15:37:26 -07001038 ASSERT_TRUE(WIFSTOPPED(status));
1039 ASSERT_EQ(SIGABRT, WSTOPSIG(status));
1040
1041 ASSERT_EQ(0, ptrace(PTRACE_CONT, crasher_pid, 0, SIGABRT));
1042 FinishIntercept(&intercept_result);
1043 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1044
1045 std::string result;
1046 ConsumeFd(std::move(output_fd), &result);
1047 std::string regex = R"(failed to attach to thread \d+, already traced by )";
1048 regex += std::to_string(gettid());
1049 regex += R"( \(.+debuggerd_test)";
1050 ASSERT_MATCH(result, regex.c_str());
1051
Christopher Ferris172b0a02019-09-18 17:48:30 -07001052 ASSERT_EQ(crasher_pid, TEMP_FAILURE_RETRY(waitpid(crasher_pid, &status, 0)));
Josh Gao2b2ae0c2017-08-21 14:31:17 -07001053 ASSERT_TRUE(WIFSTOPPED(status));
1054 ASSERT_EQ(SIGABRT, WSTOPSIG(status));
1055
Josh Gaofd13bf02017-08-18 15:37:26 -07001056 ASSERT_EQ(0, ptrace(PTRACE_DETACH, crasher_pid, 0, SIGABRT));
1057 AssertDeath(SIGABRT);
1058}
1059
Josh Gaobf06a402018-08-27 16:34:01 -07001060TEST_F(CrasherTest, fdsan_warning_abort_message) {
1061 int intercept_result;
1062 unique_fd output_fd;
1063
1064 StartProcess([]() {
1065 android_fdsan_set_error_level(ANDROID_FDSAN_ERROR_LEVEL_WARN_ONCE);
Christopher Ferris172b0a02019-09-18 17:48:30 -07001066 unique_fd fd(TEMP_FAILURE_RETRY(open("/dev/null", O_RDONLY | O_CLOEXEC)));
Josh Gaobf06a402018-08-27 16:34:01 -07001067 if (fd == -1) {
1068 abort();
1069 }
1070 close(fd.get());
1071 _exit(0);
1072 });
1073
1074 StartIntercept(&output_fd);
1075 FinishCrasher();
1076 AssertDeath(0);
1077 FinishIntercept(&intercept_result);
1078 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1079
1080 std::string result;
1081 ConsumeFd(std::move(output_fd), &result);
1082 ASSERT_MATCH(result, "Abort message: 'attempted to close");
1083}
1084
Josh Gaoc3c8c022017-02-13 16:36:18 -08001085TEST(crash_dump, zombie) {
1086 pid_t forkpid = fork();
1087
Josh Gaoc3c8c022017-02-13 16:36:18 -08001088 pid_t rc;
1089 int status;
1090
1091 if (forkpid == 0) {
1092 errno = 0;
1093 rc = waitpid(-1, &status, WNOHANG | __WALL | __WNOTHREAD);
1094 if (rc != -1 || errno != ECHILD) {
1095 errx(2, "first waitpid returned %d (%s), expected failure with ECHILD", rc, strerror(errno));
1096 }
1097
Josh Gaoa48b41b2019-12-13 14:11:04 -08001098 raise(BIONIC_SIGNAL_DEBUGGER);
Josh Gaoc3c8c022017-02-13 16:36:18 -08001099
1100 errno = 0;
Christopher Ferris172b0a02019-09-18 17:48:30 -07001101 rc = TEMP_FAILURE_RETRY(waitpid(-1, &status, __WALL | __WNOTHREAD));
Josh Gaoc3c8c022017-02-13 16:36:18 -08001102 if (rc != -1 || errno != ECHILD) {
1103 errx(2, "second waitpid returned %d (%s), expected failure with ECHILD", rc, strerror(errno));
1104 }
1105 _exit(0);
1106 } else {
Christopher Ferris172b0a02019-09-18 17:48:30 -07001107 rc = TEMP_FAILURE_RETRY(waitpid(forkpid, &status, 0));
Josh Gaoc3c8c022017-02-13 16:36:18 -08001108 ASSERT_EQ(forkpid, rc);
1109 ASSERT_TRUE(WIFEXITED(status));
1110 ASSERT_EQ(0, WEXITSTATUS(status));
1111 }
1112}
Josh Gao352a8452017-03-30 16:46:21 -07001113
1114TEST(tombstoned, no_notify) {
1115 // Do this a few times.
1116 for (int i = 0; i < 3; ++i) {
1117 pid_t pid = 123'456'789 + i;
1118
1119 unique_fd intercept_fd, output_fd;
Narayan Kamathca5e9082017-06-02 15:42:06 +01001120 InterceptStatus status;
1121 tombstoned_intercept(pid, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
1122 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gao352a8452017-03-30 16:46:21 -07001123
1124 {
1125 unique_fd tombstoned_socket, input_fd;
Narayan Kamatha73df602017-05-24 15:07:25 +01001126 ASSERT_TRUE(tombstoned_connect(pid, &tombstoned_socket, &input_fd, kDebuggerdTombstone));
Josh Gao352a8452017-03-30 16:46:21 -07001127 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), &pid, sizeof(pid)));
1128 }
1129
1130 pid_t read_pid;
1131 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), &read_pid, sizeof(read_pid)));
1132 ASSERT_EQ(read_pid, pid);
1133 }
1134}
1135
1136TEST(tombstoned, stress) {
1137 // Spawn threads to simultaneously do a bunch of failing dumps and a bunch of successful dumps.
1138 static constexpr int kDumpCount = 100;
1139
1140 std::atomic<bool> start(false);
1141 std::vector<std::thread> threads;
1142 threads.emplace_back([&start]() {
1143 while (!start) {
1144 continue;
1145 }
1146
1147 // Use a way out of range pid, to avoid stomping on an actual process.
1148 pid_t pid_base = 1'000'000;
1149
1150 for (int dump = 0; dump < kDumpCount; ++dump) {
1151 pid_t pid = pid_base + dump;
1152
1153 unique_fd intercept_fd, output_fd;
Narayan Kamathca5e9082017-06-02 15:42:06 +01001154 InterceptStatus status;
1155 tombstoned_intercept(pid, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
1156 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gao352a8452017-03-30 16:46:21 -07001157
1158 // Pretend to crash, and then immediately close the socket.
1159 unique_fd sockfd(socket_local_client(kTombstonedCrashSocketName,
1160 ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_SEQPACKET));
1161 if (sockfd == -1) {
1162 FAIL() << "failed to connect to tombstoned: " << strerror(errno);
1163 }
1164 TombstonedCrashPacket packet = {};
1165 packet.packet_type = CrashPacketType::kDumpRequest;
1166 packet.packet.dump_request.pid = pid;
1167 if (TEMP_FAILURE_RETRY(write(sockfd, &packet, sizeof(packet))) != sizeof(packet)) {
1168 FAIL() << "failed to write to tombstoned: " << strerror(errno);
1169 }
1170
1171 continue;
1172 }
1173 });
1174
1175 threads.emplace_back([&start]() {
1176 while (!start) {
1177 continue;
1178 }
1179
1180 // Use a way out of range pid, to avoid stomping on an actual process.
1181 pid_t pid_base = 2'000'000;
1182
1183 for (int dump = 0; dump < kDumpCount; ++dump) {
1184 pid_t pid = pid_base + dump;
1185
1186 unique_fd intercept_fd, output_fd;
Narayan Kamathca5e9082017-06-02 15:42:06 +01001187 InterceptStatus status;
1188 tombstoned_intercept(pid, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
1189 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gao352a8452017-03-30 16:46:21 -07001190
1191 {
1192 unique_fd tombstoned_socket, input_fd;
Narayan Kamatha73df602017-05-24 15:07:25 +01001193 ASSERT_TRUE(tombstoned_connect(pid, &tombstoned_socket, &input_fd, kDebuggerdTombstone));
Josh Gao352a8452017-03-30 16:46:21 -07001194 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), &pid, sizeof(pid)));
1195 tombstoned_notify_completion(tombstoned_socket.get());
1196 }
1197
1198 // TODO: Fix the race that requires this sleep.
1199 std::this_thread::sleep_for(50ms);
1200
1201 pid_t read_pid;
1202 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), &read_pid, sizeof(read_pid)));
1203 ASSERT_EQ(read_pid, pid);
1204 }
1205 });
1206
1207 start = true;
1208
1209 for (std::thread& thread : threads) {
1210 thread.join();
1211 }
1212}
Narayan Kamathca5e9082017-06-02 15:42:06 +01001213
1214TEST(tombstoned, java_trace_intercept_smoke) {
1215 // Using a "real" PID is a little dangerous here - if the test fails
1216 // or crashes, we might end up getting a bogus / unreliable stack
1217 // trace.
1218 const pid_t self = getpid();
1219
1220 unique_fd intercept_fd, output_fd;
1221 InterceptStatus status;
1222 tombstoned_intercept(self, &intercept_fd, &output_fd, &status, kDebuggerdJavaBacktrace);
1223 ASSERT_EQ(InterceptStatus::kRegistered, status);
1224
1225 // First connect to tombstoned requesting a native backtrace. This
1226 // should result in a "regular" FD and not the installed intercept.
1227 const char native[] = "native";
1228 unique_fd tombstoned_socket, input_fd;
1229 ASSERT_TRUE(tombstoned_connect(self, &tombstoned_socket, &input_fd, kDebuggerdNativeBacktrace));
1230 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), native, sizeof(native)));
1231 tombstoned_notify_completion(tombstoned_socket.get());
1232
1233 // Then, connect to tombstoned asking for a java backtrace. This *should*
1234 // trigger the intercept.
1235 const char java[] = "java";
1236 ASSERT_TRUE(tombstoned_connect(self, &tombstoned_socket, &input_fd, kDebuggerdJavaBacktrace));
1237 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), java, sizeof(java)));
1238 tombstoned_notify_completion(tombstoned_socket.get());
1239
1240 char outbuf[sizeof(java)];
1241 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), outbuf, sizeof(outbuf)));
1242 ASSERT_STREQ("java", outbuf);
1243}
1244
1245TEST(tombstoned, multiple_intercepts) {
1246 const pid_t fake_pid = 1'234'567;
1247 unique_fd intercept_fd, output_fd;
1248 InterceptStatus status;
1249 tombstoned_intercept(fake_pid, &intercept_fd, &output_fd, &status, kDebuggerdJavaBacktrace);
1250 ASSERT_EQ(InterceptStatus::kRegistered, status);
1251
1252 unique_fd intercept_fd_2, output_fd_2;
1253 tombstoned_intercept(fake_pid, &intercept_fd_2, &output_fd_2, &status, kDebuggerdNativeBacktrace);
1254 ASSERT_EQ(InterceptStatus::kFailedAlreadyRegistered, status);
1255}
1256
1257TEST(tombstoned, intercept_any) {
1258 const pid_t fake_pid = 1'234'567;
1259
1260 unique_fd intercept_fd, output_fd;
1261 InterceptStatus status;
1262 tombstoned_intercept(fake_pid, &intercept_fd, &output_fd, &status, kDebuggerdNativeBacktrace);
1263 ASSERT_EQ(InterceptStatus::kRegistered, status);
1264
1265 const char any[] = "any";
1266 unique_fd tombstoned_socket, input_fd;
1267 ASSERT_TRUE(tombstoned_connect(fake_pid, &tombstoned_socket, &input_fd, kDebuggerdAnyIntercept));
1268 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), any, sizeof(any)));
1269 tombstoned_notify_completion(tombstoned_socket.get());
1270
1271 char outbuf[sizeof(any)];
1272 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), outbuf, sizeof(outbuf)));
1273 ASSERT_STREQ("any", outbuf);
1274}
Josh Gao2b22ae12018-09-12 14:51:03 -07001275
1276TEST(tombstoned, interceptless_backtrace) {
1277 // Generate 50 backtraces, and then check to see that we haven't created 50 new tombstones.
1278 auto get_tombstone_timestamps = []() -> std::map<int, time_t> {
1279 std::map<int, time_t> result;
1280 for (int i = 0; i < 99; ++i) {
1281 std::string path = android::base::StringPrintf("/data/tombstones/tombstone_%02d", i);
1282 struct stat st;
1283 if (stat(path.c_str(), &st) == 0) {
1284 result[i] = st.st_mtim.tv_sec;
1285 }
1286 }
1287 return result;
1288 };
1289
1290 auto before = get_tombstone_timestamps();
1291 for (int i = 0; i < 50; ++i) {
1292 raise_debugger_signal(kDebuggerdNativeBacktrace);
1293 }
1294 auto after = get_tombstone_timestamps();
1295
1296 int diff = 0;
1297 for (int i = 0; i < 99; ++i) {
1298 if (after.count(i) == 0) {
1299 continue;
1300 }
1301 if (before.count(i) == 0) {
1302 ++diff;
1303 continue;
1304 }
1305 if (before[i] != after[i]) {
1306 ++diff;
1307 }
1308 }
1309
1310 // We can't be sure that nothing's crash looping in the background.
1311 // This should be good enough, though...
1312 ASSERT_LT(diff, 10) << "too many new tombstones; is something crashing in the background?";
1313}
Christopher Ferris481e8372019-07-15 17:13:24 -07001314
1315static __attribute__((__noinline__)) void overflow_stack(void* p) {
1316 void* buf[1];
1317 buf[0] = p;
1318 static volatile void* global = buf;
1319 if (global) {
1320 global = buf;
1321 overflow_stack(&buf);
1322 }
1323}
1324
1325TEST_F(CrasherTest, stack_overflow) {
1326 int intercept_result;
1327 unique_fd output_fd;
1328 StartProcess([]() { overflow_stack(nullptr); });
1329
1330 StartIntercept(&output_fd);
1331 FinishCrasher();
1332 AssertDeath(SIGSEGV);
1333 FinishIntercept(&intercept_result);
1334
1335 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1336
1337 std::string result;
1338 ConsumeFd(std::move(output_fd), &result);
1339 ASSERT_MATCH(result, R"(Cause: stack pointer[^\n]*stack overflow.\n)");
1340}