blob: 7938a61a671c0a5d1144ccaff03689fe554778f6 [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>
Peter Collingbournefe8997a2020-07-20 15:08:52 -070021#include <sys/mman.h>
Josh Gaofca7ca32017-01-23 12:05:35 -080022#include <sys/prctl.h>
Josh Gaofd13bf02017-08-18 15:37:26 -070023#include <sys/ptrace.h>
Josh Gao70adac62018-02-22 11:38:33 -080024#include <sys/resource.h>
Dan Albertc38057a2017-10-11 11:35:40 -070025#include <sys/syscall.h>
Josh Gaocbe70cb2016-10-18 18:17:52 -070026#include <sys/types.h>
Josh Gaofd13bf02017-08-18 15:37:26 -070027#include <unistd.h>
Josh Gaocbe70cb2016-10-18 18:17:52 -070028
29#include <chrono>
30#include <regex>
31#include <thread>
32
Josh Gaobf06a402018-08-27 16:34:01 -070033#include <android/fdsan.h>
Josh Gao502cfd22017-02-17 01:39:15 -080034#include <android/set_abort_message.h>
Peter Collingbournef8622522020-04-07 14:07:32 -070035#include <bionic/malloc.h>
36#include <bionic/mte.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);
Peter Collingbourne10e428d2020-07-17 14:49:31 -0700175
176 static void Trap(void* ptr);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700177};
178
179CrasherTest::CrasherTest() {
180 previous_wait_for_gdb = android::base::GetBoolProperty(kWaitForGdbKey, false);
181 android::base::SetProperty(kWaitForGdbKey, "0");
182}
183
184CrasherTest::~CrasherTest() {
185 if (crasher_pid != -1) {
186 kill(crasher_pid, SIGKILL);
187 int status;
Christopher Ferris172b0a02019-09-18 17:48:30 -0700188 TEMP_FAILURE_RETRY(waitpid(crasher_pid, &status, WUNTRACED));
Josh Gaocbe70cb2016-10-18 18:17:52 -0700189 }
190
191 android::base::SetProperty(kWaitForGdbKey, previous_wait_for_gdb ? "1" : "0");
192}
193
Narayan Kamatha73df602017-05-24 15:07:25 +0100194void CrasherTest::StartIntercept(unique_fd* output_fd, DebuggerdDumpType intercept_type) {
Josh Gaocbe70cb2016-10-18 18:17:52 -0700195 if (crasher_pid == -1) {
196 FAIL() << "crasher hasn't been started";
197 }
198
Narayan Kamathca5e9082017-06-02 15:42:06 +0100199 InterceptStatus status;
200 tombstoned_intercept(crasher_pid, &this->intercept_fd, output_fd, &status, intercept_type);
201 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700202}
203
204void CrasherTest::FinishIntercept(int* result) {
205 InterceptResponse response;
206
Christopher Ferris11555f02019-09-20 14:18:55 -0700207 ssize_t rc = TIMEOUT(30, read(intercept_fd.get(), &response, sizeof(response)));
Josh Gaocbe70cb2016-10-18 18:17:52 -0700208 if (rc == -1) {
209 FAIL() << "failed to read response from tombstoned: " << strerror(errno);
210 } else if (rc == 0) {
211 *result = -1;
212 } else if (rc != sizeof(response)) {
213 FAIL() << "received packet of unexpected length from tombstoned: expected " << sizeof(response)
214 << ", received " << rc;
215 } else {
Josh Gao460b3362017-03-30 16:40:47 -0700216 *result = response.status == InterceptStatus::kStarted ? 1 : 0;
Josh Gaocbe70cb2016-10-18 18:17:52 -0700217 }
218}
219
Josh Gao2e7b8e22017-05-04 17:12:57 -0700220void CrasherTest::StartProcess(std::function<void()> function, std::function<pid_t()> forker) {
Josh Gaofca7ca32017-01-23 12:05:35 -0800221 unique_fd read_pipe;
Josh Gaocbe70cb2016-10-18 18:17:52 -0700222 unique_fd crasher_read_pipe;
223 if (!Pipe(&crasher_read_pipe, &crasher_pipe)) {
224 FAIL() << "failed to create pipe: " << strerror(errno);
225 }
226
Josh Gao2e7b8e22017-05-04 17:12:57 -0700227 crasher_pid = forker();
Josh Gaocbe70cb2016-10-18 18:17:52 -0700228 if (crasher_pid == -1) {
229 FAIL() << "fork failed: " << strerror(errno);
230 } else if (crasher_pid == 0) {
Josh Gao502cfd22017-02-17 01:39:15 -0800231 char dummy;
232 crasher_pipe.reset();
233 TEMP_FAILURE_RETRY(read(crasher_read_pipe.get(), &dummy, 1));
Josh Gaofca7ca32017-01-23 12:05:35 -0800234 function();
235 _exit(0);
236 }
237}
238
Josh Gaocbe70cb2016-10-18 18:17:52 -0700239void CrasherTest::FinishCrasher() {
240 if (crasher_pipe == -1) {
241 FAIL() << "crasher pipe uninitialized";
242 }
243
Christopher Ferris172b0a02019-09-18 17:48:30 -0700244 ssize_t rc = TEMP_FAILURE_RETRY(write(crasher_pipe.get(), "\n", 1));
Josh Gaocbe70cb2016-10-18 18:17:52 -0700245 if (rc == -1) {
246 FAIL() << "failed to write to crasher pipe: " << strerror(errno);
247 } else if (rc == 0) {
248 FAIL() << "crasher pipe was closed";
249 }
250}
251
252void CrasherTest::AssertDeath(int signo) {
253 int status;
Christopher Ferris11555f02019-09-20 14:18:55 -0700254 pid_t pid = TIMEOUT(30, waitpid(crasher_pid, &status, 0));
Josh Gaocbe70cb2016-10-18 18:17:52 -0700255 if (pid != crasher_pid) {
Christopher Ferrisafc0ff72019-06-26 15:08:51 -0700256 printf("failed to wait for crasher (expected pid %d, return value %d): %s\n", crasher_pid, pid,
257 strerror(errno));
Josh Gao2b2ae0c2017-08-21 14:31:17 -0700258 sleep(100);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700259 FAIL() << "failed to wait for crasher: " << strerror(errno);
260 }
261
Josh Gaoe06f2a42017-04-27 16:50:38 -0700262 if (signo == 0) {
263 ASSERT_TRUE(WIFEXITED(status));
264 ASSERT_EQ(0, WEXITSTATUS(signo));
265 } else {
266 ASSERT_FALSE(WIFEXITED(status));
267 ASSERT_TRUE(WIFSIGNALED(status)) << "crasher didn't terminate via a signal";
268 ASSERT_EQ(signo, WTERMSIG(status));
Josh Gaocbe70cb2016-10-18 18:17:52 -0700269 }
Josh Gaocbe70cb2016-10-18 18:17:52 -0700270 crasher_pid = -1;
271}
272
273static void ConsumeFd(unique_fd fd, std::string* output) {
274 constexpr size_t read_length = PAGE_SIZE;
275 std::string result;
276
277 while (true) {
278 size_t offset = result.size();
279 result.resize(result.size() + PAGE_SIZE);
280 ssize_t rc = TEMP_FAILURE_RETRY(read(fd.get(), &result[offset], read_length));
281 if (rc == -1) {
282 FAIL() << "read failed: " << strerror(errno);
283 } else if (rc == 0) {
284 result.resize(result.size() - PAGE_SIZE);
285 break;
286 }
287
288 result.resize(result.size() - PAGE_SIZE + rc);
289 }
290
291 *output = std::move(result);
292}
293
294TEST_F(CrasherTest, smoke) {
295 int intercept_result;
296 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800297 StartProcess([]() {
298 *reinterpret_cast<volatile char*>(0xdead) = '1';
299 });
300
Josh Gaocbe70cb2016-10-18 18:17:52 -0700301 StartIntercept(&output_fd);
302 FinishCrasher();
303 AssertDeath(SIGSEGV);
304 FinishIntercept(&intercept_result);
305
306 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
307
308 std::string result;
309 ConsumeFd(std::move(output_fd), &result);
310 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\), code 1 \(SEGV_MAPERR\), fault addr 0xdead)");
Peter Collingbourne864f15d2020-09-14 20:27:36 -0700311
312 if (mte_supported()) {
313 // Test that the default TAGGED_ADDR_CTRL value is set.
Peter Collingbourne2b6764a2020-11-02 15:59:52 -0800314 ASSERT_MATCH(result, R"(tagged_addr_ctrl: 000000000007fff5)");
Peter Collingbourne864f15d2020-09-14 20:27:36 -0700315 }
Josh Gaocbe70cb2016-10-18 18:17:52 -0700316}
317
Peter Collingbournef03af882020-03-20 18:09:00 -0700318TEST_F(CrasherTest, tagged_fault_addr) {
319#if !defined(__aarch64__)
320 GTEST_SKIP() << "Requires aarch64";
321#endif
322 int intercept_result;
323 unique_fd output_fd;
324 StartProcess([]() {
325 *reinterpret_cast<volatile char*>(0x100000000000dead) = '1';
326 });
327
328 StartIntercept(&output_fd);
329 FinishCrasher();
330 AssertDeath(SIGSEGV);
331 FinishIntercept(&intercept_result);
332
333 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
334
335 std::string result;
336 ConsumeFd(std::move(output_fd), &result);
337
338 // The address can either be tagged (new kernels) or untagged (old kernels).
339 ASSERT_MATCH(
340 result,
341 R"(signal 11 \(SIGSEGV\), code 1 \(SEGV_MAPERR\), fault addr (0x100000000000dead|0xdead))");
342}
343
Peter Collingbourne10e428d2020-07-17 14:49:31 -0700344// Marked as weak to prevent the compiler from removing the malloc in the caller. In theory, the
345// compiler could still clobber the argument register before trapping, but that's unlikely.
346__attribute__((weak)) void CrasherTest::Trap(void* ptr ATTRIBUTE_UNUSED) {
347 __builtin_trap();
348}
349
350TEST_F(CrasherTest, heap_addr_in_register) {
351#if defined(__i386__)
352 GTEST_SKIP() << "architecture does not pass arguments in registers";
353#endif
354 int intercept_result;
355 unique_fd output_fd;
356 StartProcess([]() {
357 // Crash with a heap pointer in the first argument register.
358 Trap(malloc(1));
359 });
360
361 StartIntercept(&output_fd);
362 FinishCrasher();
363 int status;
364 ASSERT_EQ(crasher_pid, TIMEOUT(30, waitpid(crasher_pid, &status, 0)));
365 ASSERT_TRUE(WIFSIGNALED(status)) << "crasher didn't terminate via a signal";
366 // Don't test the signal number because different architectures use different signals for
367 // __builtin_trap().
368 FinishIntercept(&intercept_result);
369
370 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
371
372 std::string result;
373 ConsumeFd(std::move(output_fd), &result);
374
375#if defined(__aarch64__)
376 ASSERT_MATCH(result, "memory near x0");
377#elif defined(__arm__)
378 ASSERT_MATCH(result, "memory near r0");
379#elif defined(__x86_64__)
380 ASSERT_MATCH(result, "memory near rdi");
381#else
382 ASSERT_TRUE(false) << "unsupported architecture";
383#endif
384}
385
Peter Collingbournecd278072020-12-21 14:08:38 -0800386#if defined(__aarch64__)
Peter Collingbournef8622522020-04-07 14:07:32 -0700387static void SetTagCheckingLevelSync() {
Peter Collingbournef8622522020-04-07 14:07:32 -0700388 HeapTaggingLevel heap_tagging_level = M_HEAP_TAGGING_LEVEL_SYNC;
389 if (!android_mallopt(M_SET_HEAP_TAGGING_LEVEL, &heap_tagging_level, sizeof(heap_tagging_level))) {
390 abort();
391 }
392}
393#endif
394
395TEST_F(CrasherTest, mte_uaf) {
Peter Collingbournecd278072020-12-21 14:08:38 -0800396#if defined(__aarch64__)
Peter Collingbournef8622522020-04-07 14:07:32 -0700397 if (!mte_supported()) {
398 GTEST_SKIP() << "Requires MTE";
399 }
400
401 int intercept_result;
402 unique_fd output_fd;
403 StartProcess([]() {
404 SetTagCheckingLevelSync();
405 volatile int* p = (volatile int*)malloc(16);
406 free((void *)p);
407 p[0] = 42;
408 });
409
410 StartIntercept(&output_fd);
411 FinishCrasher();
412 AssertDeath(SIGSEGV);
413 FinishIntercept(&intercept_result);
414
415 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
416
417 std::string result;
418 ConsumeFd(std::move(output_fd), &result);
419
420 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\), code 9 \(SEGV_MTESERR\))");
Peter Collingbournebbe69052020-05-08 10:11:19 -0700421 ASSERT_MATCH(result, R"(Cause: \[MTE\]: Use After Free, 0 bytes into a 16-byte allocation.*
422
423allocated by thread .*
424 #00 pc)");
425 ASSERT_MATCH(result, R"(deallocated by thread .*
426 #00 pc)");
Peter Collingbournef8622522020-04-07 14:07:32 -0700427#else
Peter Collingbournecd278072020-12-21 14:08:38 -0800428 GTEST_SKIP() << "Requires aarch64";
Peter Collingbournef8622522020-04-07 14:07:32 -0700429#endif
430}
431
432TEST_F(CrasherTest, mte_overflow) {
Peter Collingbournecd278072020-12-21 14:08:38 -0800433#if defined(__aarch64__)
Peter Collingbournef8622522020-04-07 14:07:32 -0700434 if (!mte_supported()) {
435 GTEST_SKIP() << "Requires MTE";
436 }
437
438 int intercept_result;
439 unique_fd output_fd;
440 StartProcess([]() {
441 SetTagCheckingLevelSync();
442 volatile int* p = (volatile int*)malloc(16);
443 p[4] = 42;
444 });
445
446 StartIntercept(&output_fd);
447 FinishCrasher();
448 AssertDeath(SIGSEGV);
449 FinishIntercept(&intercept_result);
450
451 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
452
453 std::string result;
454 ConsumeFd(std::move(output_fd), &result);
455
456 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\))");
Peter Collingbournebbe69052020-05-08 10:11:19 -0700457 ASSERT_MATCH(result, R"(Cause: \[MTE\]: Buffer Overflow, 0 bytes right of a 16-byte allocation.*
458
459allocated by thread .*
460 #00 pc)");
Peter Collingbournef8622522020-04-07 14:07:32 -0700461#else
Peter Collingbournecd278072020-12-21 14:08:38 -0800462 GTEST_SKIP() << "Requires aarch64";
Peter Collingbournef8622522020-04-07 14:07:32 -0700463#endif
464}
465
466TEST_F(CrasherTest, mte_underflow) {
Peter Collingbournecd278072020-12-21 14:08:38 -0800467#if defined(__aarch64__)
Peter Collingbournef8622522020-04-07 14:07:32 -0700468 if (!mte_supported()) {
469 GTEST_SKIP() << "Requires MTE";
470 }
471
472 int intercept_result;
473 unique_fd output_fd;
474 StartProcess([]() {
475 SetTagCheckingLevelSync();
476 volatile int* p = (volatile int*)malloc(16);
477 p[-1] = 42;
478 });
479
480 StartIntercept(&output_fd);
481 FinishCrasher();
482 AssertDeath(SIGSEGV);
483 FinishIntercept(&intercept_result);
484
485 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
486
487 std::string result;
488 ConsumeFd(std::move(output_fd), &result);
489
490 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\), code 9 \(SEGV_MTESERR\))");
Peter Collingbournebbe69052020-05-08 10:11:19 -0700491 ASSERT_MATCH(result, R"(Cause: \[MTE\]: Buffer Underflow, 4 bytes left of a 16-byte allocation.*
492
493allocated by thread .*
494 #00 pc)");
Peter Collingbournef8622522020-04-07 14:07:32 -0700495#else
Peter Collingbournecd278072020-12-21 14:08:38 -0800496 GTEST_SKIP() << "Requires aarch64";
Peter Collingbournef8622522020-04-07 14:07:32 -0700497#endif
498}
499
500TEST_F(CrasherTest, mte_multiple_causes) {
Peter Collingbournecd278072020-12-21 14:08:38 -0800501#if defined(__aarch64__)
Peter Collingbournef8622522020-04-07 14:07:32 -0700502 if (!mte_supported()) {
503 GTEST_SKIP() << "Requires MTE";
504 }
505
506 int intercept_result;
507 unique_fd output_fd;
508 StartProcess([]() {
509 SetTagCheckingLevelSync();
510
511 // Make two allocations with the same tag and close to one another. Check for both properties
512 // with a bounds check -- this relies on the fact that only if the allocations have the same tag
513 // would they be measured as closer than 128 bytes to each other. Otherwise they would be about
514 // (some non-zero value << 56) apart.
515 //
516 // The out-of-bounds access will be considered either an overflow of one or an underflow of the
517 // other.
518 std::set<uintptr_t> allocs;
519 for (int i = 0; i != 4096; ++i) {
520 uintptr_t alloc = reinterpret_cast<uintptr_t>(malloc(16));
521 auto it = allocs.insert(alloc).first;
522 if (it != allocs.begin() && *std::prev(it) + 128 > alloc) {
523 *reinterpret_cast<int*>(*std::prev(it) + 16) = 42;
524 }
525 if (std::next(it) != allocs.end() && alloc + 128 > *std::next(it)) {
526 *reinterpret_cast<int*>(alloc + 16) = 42;
527 }
528 }
529 });
530
531 StartIntercept(&output_fd);
532 FinishCrasher();
533 AssertDeath(SIGSEGV);
534 FinishIntercept(&intercept_result);
535
536 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
537
538 std::string result;
539 ConsumeFd(std::move(output_fd), &result);
540
541 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\))");
542 ASSERT_MATCH(
543 result,
544 R"(Note: multiple potential causes for this crash were detected, listing them in decreasing order of probability.)");
545
546 // Adjacent untracked allocations may cause us to see the wrong underflow here (or only
547 // overflows), so we can't match explicitly for an underflow message.
548 ASSERT_MATCH(result, R"(Cause: \[MTE\]: Buffer Overflow, 0 bytes right of a 16-byte allocation)");
549#else
Peter Collingbournecd278072020-12-21 14:08:38 -0800550 GTEST_SKIP() << "Requires aarch64";
Peter Collingbournef8622522020-04-07 14:07:32 -0700551#endif
552}
553
Peter Collingbournecd278072020-12-21 14:08:38 -0800554#if defined(__aarch64__)
Peter Collingbournefe8997a2020-07-20 15:08:52 -0700555static uintptr_t CreateTagMapping() {
556 uintptr_t mapping =
557 reinterpret_cast<uintptr_t>(mmap(nullptr, getpagesize(), PROT_READ | PROT_WRITE | PROT_MTE,
558 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0));
559 if (reinterpret_cast<void*>(mapping) == MAP_FAILED) {
560 return 0;
561 }
562 __asm__ __volatile__(".arch_extension mte; stg %0, [%0]"
563 :
564 : "r"(mapping + (1ULL << 56))
565 : "memory");
566 return mapping;
567}
568#endif
569
570TEST_F(CrasherTest, mte_tag_dump) {
Peter Collingbournecd278072020-12-21 14:08:38 -0800571#if defined(__aarch64__)
Peter Collingbournefe8997a2020-07-20 15:08:52 -0700572 if (!mte_supported()) {
573 GTEST_SKIP() << "Requires MTE";
574 }
575
576 int intercept_result;
577 unique_fd output_fd;
578 StartProcess([&]() {
579 SetTagCheckingLevelSync();
580 Trap(reinterpret_cast<void *>(CreateTagMapping()));
581 });
582
583 StartIntercept(&output_fd);
584 FinishCrasher();
585 AssertDeath(SIGTRAP);
586 FinishIntercept(&intercept_result);
587
588 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
589
590 std::string result;
591 ConsumeFd(std::move(output_fd), &result);
592
593 ASSERT_MATCH(result, R"(memory near x0:
594.*
595.*
596 01.............0 0000000000000000 0000000000000000 ................
597 00.............0)");
598#else
Peter Collingbournecd278072020-12-21 14:08:38 -0800599 GTEST_SKIP() << "Requires aarch64";
Peter Collingbournefe8997a2020-07-20 15:08:52 -0700600#endif
601}
602
Josh Gaocdea7502017-11-01 15:00:40 -0700603TEST_F(CrasherTest, LD_PRELOAD) {
604 int intercept_result;
605 unique_fd output_fd;
606 StartProcess([]() {
607 setenv("LD_PRELOAD", "nonexistent.so", 1);
608 *reinterpret_cast<volatile char*>(0xdead) = '1';
609 });
610
611 StartIntercept(&output_fd);
612 FinishCrasher();
613 AssertDeath(SIGSEGV);
614 FinishIntercept(&intercept_result);
615
616 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
617
618 std::string result;
619 ConsumeFd(std::move(output_fd), &result);
620 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\), code 1 \(SEGV_MAPERR\), fault addr 0xdead)");
621}
622
Josh Gaocbe70cb2016-10-18 18:17:52 -0700623TEST_F(CrasherTest, abort) {
624 int intercept_result;
625 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800626 StartProcess([]() {
627 abort();
628 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700629 StartIntercept(&output_fd);
630 FinishCrasher();
631 AssertDeath(SIGABRT);
632 FinishIntercept(&intercept_result);
633
634 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
635
636 std::string result;
637 ConsumeFd(std::move(output_fd), &result);
Andreas Gampe26cbafb2017-06-22 20:14:43 -0700638 ASSERT_BACKTRACE_FRAME(result, "abort");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700639}
640
641TEST_F(CrasherTest, signal) {
642 int intercept_result;
643 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800644 StartProcess([]() {
Josh Gao2b2ae0c2017-08-21 14:31:17 -0700645 while (true) {
646 sleep(1);
647 }
Josh Gao502cfd22017-02-17 01:39:15 -0800648 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700649 StartIntercept(&output_fd);
Josh Gao2b2ae0c2017-08-21 14:31:17 -0700650 FinishCrasher();
Josh Gaocbe70cb2016-10-18 18:17:52 -0700651 ASSERT_EQ(0, kill(crasher_pid, SIGSEGV));
652
653 AssertDeath(SIGSEGV);
654 FinishIntercept(&intercept_result);
655
656 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
657
658 std::string result;
659 ConsumeFd(std::move(output_fd), &result);
Elliott Hughes89722702018-05-02 10:47:00 -0700660 ASSERT_MATCH(
661 result,
662 R"(signal 11 \(SIGSEGV\), code 0 \(SI_USER from pid \d+, uid \d+\), fault addr --------)");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700663 ASSERT_MATCH(result, R"(backtrace:)");
664}
665
666TEST_F(CrasherTest, abort_message) {
667 int intercept_result;
668 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800669 StartProcess([]() {
Josh Gao1cc7bd82018-02-13 13:16:17 -0800670 // Arrived at experimentally;
671 // logd truncates at 4062.
672 // strlen("Abort message: ''") is 17.
673 // That's 4045, but we also want a NUL.
674 char buf[4045 + 1];
675 memset(buf, 'x', sizeof(buf));
676 buf[sizeof(buf) - 1] = '\0';
677 android_set_abort_message(buf);
Josh Gao502cfd22017-02-17 01:39:15 -0800678 abort();
679 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700680 StartIntercept(&output_fd);
681 FinishCrasher();
682 AssertDeath(SIGABRT);
683 FinishIntercept(&intercept_result);
684
685 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
686
687 std::string result;
688 ConsumeFd(std::move(output_fd), &result);
Josh Gao1cc7bd82018-02-13 13:16:17 -0800689 ASSERT_MATCH(result, R"(Abort message: 'x{4045}')");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700690}
691
Josh Gaoe06f2a42017-04-27 16:50:38 -0700692TEST_F(CrasherTest, abort_message_backtrace) {
693 int intercept_result;
694 unique_fd output_fd;
695 StartProcess([]() {
696 android_set_abort_message("not actually aborting");
Josh Gaoa48b41b2019-12-13 14:11:04 -0800697 raise(BIONIC_SIGNAL_DEBUGGER);
Josh Gaoe06f2a42017-04-27 16:50:38 -0700698 exit(0);
699 });
700 StartIntercept(&output_fd);
701 FinishCrasher();
702 AssertDeath(0);
703 FinishIntercept(&intercept_result);
704
705 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
706
707 std::string result;
708 ConsumeFd(std::move(output_fd), &result);
709 ASSERT_NOT_MATCH(result, R"(Abort message:)");
710}
711
Josh Gaocbe70cb2016-10-18 18:17:52 -0700712TEST_F(CrasherTest, intercept_timeout) {
713 int intercept_result;
714 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800715 StartProcess([]() {
716 abort();
717 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700718 StartIntercept(&output_fd);
719
720 // Don't let crasher finish until we timeout.
721 FinishIntercept(&intercept_result);
722
723 ASSERT_NE(1, intercept_result) << "tombstoned reported success? (intercept_result = "
724 << intercept_result << ")";
725
726 FinishCrasher();
727 AssertDeath(SIGABRT);
728}
729
730TEST_F(CrasherTest, wait_for_gdb) {
731 if (!android::base::SetProperty(kWaitForGdbKey, "1")) {
732 FAIL() << "failed to enable wait_for_gdb";
733 }
734 sleep(1);
735
Josh Gao502cfd22017-02-17 01:39:15 -0800736 StartProcess([]() {
737 abort();
738 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700739 FinishCrasher();
740
741 int status;
Christopher Ferris172b0a02019-09-18 17:48:30 -0700742 ASSERT_EQ(crasher_pid, TEMP_FAILURE_RETRY(waitpid(crasher_pid, &status, WUNTRACED)));
Josh Gaocbe70cb2016-10-18 18:17:52 -0700743 ASSERT_TRUE(WIFSTOPPED(status));
744 ASSERT_EQ(SIGSTOP, WSTOPSIG(status));
745
746 ASSERT_EQ(0, kill(crasher_pid, SIGCONT));
747
748 AssertDeath(SIGABRT);
749}
750
Josh Gaocbe70cb2016-10-18 18:17:52 -0700751TEST_F(CrasherTest, backtrace) {
752 std::string result;
753 int intercept_result;
754 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800755
756 StartProcess([]() {
757 abort();
758 });
Narayan Kamatha73df602017-05-24 15:07:25 +0100759 StartIntercept(&output_fd, kDebuggerdNativeBacktrace);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700760
761 std::this_thread::sleep_for(500ms);
762
763 sigval val;
764 val.sival_int = 1;
Josh Gaoa48b41b2019-12-13 14:11:04 -0800765 ASSERT_EQ(0, sigqueue(crasher_pid, BIONIC_SIGNAL_DEBUGGER, val)) << strerror(errno);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700766 FinishIntercept(&intercept_result);
767 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
768 ConsumeFd(std::move(output_fd), &result);
Jaesung Chung58778e12017-06-15 18:20:34 +0900769 ASSERT_BACKTRACE_FRAME(result, "read");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700770
771 int status;
772 ASSERT_EQ(0, waitpid(crasher_pid, &status, WNOHANG | WUNTRACED));
773
774 StartIntercept(&output_fd);
775 FinishCrasher();
776 AssertDeath(SIGABRT);
777 FinishIntercept(&intercept_result);
778 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
779 ConsumeFd(std::move(output_fd), &result);
Andreas Gampe26cbafb2017-06-22 20:14:43 -0700780 ASSERT_BACKTRACE_FRAME(result, "abort");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700781}
Josh Gaofca7ca32017-01-23 12:05:35 -0800782
783TEST_F(CrasherTest, PR_SET_DUMPABLE_0_crash) {
Josh Gao502cfd22017-02-17 01:39:15 -0800784 int intercept_result;
785 unique_fd output_fd;
Josh Gaofca7ca32017-01-23 12:05:35 -0800786 StartProcess([]() {
787 prctl(PR_SET_DUMPABLE, 0);
Josh Gao502cfd22017-02-17 01:39:15 -0800788 abort();
Josh Gaofca7ca32017-01-23 12:05:35 -0800789 });
Josh Gao502cfd22017-02-17 01:39:15 -0800790
791 StartIntercept(&output_fd);
792 FinishCrasher();
793 AssertDeath(SIGABRT);
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);
Andreas Gampe26cbafb2017-06-22 20:14:43 -0700800 ASSERT_BACKTRACE_FRAME(result, "abort");
Josh Gaofca7ca32017-01-23 12:05:35 -0800801}
802
Josh Gao502cfd22017-02-17 01:39:15 -0800803TEST_F(CrasherTest, capabilities) {
804 ASSERT_EQ(0U, getuid()) << "capability test requires root";
805
Josh Gaofca7ca32017-01-23 12:05:35 -0800806 StartProcess([]() {
Josh Gao502cfd22017-02-17 01:39:15 -0800807 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) != 0) {
808 err(1, "failed to set PR_SET_KEEPCAPS");
809 }
810
811 if (setresuid(1, 1, 1) != 0) {
812 err(1, "setresuid failed");
813 }
814
815 __user_cap_header_struct capheader;
816 __user_cap_data_struct capdata[2];
817 memset(&capheader, 0, sizeof(capheader));
818 memset(&capdata, 0, sizeof(capdata));
819
820 capheader.version = _LINUX_CAPABILITY_VERSION_3;
821 capheader.pid = 0;
822
823 // Turn on every third capability.
824 static_assert(CAP_LAST_CAP > 33, "CAP_LAST_CAP <= 32");
825 for (int i = 0; i < CAP_LAST_CAP; i += 3) {
826 capdata[CAP_TO_INDEX(i)].permitted |= CAP_TO_MASK(i);
827 capdata[CAP_TO_INDEX(i)].effective |= CAP_TO_MASK(i);
828 }
829
830 // Make sure CAP_SYS_PTRACE is off.
831 capdata[CAP_TO_INDEX(CAP_SYS_PTRACE)].permitted &= ~(CAP_TO_MASK(CAP_SYS_PTRACE));
832 capdata[CAP_TO_INDEX(CAP_SYS_PTRACE)].effective &= ~(CAP_TO_MASK(CAP_SYS_PTRACE));
833
834 if (capset(&capheader, &capdata[0]) != 0) {
835 err(1, "capset failed");
836 }
837
838 if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_CLEAR_ALL, 0, 0, 0) != 0) {
839 err(1, "failed to drop ambient capabilities");
840 }
841
Josh Gaoa5199a92017-04-03 13:18:34 -0700842 pthread_setname_np(pthread_self(), "thread_name");
Josh Gao502cfd22017-02-17 01:39:15 -0800843 raise(SIGSYS);
Josh Gaofca7ca32017-01-23 12:05:35 -0800844 });
Josh Gao502cfd22017-02-17 01:39:15 -0800845
846 unique_fd output_fd;
847 StartIntercept(&output_fd);
848 FinishCrasher();
849 AssertDeath(SIGSYS);
850
851 std::string result;
852 int intercept_result;
853 FinishIntercept(&intercept_result);
854 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
855 ConsumeFd(std::move(output_fd), &result);
Josh Gaoa5199a92017-04-03 13:18:34 -0700856 ASSERT_MATCH(result, R"(name: thread_name\s+>>> .+debuggerd_test(32|64) <<<)");
Jaesung Chung58778e12017-06-15 18:20:34 +0900857 ASSERT_BACKTRACE_FRAME(result, "tgkill");
Josh Gaofca7ca32017-01-23 12:05:35 -0800858}
Josh Gaoc3c8c022017-02-13 16:36:18 -0800859
Josh Gao2e7b8e22017-05-04 17:12:57 -0700860TEST_F(CrasherTest, fake_pid) {
861 int intercept_result;
862 unique_fd output_fd;
863
864 // Prime the getpid/gettid caches.
865 UNUSED(getpid());
866 UNUSED(gettid());
867
868 std::function<pid_t()> clone_fn = []() {
869 return syscall(__NR_clone, SIGCHLD, nullptr, nullptr, nullptr, nullptr);
870 };
871 StartProcess(
872 []() {
873 ASSERT_NE(getpid(), syscall(__NR_getpid));
874 ASSERT_NE(gettid(), syscall(__NR_gettid));
875 raise(SIGSEGV);
876 },
877 clone_fn);
878
879 StartIntercept(&output_fd);
880 FinishCrasher();
881 AssertDeath(SIGSEGV);
882 FinishIntercept(&intercept_result);
883
884 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
885
886 std::string result;
887 ConsumeFd(std::move(output_fd), &result);
Jaesung Chung58778e12017-06-15 18:20:34 +0900888 ASSERT_BACKTRACE_FRAME(result, "tgkill");
Josh Gao2e7b8e22017-05-04 17:12:57 -0700889}
890
Josh Gaoe04ca272018-01-16 15:38:17 -0800891static const char* const kDebuggerdSeccompPolicy =
892 "/system/etc/seccomp_policy/crash_dump." ABI_STRING ".policy";
893
Josh Gao70adac62018-02-22 11:38:33 -0800894static pid_t seccomp_fork_impl(void (*prejail)()) {
Josh Gao6f9eeec2018-09-12 13:55:47 -0700895 std::string policy;
896 if (!android::base::ReadFileToString(kDebuggerdSeccompPolicy, &policy)) {
897 PLOG(FATAL) << "failed to read policy file";
898 }
899
900 // Allow a bunch of syscalls used by the tests.
901 policy += "\nclone: 1";
902 policy += "\nsigaltstack: 1";
903 policy += "\nnanosleep: 1";
Christopher Ferrisab606682019-09-17 15:31:47 -0700904 policy += "\ngetrlimit: 1";
905 policy += "\nugetrlimit: 1";
Josh Gao6f9eeec2018-09-12 13:55:47 -0700906
907 FILE* tmp_file = tmpfile();
908 if (!tmp_file) {
909 PLOG(FATAL) << "tmpfile failed";
910 }
911
Christopher Ferris172b0a02019-09-18 17:48:30 -0700912 unique_fd tmp_fd(TEMP_FAILURE_RETRY(dup(fileno(tmp_file))));
Josh Gao6f9eeec2018-09-12 13:55:47 -0700913 if (!android::base::WriteStringToFd(policy, tmp_fd.get())) {
914 PLOG(FATAL) << "failed to write policy to tmpfile";
915 }
916
917 if (lseek(tmp_fd.get(), 0, SEEK_SET) != 0) {
918 PLOG(FATAL) << "failed to seek tmp_fd";
Josh Gaoe04ca272018-01-16 15:38:17 -0800919 }
920
921 ScopedMinijail jail{minijail_new()};
922 if (!jail) {
923 LOG(FATAL) << "failed to create minijail";
924 }
925
926 minijail_no_new_privs(jail.get());
927 minijail_log_seccomp_filter_failures(jail.get());
928 minijail_use_seccomp_filter(jail.get());
Josh Gao6f9eeec2018-09-12 13:55:47 -0700929 minijail_parse_seccomp_filters_from_fd(jail.get(), tmp_fd.release());
Josh Gaoe04ca272018-01-16 15:38:17 -0800930
931 pid_t result = fork();
932 if (result == -1) {
933 return result;
934 } else if (result != 0) {
935 return result;
936 }
937
938 // Spawn and detach a thread that spins forever.
939 std::atomic<bool> thread_ready(false);
940 std::thread thread([&jail, &thread_ready]() {
941 minijail_enter(jail.get());
942 thread_ready = true;
943 for (;;)
944 ;
945 });
946 thread.detach();
947
948 while (!thread_ready) {
949 continue;
950 }
951
Josh Gao70adac62018-02-22 11:38:33 -0800952 if (prejail) {
953 prejail();
954 }
955
Josh Gaoe04ca272018-01-16 15:38:17 -0800956 minijail_enter(jail.get());
957 return result;
958}
959
Josh Gao70adac62018-02-22 11:38:33 -0800960static pid_t seccomp_fork() {
961 return seccomp_fork_impl(nullptr);
962}
963
Josh Gaoe04ca272018-01-16 15:38:17 -0800964TEST_F(CrasherTest, seccomp_crash) {
965 int intercept_result;
966 unique_fd output_fd;
967
968 StartProcess([]() { abort(); }, &seccomp_fork);
969
970 StartIntercept(&output_fd);
971 FinishCrasher();
972 AssertDeath(SIGABRT);
973 FinishIntercept(&intercept_result);
974 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
975
976 std::string result;
977 ConsumeFd(std::move(output_fd), &result);
978 ASSERT_BACKTRACE_FRAME(result, "abort");
979}
980
Josh Gao70adac62018-02-22 11:38:33 -0800981static pid_t seccomp_fork_rlimit() {
982 return seccomp_fork_impl([]() {
983 struct rlimit rlim = {
984 .rlim_cur = 512 * 1024 * 1024,
985 .rlim_max = 512 * 1024 * 1024,
986 };
987
988 if (setrlimit(RLIMIT_AS, &rlim) != 0) {
989 raise(SIGINT);
990 }
991 });
992}
993
994TEST_F(CrasherTest, seccomp_crash_oom) {
995 int intercept_result;
996 unique_fd output_fd;
997
998 StartProcess(
999 []() {
1000 std::vector<void*> vec;
1001 for (int i = 0; i < 512; ++i) {
1002 char* buf = static_cast<char*>(malloc(1024 * 1024));
1003 if (!buf) {
1004 abort();
1005 }
1006 memset(buf, 0xff, 1024 * 1024);
1007 vec.push_back(buf);
1008 }
1009 },
1010 &seccomp_fork_rlimit);
1011
1012 StartIntercept(&output_fd);
1013 FinishCrasher();
1014 AssertDeath(SIGABRT);
1015 FinishIntercept(&intercept_result);
1016 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1017
1018 // We can't actually generate a backtrace, just make sure that the process terminates.
1019}
1020
Josh Gaoe04ca272018-01-16 15:38:17 -08001021__attribute__((noinline)) extern "C" bool raise_debugger_signal(DebuggerdDumpType dump_type) {
1022 siginfo_t siginfo;
1023 siginfo.si_code = SI_QUEUE;
1024 siginfo.si_pid = getpid();
1025 siginfo.si_uid = getuid();
1026
1027 if (dump_type != kDebuggerdNativeBacktrace && dump_type != kDebuggerdTombstone) {
1028 PLOG(FATAL) << "invalid dump type";
1029 }
1030
1031 siginfo.si_value.sival_int = dump_type == kDebuggerdNativeBacktrace;
1032
Josh Gaoa48b41b2019-12-13 14:11:04 -08001033 if (syscall(__NR_rt_tgsigqueueinfo, getpid(), gettid(), BIONIC_SIGNAL_DEBUGGER, &siginfo) != 0) {
Josh Gaoe04ca272018-01-16 15:38:17 -08001034 PLOG(ERROR) << "libdebuggerd_client: failed to send signal to self";
1035 return false;
1036 }
1037
1038 return true;
1039}
1040
1041TEST_F(CrasherTest, seccomp_tombstone) {
1042 int intercept_result;
1043 unique_fd output_fd;
1044
1045 static const auto dump_type = kDebuggerdTombstone;
1046 StartProcess(
1047 []() {
1048 raise_debugger_signal(dump_type);
1049 _exit(0);
1050 },
1051 &seccomp_fork);
1052
1053 StartIntercept(&output_fd, dump_type);
1054 FinishCrasher();
1055 AssertDeath(0);
1056 FinishIntercept(&intercept_result);
1057 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1058
1059 std::string result;
1060 ConsumeFd(std::move(output_fd), &result);
1061 ASSERT_BACKTRACE_FRAME(result, "raise_debugger_signal");
1062}
1063
Josh Gao6f9eeec2018-09-12 13:55:47 -07001064extern "C" void foo() {
1065 LOG(INFO) << "foo";
1066 std::this_thread::sleep_for(1s);
1067}
1068
1069extern "C" void bar() {
1070 LOG(INFO) << "bar";
1071 std::this_thread::sleep_for(1s);
1072}
1073
Josh Gaoe04ca272018-01-16 15:38:17 -08001074TEST_F(CrasherTest, seccomp_backtrace) {
1075 int intercept_result;
1076 unique_fd output_fd;
1077
1078 static const auto dump_type = kDebuggerdNativeBacktrace;
1079 StartProcess(
1080 []() {
Josh Gao6f9eeec2018-09-12 13:55:47 -07001081 std::thread a(foo);
1082 std::thread b(bar);
1083
1084 std::this_thread::sleep_for(100ms);
1085
Josh Gaoe04ca272018-01-16 15:38:17 -08001086 raise_debugger_signal(dump_type);
1087 _exit(0);
1088 },
1089 &seccomp_fork);
1090
1091 StartIntercept(&output_fd, dump_type);
1092 FinishCrasher();
1093 AssertDeath(0);
1094 FinishIntercept(&intercept_result);
1095 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1096
1097 std::string result;
1098 ConsumeFd(std::move(output_fd), &result);
1099 ASSERT_BACKTRACE_FRAME(result, "raise_debugger_signal");
Josh Gao6f9eeec2018-09-12 13:55:47 -07001100 ASSERT_BACKTRACE_FRAME(result, "foo");
1101 ASSERT_BACKTRACE_FRAME(result, "bar");
Josh Gaoe04ca272018-01-16 15:38:17 -08001102}
1103
1104TEST_F(CrasherTest, seccomp_crash_logcat) {
1105 StartProcess([]() { abort(); }, &seccomp_fork);
1106 FinishCrasher();
1107
1108 // Make sure we don't get SIGSYS when trying to dump a crash to logcat.
1109 AssertDeath(SIGABRT);
1110}
1111
Josh Gaofd13bf02017-08-18 15:37:26 -07001112TEST_F(CrasherTest, competing_tracer) {
1113 int intercept_result;
1114 unique_fd output_fd;
1115 StartProcess([]() {
Josh Gao2b2ae0c2017-08-21 14:31:17 -07001116 raise(SIGABRT);
Josh Gaofd13bf02017-08-18 15:37:26 -07001117 });
1118
1119 StartIntercept(&output_fd);
Josh Gaofd13bf02017-08-18 15:37:26 -07001120
1121 ASSERT_EQ(0, ptrace(PTRACE_SEIZE, crasher_pid, 0, 0));
Josh Gao2b2ae0c2017-08-21 14:31:17 -07001122 FinishCrasher();
Josh Gaofd13bf02017-08-18 15:37:26 -07001123
1124 int status;
Christopher Ferris172b0a02019-09-18 17:48:30 -07001125 ASSERT_EQ(crasher_pid, TEMP_FAILURE_RETRY(waitpid(crasher_pid, &status, 0)));
Josh Gaofd13bf02017-08-18 15:37:26 -07001126 ASSERT_TRUE(WIFSTOPPED(status));
1127 ASSERT_EQ(SIGABRT, WSTOPSIG(status));
1128
1129 ASSERT_EQ(0, ptrace(PTRACE_CONT, crasher_pid, 0, SIGABRT));
1130 FinishIntercept(&intercept_result);
1131 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1132
1133 std::string result;
1134 ConsumeFd(std::move(output_fd), &result);
1135 std::string regex = R"(failed to attach to thread \d+, already traced by )";
1136 regex += std::to_string(gettid());
1137 regex += R"( \(.+debuggerd_test)";
1138 ASSERT_MATCH(result, regex.c_str());
1139
Christopher Ferris172b0a02019-09-18 17:48:30 -07001140 ASSERT_EQ(crasher_pid, TEMP_FAILURE_RETRY(waitpid(crasher_pid, &status, 0)));
Josh Gao2b2ae0c2017-08-21 14:31:17 -07001141 ASSERT_TRUE(WIFSTOPPED(status));
1142 ASSERT_EQ(SIGABRT, WSTOPSIG(status));
1143
Josh Gaofd13bf02017-08-18 15:37:26 -07001144 ASSERT_EQ(0, ptrace(PTRACE_DETACH, crasher_pid, 0, SIGABRT));
1145 AssertDeath(SIGABRT);
1146}
1147
Josh Gaobf06a402018-08-27 16:34:01 -07001148TEST_F(CrasherTest, fdsan_warning_abort_message) {
1149 int intercept_result;
1150 unique_fd output_fd;
1151
1152 StartProcess([]() {
1153 android_fdsan_set_error_level(ANDROID_FDSAN_ERROR_LEVEL_WARN_ONCE);
Christopher Ferris172b0a02019-09-18 17:48:30 -07001154 unique_fd fd(TEMP_FAILURE_RETRY(open("/dev/null", O_RDONLY | O_CLOEXEC)));
Josh Gaobf06a402018-08-27 16:34:01 -07001155 if (fd == -1) {
1156 abort();
1157 }
1158 close(fd.get());
1159 _exit(0);
1160 });
1161
1162 StartIntercept(&output_fd);
1163 FinishCrasher();
1164 AssertDeath(0);
1165 FinishIntercept(&intercept_result);
1166 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1167
1168 std::string result;
1169 ConsumeFd(std::move(output_fd), &result);
1170 ASSERT_MATCH(result, "Abort message: 'attempted to close");
1171}
1172
Josh Gaoc3c8c022017-02-13 16:36:18 -08001173TEST(crash_dump, zombie) {
1174 pid_t forkpid = fork();
1175
Josh Gaoc3c8c022017-02-13 16:36:18 -08001176 pid_t rc;
1177 int status;
1178
1179 if (forkpid == 0) {
1180 errno = 0;
1181 rc = waitpid(-1, &status, WNOHANG | __WALL | __WNOTHREAD);
1182 if (rc != -1 || errno != ECHILD) {
1183 errx(2, "first waitpid returned %d (%s), expected failure with ECHILD", rc, strerror(errno));
1184 }
1185
Josh Gaoa48b41b2019-12-13 14:11:04 -08001186 raise(BIONIC_SIGNAL_DEBUGGER);
Josh Gaoc3c8c022017-02-13 16:36:18 -08001187
1188 errno = 0;
Christopher Ferris172b0a02019-09-18 17:48:30 -07001189 rc = TEMP_FAILURE_RETRY(waitpid(-1, &status, __WALL | __WNOTHREAD));
Josh Gaoc3c8c022017-02-13 16:36:18 -08001190 if (rc != -1 || errno != ECHILD) {
1191 errx(2, "second waitpid returned %d (%s), expected failure with ECHILD", rc, strerror(errno));
1192 }
1193 _exit(0);
1194 } else {
Christopher Ferris172b0a02019-09-18 17:48:30 -07001195 rc = TEMP_FAILURE_RETRY(waitpid(forkpid, &status, 0));
Josh Gaoc3c8c022017-02-13 16:36:18 -08001196 ASSERT_EQ(forkpid, rc);
1197 ASSERT_TRUE(WIFEXITED(status));
1198 ASSERT_EQ(0, WEXITSTATUS(status));
1199 }
1200}
Josh Gao352a8452017-03-30 16:46:21 -07001201
1202TEST(tombstoned, no_notify) {
1203 // Do this a few times.
1204 for (int i = 0; i < 3; ++i) {
1205 pid_t pid = 123'456'789 + i;
1206
1207 unique_fd intercept_fd, output_fd;
Narayan Kamathca5e9082017-06-02 15:42:06 +01001208 InterceptStatus status;
1209 tombstoned_intercept(pid, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
1210 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gao352a8452017-03-30 16:46:21 -07001211
1212 {
1213 unique_fd tombstoned_socket, input_fd;
Narayan Kamatha73df602017-05-24 15:07:25 +01001214 ASSERT_TRUE(tombstoned_connect(pid, &tombstoned_socket, &input_fd, kDebuggerdTombstone));
Josh Gao352a8452017-03-30 16:46:21 -07001215 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), &pid, sizeof(pid)));
1216 }
1217
1218 pid_t read_pid;
1219 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), &read_pid, sizeof(read_pid)));
1220 ASSERT_EQ(read_pid, pid);
1221 }
1222}
1223
1224TEST(tombstoned, stress) {
1225 // Spawn threads to simultaneously do a bunch of failing dumps and a bunch of successful dumps.
1226 static constexpr int kDumpCount = 100;
1227
1228 std::atomic<bool> start(false);
1229 std::vector<std::thread> threads;
1230 threads.emplace_back([&start]() {
1231 while (!start) {
1232 continue;
1233 }
1234
1235 // Use a way out of range pid, to avoid stomping on an actual process.
1236 pid_t pid_base = 1'000'000;
1237
1238 for (int dump = 0; dump < kDumpCount; ++dump) {
1239 pid_t pid = pid_base + dump;
1240
1241 unique_fd intercept_fd, output_fd;
Narayan Kamathca5e9082017-06-02 15:42:06 +01001242 InterceptStatus status;
1243 tombstoned_intercept(pid, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
1244 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gao352a8452017-03-30 16:46:21 -07001245
1246 // Pretend to crash, and then immediately close the socket.
1247 unique_fd sockfd(socket_local_client(kTombstonedCrashSocketName,
1248 ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_SEQPACKET));
1249 if (sockfd == -1) {
1250 FAIL() << "failed to connect to tombstoned: " << strerror(errno);
1251 }
1252 TombstonedCrashPacket packet = {};
1253 packet.packet_type = CrashPacketType::kDumpRequest;
1254 packet.packet.dump_request.pid = pid;
1255 if (TEMP_FAILURE_RETRY(write(sockfd, &packet, sizeof(packet))) != sizeof(packet)) {
1256 FAIL() << "failed to write to tombstoned: " << strerror(errno);
1257 }
1258
1259 continue;
1260 }
1261 });
1262
1263 threads.emplace_back([&start]() {
1264 while (!start) {
1265 continue;
1266 }
1267
1268 // Use a way out of range pid, to avoid stomping on an actual process.
1269 pid_t pid_base = 2'000'000;
1270
1271 for (int dump = 0; dump < kDumpCount; ++dump) {
1272 pid_t pid = pid_base + dump;
1273
1274 unique_fd intercept_fd, output_fd;
Narayan Kamathca5e9082017-06-02 15:42:06 +01001275 InterceptStatus status;
1276 tombstoned_intercept(pid, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
1277 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gao352a8452017-03-30 16:46:21 -07001278
1279 {
1280 unique_fd tombstoned_socket, input_fd;
Narayan Kamatha73df602017-05-24 15:07:25 +01001281 ASSERT_TRUE(tombstoned_connect(pid, &tombstoned_socket, &input_fd, kDebuggerdTombstone));
Josh Gao352a8452017-03-30 16:46:21 -07001282 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), &pid, sizeof(pid)));
1283 tombstoned_notify_completion(tombstoned_socket.get());
1284 }
1285
1286 // TODO: Fix the race that requires this sleep.
1287 std::this_thread::sleep_for(50ms);
1288
1289 pid_t read_pid;
1290 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), &read_pid, sizeof(read_pid)));
1291 ASSERT_EQ(read_pid, pid);
1292 }
1293 });
1294
1295 start = true;
1296
1297 for (std::thread& thread : threads) {
1298 thread.join();
1299 }
1300}
Narayan Kamathca5e9082017-06-02 15:42:06 +01001301
1302TEST(tombstoned, java_trace_intercept_smoke) {
1303 // Using a "real" PID is a little dangerous here - if the test fails
1304 // or crashes, we might end up getting a bogus / unreliable stack
1305 // trace.
1306 const pid_t self = getpid();
1307
1308 unique_fd intercept_fd, output_fd;
1309 InterceptStatus status;
1310 tombstoned_intercept(self, &intercept_fd, &output_fd, &status, kDebuggerdJavaBacktrace);
1311 ASSERT_EQ(InterceptStatus::kRegistered, status);
1312
1313 // First connect to tombstoned requesting a native backtrace. This
1314 // should result in a "regular" FD and not the installed intercept.
1315 const char native[] = "native";
1316 unique_fd tombstoned_socket, input_fd;
1317 ASSERT_TRUE(tombstoned_connect(self, &tombstoned_socket, &input_fd, kDebuggerdNativeBacktrace));
1318 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), native, sizeof(native)));
1319 tombstoned_notify_completion(tombstoned_socket.get());
1320
1321 // Then, connect to tombstoned asking for a java backtrace. This *should*
1322 // trigger the intercept.
1323 const char java[] = "java";
1324 ASSERT_TRUE(tombstoned_connect(self, &tombstoned_socket, &input_fd, kDebuggerdJavaBacktrace));
1325 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), java, sizeof(java)));
1326 tombstoned_notify_completion(tombstoned_socket.get());
1327
1328 char outbuf[sizeof(java)];
1329 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), outbuf, sizeof(outbuf)));
1330 ASSERT_STREQ("java", outbuf);
1331}
1332
1333TEST(tombstoned, multiple_intercepts) {
1334 const pid_t fake_pid = 1'234'567;
1335 unique_fd intercept_fd, output_fd;
1336 InterceptStatus status;
1337 tombstoned_intercept(fake_pid, &intercept_fd, &output_fd, &status, kDebuggerdJavaBacktrace);
1338 ASSERT_EQ(InterceptStatus::kRegistered, status);
1339
1340 unique_fd intercept_fd_2, output_fd_2;
1341 tombstoned_intercept(fake_pid, &intercept_fd_2, &output_fd_2, &status, kDebuggerdNativeBacktrace);
1342 ASSERT_EQ(InterceptStatus::kFailedAlreadyRegistered, status);
1343}
1344
1345TEST(tombstoned, intercept_any) {
1346 const pid_t fake_pid = 1'234'567;
1347
1348 unique_fd intercept_fd, output_fd;
1349 InterceptStatus status;
1350 tombstoned_intercept(fake_pid, &intercept_fd, &output_fd, &status, kDebuggerdNativeBacktrace);
1351 ASSERT_EQ(InterceptStatus::kRegistered, status);
1352
1353 const char any[] = "any";
1354 unique_fd tombstoned_socket, input_fd;
1355 ASSERT_TRUE(tombstoned_connect(fake_pid, &tombstoned_socket, &input_fd, kDebuggerdAnyIntercept));
1356 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), any, sizeof(any)));
1357 tombstoned_notify_completion(tombstoned_socket.get());
1358
1359 char outbuf[sizeof(any)];
1360 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), outbuf, sizeof(outbuf)));
1361 ASSERT_STREQ("any", outbuf);
1362}
Josh Gao2b22ae12018-09-12 14:51:03 -07001363
1364TEST(tombstoned, interceptless_backtrace) {
1365 // Generate 50 backtraces, and then check to see that we haven't created 50 new tombstones.
1366 auto get_tombstone_timestamps = []() -> std::map<int, time_t> {
1367 std::map<int, time_t> result;
1368 for (int i = 0; i < 99; ++i) {
1369 std::string path = android::base::StringPrintf("/data/tombstones/tombstone_%02d", i);
1370 struct stat st;
1371 if (stat(path.c_str(), &st) == 0) {
1372 result[i] = st.st_mtim.tv_sec;
1373 }
1374 }
1375 return result;
1376 };
1377
1378 auto before = get_tombstone_timestamps();
1379 for (int i = 0; i < 50; ++i) {
1380 raise_debugger_signal(kDebuggerdNativeBacktrace);
1381 }
1382 auto after = get_tombstone_timestamps();
1383
1384 int diff = 0;
1385 for (int i = 0; i < 99; ++i) {
1386 if (after.count(i) == 0) {
1387 continue;
1388 }
1389 if (before.count(i) == 0) {
1390 ++diff;
1391 continue;
1392 }
1393 if (before[i] != after[i]) {
1394 ++diff;
1395 }
1396 }
1397
1398 // We can't be sure that nothing's crash looping in the background.
1399 // This should be good enough, though...
1400 ASSERT_LT(diff, 10) << "too many new tombstones; is something crashing in the background?";
1401}
Christopher Ferris481e8372019-07-15 17:13:24 -07001402
1403static __attribute__((__noinline__)) void overflow_stack(void* p) {
1404 void* buf[1];
1405 buf[0] = p;
1406 static volatile void* global = buf;
1407 if (global) {
1408 global = buf;
1409 overflow_stack(&buf);
1410 }
1411}
1412
1413TEST_F(CrasherTest, stack_overflow) {
1414 int intercept_result;
1415 unique_fd output_fd;
1416 StartProcess([]() { overflow_stack(nullptr); });
1417
1418 StartIntercept(&output_fd);
1419 FinishCrasher();
1420 AssertDeath(SIGSEGV);
1421 FinishIntercept(&intercept_result);
1422
1423 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1424
1425 std::string result;
1426 ConsumeFd(std::move(output_fd), &result);
1427 ASSERT_MATCH(result, R"(Cause: stack pointer[^\n]*stack overflow.\n)");
1428}