blob: b9d66063ef0cdccaadd6572339a8f257609ae5df [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>
Elliott Hughes03b283a2021-01-15 11:34:26 -080019#include <malloc.h>
Josh Gaocdea7502017-11-01 15:00:40 -070020#include <stdlib.h>
Josh Gao502cfd22017-02-17 01:39:15 -080021#include <sys/capability.h>
Peter Collingbournefe8997a2020-07-20 15:08:52 -070022#include <sys/mman.h>
Josh Gaofca7ca32017-01-23 12:05:35 -080023#include <sys/prctl.h>
Josh Gaofd13bf02017-08-18 15:37:26 -070024#include <sys/ptrace.h>
Josh Gao70adac62018-02-22 11:38:33 -080025#include <sys/resource.h>
Dan Albertc38057a2017-10-11 11:35:40 -070026#include <sys/syscall.h>
Josh Gaocbe70cb2016-10-18 18:17:52 -070027#include <sys/types.h>
Josh Gaofd13bf02017-08-18 15:37:26 -070028#include <unistd.h>
Josh Gaocbe70cb2016-10-18 18:17:52 -070029
30#include <chrono>
31#include <regex>
32#include <thread>
33
Josh Gaobf06a402018-08-27 16:34:01 -070034#include <android/fdsan.h>
Josh Gao502cfd22017-02-17 01:39:15 -080035#include <android/set_abort_message.h>
Peter Collingbournef8622522020-04-07 14:07:32 -070036#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() {
Elliott Hughes03b283a2021-01-15 11:34:26 -0800388 if (mallopt(M_BIONIC_SET_HEAP_TAGGING_LEVEL, M_HEAP_TAGGING_LEVEL_SYNC) == 0) {
Peter Collingbournef8622522020-04-07 14:07:32 -0700389 abort();
390 }
391}
392#endif
393
394TEST_F(CrasherTest, mte_uaf) {
Peter Collingbournecd278072020-12-21 14:08:38 -0800395#if defined(__aarch64__)
Peter Collingbournef8622522020-04-07 14:07:32 -0700396 if (!mte_supported()) {
397 GTEST_SKIP() << "Requires MTE";
398 }
399
400 int intercept_result;
401 unique_fd output_fd;
402 StartProcess([]() {
403 SetTagCheckingLevelSync();
404 volatile int* p = (volatile int*)malloc(16);
405 free((void *)p);
406 p[0] = 42;
407 });
408
409 StartIntercept(&output_fd);
410 FinishCrasher();
411 AssertDeath(SIGSEGV);
412 FinishIntercept(&intercept_result);
413
414 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
415
416 std::string result;
417 ConsumeFd(std::move(output_fd), &result);
418
419 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\), code 9 \(SEGV_MTESERR\))");
Peter Collingbournebbe69052020-05-08 10:11:19 -0700420 ASSERT_MATCH(result, R"(Cause: \[MTE\]: Use After Free, 0 bytes into a 16-byte allocation.*
421
422allocated by thread .*
423 #00 pc)");
424 ASSERT_MATCH(result, R"(deallocated by thread .*
425 #00 pc)");
Peter Collingbournef8622522020-04-07 14:07:32 -0700426#else
Peter Collingbournecd278072020-12-21 14:08:38 -0800427 GTEST_SKIP() << "Requires aarch64";
Peter Collingbournef8622522020-04-07 14:07:32 -0700428#endif
429}
430
431TEST_F(CrasherTest, mte_overflow) {
Peter Collingbournecd278072020-12-21 14:08:38 -0800432#if defined(__aarch64__)
Peter Collingbournef8622522020-04-07 14:07:32 -0700433 if (!mte_supported()) {
434 GTEST_SKIP() << "Requires MTE";
435 }
436
437 int intercept_result;
438 unique_fd output_fd;
439 StartProcess([]() {
440 SetTagCheckingLevelSync();
441 volatile int* p = (volatile int*)malloc(16);
442 p[4] = 42;
443 });
444
445 StartIntercept(&output_fd);
446 FinishCrasher();
447 AssertDeath(SIGSEGV);
448 FinishIntercept(&intercept_result);
449
450 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
451
452 std::string result;
453 ConsumeFd(std::move(output_fd), &result);
454
455 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\))");
Peter Collingbournebbe69052020-05-08 10:11:19 -0700456 ASSERT_MATCH(result, R"(Cause: \[MTE\]: Buffer Overflow, 0 bytes right of a 16-byte allocation.*
457
458allocated by thread .*
459 #00 pc)");
Peter Collingbournef8622522020-04-07 14:07:32 -0700460#else
Peter Collingbournecd278072020-12-21 14:08:38 -0800461 GTEST_SKIP() << "Requires aarch64";
Peter Collingbournef8622522020-04-07 14:07:32 -0700462#endif
463}
464
465TEST_F(CrasherTest, mte_underflow) {
Peter Collingbournecd278072020-12-21 14:08:38 -0800466#if defined(__aarch64__)
Peter Collingbournef8622522020-04-07 14:07:32 -0700467 if (!mte_supported()) {
468 GTEST_SKIP() << "Requires MTE";
469 }
470
471 int intercept_result;
472 unique_fd output_fd;
473 StartProcess([]() {
474 SetTagCheckingLevelSync();
475 volatile int* p = (volatile int*)malloc(16);
476 p[-1] = 42;
477 });
478
479 StartIntercept(&output_fd);
480 FinishCrasher();
481 AssertDeath(SIGSEGV);
482 FinishIntercept(&intercept_result);
483
484 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
485
486 std::string result;
487 ConsumeFd(std::move(output_fd), &result);
488
489 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\), code 9 \(SEGV_MTESERR\))");
Peter Collingbournebbe69052020-05-08 10:11:19 -0700490 ASSERT_MATCH(result, R"(Cause: \[MTE\]: Buffer Underflow, 4 bytes left of a 16-byte allocation.*
491
492allocated by thread .*
493 #00 pc)");
Peter Collingbournef8622522020-04-07 14:07:32 -0700494#else
Peter Collingbournecd278072020-12-21 14:08:38 -0800495 GTEST_SKIP() << "Requires aarch64";
Peter Collingbournef8622522020-04-07 14:07:32 -0700496#endif
497}
498
499TEST_F(CrasherTest, mte_multiple_causes) {
Peter Collingbournecd278072020-12-21 14:08:38 -0800500#if defined(__aarch64__)
Peter Collingbournef8622522020-04-07 14:07:32 -0700501 if (!mte_supported()) {
502 GTEST_SKIP() << "Requires MTE";
503 }
504
505 int intercept_result;
506 unique_fd output_fd;
507 StartProcess([]() {
508 SetTagCheckingLevelSync();
509
510 // Make two allocations with the same tag and close to one another. Check for both properties
511 // with a bounds check -- this relies on the fact that only if the allocations have the same tag
512 // would they be measured as closer than 128 bytes to each other. Otherwise they would be about
513 // (some non-zero value << 56) apart.
514 //
515 // The out-of-bounds access will be considered either an overflow of one or an underflow of the
516 // other.
517 std::set<uintptr_t> allocs;
518 for (int i = 0; i != 4096; ++i) {
519 uintptr_t alloc = reinterpret_cast<uintptr_t>(malloc(16));
520 auto it = allocs.insert(alloc).first;
521 if (it != allocs.begin() && *std::prev(it) + 128 > alloc) {
522 *reinterpret_cast<int*>(*std::prev(it) + 16) = 42;
523 }
524 if (std::next(it) != allocs.end() && alloc + 128 > *std::next(it)) {
525 *reinterpret_cast<int*>(alloc + 16) = 42;
526 }
527 }
528 });
529
530 StartIntercept(&output_fd);
531 FinishCrasher();
532 AssertDeath(SIGSEGV);
533 FinishIntercept(&intercept_result);
534
535 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
536
537 std::string result;
538 ConsumeFd(std::move(output_fd), &result);
539
540 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\))");
541 ASSERT_MATCH(
542 result,
543 R"(Note: multiple potential causes for this crash were detected, listing them in decreasing order of probability.)");
544
545 // Adjacent untracked allocations may cause us to see the wrong underflow here (or only
546 // overflows), so we can't match explicitly for an underflow message.
547 ASSERT_MATCH(result, R"(Cause: \[MTE\]: Buffer Overflow, 0 bytes right of a 16-byte allocation)");
548#else
Peter Collingbournecd278072020-12-21 14:08:38 -0800549 GTEST_SKIP() << "Requires aarch64";
Peter Collingbournef8622522020-04-07 14:07:32 -0700550#endif
551}
552
Peter Collingbournecd278072020-12-21 14:08:38 -0800553#if defined(__aarch64__)
Peter Collingbournefe8997a2020-07-20 15:08:52 -0700554static uintptr_t CreateTagMapping() {
555 uintptr_t mapping =
556 reinterpret_cast<uintptr_t>(mmap(nullptr, getpagesize(), PROT_READ | PROT_WRITE | PROT_MTE,
557 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0));
558 if (reinterpret_cast<void*>(mapping) == MAP_FAILED) {
559 return 0;
560 }
561 __asm__ __volatile__(".arch_extension mte; stg %0, [%0]"
562 :
563 : "r"(mapping + (1ULL << 56))
564 : "memory");
565 return mapping;
566}
567#endif
568
569TEST_F(CrasherTest, mte_tag_dump) {
Peter Collingbournecd278072020-12-21 14:08:38 -0800570#if defined(__aarch64__)
Peter Collingbournefe8997a2020-07-20 15:08:52 -0700571 if (!mte_supported()) {
572 GTEST_SKIP() << "Requires MTE";
573 }
574
575 int intercept_result;
576 unique_fd output_fd;
577 StartProcess([&]() {
578 SetTagCheckingLevelSync();
579 Trap(reinterpret_cast<void *>(CreateTagMapping()));
580 });
581
582 StartIntercept(&output_fd);
583 FinishCrasher();
584 AssertDeath(SIGTRAP);
585 FinishIntercept(&intercept_result);
586
587 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
588
589 std::string result;
590 ConsumeFd(std::move(output_fd), &result);
591
592 ASSERT_MATCH(result, R"(memory near x0:
593.*
594.*
595 01.............0 0000000000000000 0000000000000000 ................
596 00.............0)");
597#else
Peter Collingbournecd278072020-12-21 14:08:38 -0800598 GTEST_SKIP() << "Requires aarch64";
Peter Collingbournefe8997a2020-07-20 15:08:52 -0700599#endif
600}
601
Josh Gaocdea7502017-11-01 15:00:40 -0700602TEST_F(CrasherTest, LD_PRELOAD) {
603 int intercept_result;
604 unique_fd output_fd;
605 StartProcess([]() {
606 setenv("LD_PRELOAD", "nonexistent.so", 1);
607 *reinterpret_cast<volatile char*>(0xdead) = '1';
608 });
609
610 StartIntercept(&output_fd);
611 FinishCrasher();
612 AssertDeath(SIGSEGV);
613 FinishIntercept(&intercept_result);
614
615 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
616
617 std::string result;
618 ConsumeFd(std::move(output_fd), &result);
619 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\), code 1 \(SEGV_MAPERR\), fault addr 0xdead)");
620}
621
Josh Gaocbe70cb2016-10-18 18:17:52 -0700622TEST_F(CrasherTest, abort) {
623 int intercept_result;
624 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800625 StartProcess([]() {
626 abort();
627 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700628 StartIntercept(&output_fd);
629 FinishCrasher();
630 AssertDeath(SIGABRT);
631 FinishIntercept(&intercept_result);
632
633 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
634
635 std::string result;
636 ConsumeFd(std::move(output_fd), &result);
Andreas Gampe26cbafb2017-06-22 20:14:43 -0700637 ASSERT_BACKTRACE_FRAME(result, "abort");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700638}
639
640TEST_F(CrasherTest, signal) {
641 int intercept_result;
642 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800643 StartProcess([]() {
Josh Gao2b2ae0c2017-08-21 14:31:17 -0700644 while (true) {
645 sleep(1);
646 }
Josh Gao502cfd22017-02-17 01:39:15 -0800647 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700648 StartIntercept(&output_fd);
Josh Gao2b2ae0c2017-08-21 14:31:17 -0700649 FinishCrasher();
Josh Gaocbe70cb2016-10-18 18:17:52 -0700650 ASSERT_EQ(0, kill(crasher_pid, SIGSEGV));
651
652 AssertDeath(SIGSEGV);
653 FinishIntercept(&intercept_result);
654
655 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
656
657 std::string result;
658 ConsumeFd(std::move(output_fd), &result);
Elliott Hughes89722702018-05-02 10:47:00 -0700659 ASSERT_MATCH(
660 result,
661 R"(signal 11 \(SIGSEGV\), code 0 \(SI_USER from pid \d+, uid \d+\), fault addr --------)");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700662 ASSERT_MATCH(result, R"(backtrace:)");
663}
664
665TEST_F(CrasherTest, abort_message) {
666 int intercept_result;
667 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800668 StartProcess([]() {
Josh Gao1cc7bd82018-02-13 13:16:17 -0800669 // Arrived at experimentally;
670 // logd truncates at 4062.
671 // strlen("Abort message: ''") is 17.
672 // That's 4045, but we also want a NUL.
673 char buf[4045 + 1];
674 memset(buf, 'x', sizeof(buf));
675 buf[sizeof(buf) - 1] = '\0';
676 android_set_abort_message(buf);
Josh Gao502cfd22017-02-17 01:39:15 -0800677 abort();
678 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700679 StartIntercept(&output_fd);
680 FinishCrasher();
681 AssertDeath(SIGABRT);
682 FinishIntercept(&intercept_result);
683
684 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
685
686 std::string result;
687 ConsumeFd(std::move(output_fd), &result);
Josh Gao1cc7bd82018-02-13 13:16:17 -0800688 ASSERT_MATCH(result, R"(Abort message: 'x{4045}')");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700689}
690
Josh Gaoe06f2a42017-04-27 16:50:38 -0700691TEST_F(CrasherTest, abort_message_backtrace) {
692 int intercept_result;
693 unique_fd output_fd;
694 StartProcess([]() {
695 android_set_abort_message("not actually aborting");
Josh Gaoa48b41b2019-12-13 14:11:04 -0800696 raise(BIONIC_SIGNAL_DEBUGGER);
Josh Gaoe06f2a42017-04-27 16:50:38 -0700697 exit(0);
698 });
699 StartIntercept(&output_fd);
700 FinishCrasher();
701 AssertDeath(0);
702 FinishIntercept(&intercept_result);
703
704 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
705
706 std::string result;
707 ConsumeFd(std::move(output_fd), &result);
708 ASSERT_NOT_MATCH(result, R"(Abort message:)");
709}
710
Josh Gaocbe70cb2016-10-18 18:17:52 -0700711TEST_F(CrasherTest, intercept_timeout) {
712 int intercept_result;
713 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800714 StartProcess([]() {
715 abort();
716 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700717 StartIntercept(&output_fd);
718
719 // Don't let crasher finish until we timeout.
720 FinishIntercept(&intercept_result);
721
722 ASSERT_NE(1, intercept_result) << "tombstoned reported success? (intercept_result = "
723 << intercept_result << ")";
724
725 FinishCrasher();
726 AssertDeath(SIGABRT);
727}
728
729TEST_F(CrasherTest, wait_for_gdb) {
730 if (!android::base::SetProperty(kWaitForGdbKey, "1")) {
731 FAIL() << "failed to enable wait_for_gdb";
732 }
733 sleep(1);
734
Josh Gao502cfd22017-02-17 01:39:15 -0800735 StartProcess([]() {
736 abort();
737 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700738 FinishCrasher();
739
740 int status;
Christopher Ferris172b0a02019-09-18 17:48:30 -0700741 ASSERT_EQ(crasher_pid, TEMP_FAILURE_RETRY(waitpid(crasher_pid, &status, WUNTRACED)));
Josh Gaocbe70cb2016-10-18 18:17:52 -0700742 ASSERT_TRUE(WIFSTOPPED(status));
743 ASSERT_EQ(SIGSTOP, WSTOPSIG(status));
744
745 ASSERT_EQ(0, kill(crasher_pid, SIGCONT));
746
747 AssertDeath(SIGABRT);
748}
749
Josh Gaocbe70cb2016-10-18 18:17:52 -0700750TEST_F(CrasherTest, backtrace) {
751 std::string result;
752 int intercept_result;
753 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800754
755 StartProcess([]() {
756 abort();
757 });
Narayan Kamatha73df602017-05-24 15:07:25 +0100758 StartIntercept(&output_fd, kDebuggerdNativeBacktrace);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700759
760 std::this_thread::sleep_for(500ms);
761
762 sigval val;
763 val.sival_int = 1;
Josh Gaoa48b41b2019-12-13 14:11:04 -0800764 ASSERT_EQ(0, sigqueue(crasher_pid, BIONIC_SIGNAL_DEBUGGER, val)) << strerror(errno);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700765 FinishIntercept(&intercept_result);
766 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
767 ConsumeFd(std::move(output_fd), &result);
Jaesung Chung58778e12017-06-15 18:20:34 +0900768 ASSERT_BACKTRACE_FRAME(result, "read");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700769
770 int status;
771 ASSERT_EQ(0, waitpid(crasher_pid, &status, WNOHANG | WUNTRACED));
772
773 StartIntercept(&output_fd);
774 FinishCrasher();
775 AssertDeath(SIGABRT);
776 FinishIntercept(&intercept_result);
777 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
778 ConsumeFd(std::move(output_fd), &result);
Andreas Gampe26cbafb2017-06-22 20:14:43 -0700779 ASSERT_BACKTRACE_FRAME(result, "abort");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700780}
Josh Gaofca7ca32017-01-23 12:05:35 -0800781
782TEST_F(CrasherTest, PR_SET_DUMPABLE_0_crash) {
Josh Gao502cfd22017-02-17 01:39:15 -0800783 int intercept_result;
784 unique_fd output_fd;
Josh Gaofca7ca32017-01-23 12:05:35 -0800785 StartProcess([]() {
786 prctl(PR_SET_DUMPABLE, 0);
Josh Gao502cfd22017-02-17 01:39:15 -0800787 abort();
Josh Gaofca7ca32017-01-23 12:05:35 -0800788 });
Josh Gao502cfd22017-02-17 01:39:15 -0800789
790 StartIntercept(&output_fd);
791 FinishCrasher();
792 AssertDeath(SIGABRT);
793 FinishIntercept(&intercept_result);
794
795 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
796
797 std::string result;
798 ConsumeFd(std::move(output_fd), &result);
Andreas Gampe26cbafb2017-06-22 20:14:43 -0700799 ASSERT_BACKTRACE_FRAME(result, "abort");
Josh Gaofca7ca32017-01-23 12:05:35 -0800800}
801
Josh Gao502cfd22017-02-17 01:39:15 -0800802TEST_F(CrasherTest, capabilities) {
803 ASSERT_EQ(0U, getuid()) << "capability test requires root";
804
Josh Gaofca7ca32017-01-23 12:05:35 -0800805 StartProcess([]() {
Josh Gao502cfd22017-02-17 01:39:15 -0800806 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) != 0) {
807 err(1, "failed to set PR_SET_KEEPCAPS");
808 }
809
810 if (setresuid(1, 1, 1) != 0) {
811 err(1, "setresuid failed");
812 }
813
814 __user_cap_header_struct capheader;
815 __user_cap_data_struct capdata[2];
816 memset(&capheader, 0, sizeof(capheader));
817 memset(&capdata, 0, sizeof(capdata));
818
819 capheader.version = _LINUX_CAPABILITY_VERSION_3;
820 capheader.pid = 0;
821
822 // Turn on every third capability.
823 static_assert(CAP_LAST_CAP > 33, "CAP_LAST_CAP <= 32");
824 for (int i = 0; i < CAP_LAST_CAP; i += 3) {
825 capdata[CAP_TO_INDEX(i)].permitted |= CAP_TO_MASK(i);
826 capdata[CAP_TO_INDEX(i)].effective |= CAP_TO_MASK(i);
827 }
828
829 // Make sure CAP_SYS_PTRACE is off.
830 capdata[CAP_TO_INDEX(CAP_SYS_PTRACE)].permitted &= ~(CAP_TO_MASK(CAP_SYS_PTRACE));
831 capdata[CAP_TO_INDEX(CAP_SYS_PTRACE)].effective &= ~(CAP_TO_MASK(CAP_SYS_PTRACE));
832
833 if (capset(&capheader, &capdata[0]) != 0) {
834 err(1, "capset failed");
835 }
836
837 if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_CLEAR_ALL, 0, 0, 0) != 0) {
838 err(1, "failed to drop ambient capabilities");
839 }
840
Josh Gaoa5199a92017-04-03 13:18:34 -0700841 pthread_setname_np(pthread_self(), "thread_name");
Josh Gao502cfd22017-02-17 01:39:15 -0800842 raise(SIGSYS);
Josh Gaofca7ca32017-01-23 12:05:35 -0800843 });
Josh Gao502cfd22017-02-17 01:39:15 -0800844
845 unique_fd output_fd;
846 StartIntercept(&output_fd);
847 FinishCrasher();
848 AssertDeath(SIGSYS);
849
850 std::string result;
851 int intercept_result;
852 FinishIntercept(&intercept_result);
853 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
854 ConsumeFd(std::move(output_fd), &result);
Josh Gaoa5199a92017-04-03 13:18:34 -0700855 ASSERT_MATCH(result, R"(name: thread_name\s+>>> .+debuggerd_test(32|64) <<<)");
Jaesung Chung58778e12017-06-15 18:20:34 +0900856 ASSERT_BACKTRACE_FRAME(result, "tgkill");
Josh Gaofca7ca32017-01-23 12:05:35 -0800857}
Josh Gaoc3c8c022017-02-13 16:36:18 -0800858
Josh Gao2e7b8e22017-05-04 17:12:57 -0700859TEST_F(CrasherTest, fake_pid) {
860 int intercept_result;
861 unique_fd output_fd;
862
863 // Prime the getpid/gettid caches.
864 UNUSED(getpid());
865 UNUSED(gettid());
866
867 std::function<pid_t()> clone_fn = []() {
868 return syscall(__NR_clone, SIGCHLD, nullptr, nullptr, nullptr, nullptr);
869 };
870 StartProcess(
871 []() {
872 ASSERT_NE(getpid(), syscall(__NR_getpid));
873 ASSERT_NE(gettid(), syscall(__NR_gettid));
874 raise(SIGSEGV);
875 },
876 clone_fn);
877
878 StartIntercept(&output_fd);
879 FinishCrasher();
880 AssertDeath(SIGSEGV);
881 FinishIntercept(&intercept_result);
882
883 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
884
885 std::string result;
886 ConsumeFd(std::move(output_fd), &result);
Jaesung Chung58778e12017-06-15 18:20:34 +0900887 ASSERT_BACKTRACE_FRAME(result, "tgkill");
Josh Gao2e7b8e22017-05-04 17:12:57 -0700888}
889
Josh Gaoe04ca272018-01-16 15:38:17 -0800890static const char* const kDebuggerdSeccompPolicy =
891 "/system/etc/seccomp_policy/crash_dump." ABI_STRING ".policy";
892
Josh Gao70adac62018-02-22 11:38:33 -0800893static pid_t seccomp_fork_impl(void (*prejail)()) {
Josh Gao6f9eeec2018-09-12 13:55:47 -0700894 std::string policy;
895 if (!android::base::ReadFileToString(kDebuggerdSeccompPolicy, &policy)) {
896 PLOG(FATAL) << "failed to read policy file";
897 }
898
899 // Allow a bunch of syscalls used by the tests.
900 policy += "\nclone: 1";
901 policy += "\nsigaltstack: 1";
902 policy += "\nnanosleep: 1";
Christopher Ferrisab606682019-09-17 15:31:47 -0700903 policy += "\ngetrlimit: 1";
904 policy += "\nugetrlimit: 1";
Josh Gao6f9eeec2018-09-12 13:55:47 -0700905
906 FILE* tmp_file = tmpfile();
907 if (!tmp_file) {
908 PLOG(FATAL) << "tmpfile failed";
909 }
910
Christopher Ferris172b0a02019-09-18 17:48:30 -0700911 unique_fd tmp_fd(TEMP_FAILURE_RETRY(dup(fileno(tmp_file))));
Josh Gao6f9eeec2018-09-12 13:55:47 -0700912 if (!android::base::WriteStringToFd(policy, tmp_fd.get())) {
913 PLOG(FATAL) << "failed to write policy to tmpfile";
914 }
915
916 if (lseek(tmp_fd.get(), 0, SEEK_SET) != 0) {
917 PLOG(FATAL) << "failed to seek tmp_fd";
Josh Gaoe04ca272018-01-16 15:38:17 -0800918 }
919
920 ScopedMinijail jail{minijail_new()};
921 if (!jail) {
922 LOG(FATAL) << "failed to create minijail";
923 }
924
925 minijail_no_new_privs(jail.get());
926 minijail_log_seccomp_filter_failures(jail.get());
927 minijail_use_seccomp_filter(jail.get());
Josh Gao6f9eeec2018-09-12 13:55:47 -0700928 minijail_parse_seccomp_filters_from_fd(jail.get(), tmp_fd.release());
Josh Gaoe04ca272018-01-16 15:38:17 -0800929
930 pid_t result = fork();
931 if (result == -1) {
932 return result;
933 } else if (result != 0) {
934 return result;
935 }
936
937 // Spawn and detach a thread that spins forever.
938 std::atomic<bool> thread_ready(false);
939 std::thread thread([&jail, &thread_ready]() {
940 minijail_enter(jail.get());
941 thread_ready = true;
942 for (;;)
943 ;
944 });
945 thread.detach();
946
947 while (!thread_ready) {
948 continue;
949 }
950
Josh Gao70adac62018-02-22 11:38:33 -0800951 if (prejail) {
952 prejail();
953 }
954
Josh Gaoe04ca272018-01-16 15:38:17 -0800955 minijail_enter(jail.get());
956 return result;
957}
958
Josh Gao70adac62018-02-22 11:38:33 -0800959static pid_t seccomp_fork() {
960 return seccomp_fork_impl(nullptr);
961}
962
Josh Gaoe04ca272018-01-16 15:38:17 -0800963TEST_F(CrasherTest, seccomp_crash) {
964 int intercept_result;
965 unique_fd output_fd;
966
967 StartProcess([]() { abort(); }, &seccomp_fork);
968
969 StartIntercept(&output_fd);
970 FinishCrasher();
971 AssertDeath(SIGABRT);
972 FinishIntercept(&intercept_result);
973 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
974
975 std::string result;
976 ConsumeFd(std::move(output_fd), &result);
977 ASSERT_BACKTRACE_FRAME(result, "abort");
978}
979
Josh Gao70adac62018-02-22 11:38:33 -0800980static pid_t seccomp_fork_rlimit() {
981 return seccomp_fork_impl([]() {
982 struct rlimit rlim = {
983 .rlim_cur = 512 * 1024 * 1024,
984 .rlim_max = 512 * 1024 * 1024,
985 };
986
987 if (setrlimit(RLIMIT_AS, &rlim) != 0) {
988 raise(SIGINT);
989 }
990 });
991}
992
993TEST_F(CrasherTest, seccomp_crash_oom) {
994 int intercept_result;
995 unique_fd output_fd;
996
997 StartProcess(
998 []() {
999 std::vector<void*> vec;
1000 for (int i = 0; i < 512; ++i) {
1001 char* buf = static_cast<char*>(malloc(1024 * 1024));
1002 if (!buf) {
1003 abort();
1004 }
1005 memset(buf, 0xff, 1024 * 1024);
1006 vec.push_back(buf);
1007 }
1008 },
1009 &seccomp_fork_rlimit);
1010
1011 StartIntercept(&output_fd);
1012 FinishCrasher();
1013 AssertDeath(SIGABRT);
1014 FinishIntercept(&intercept_result);
1015 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1016
1017 // We can't actually generate a backtrace, just make sure that the process terminates.
1018}
1019
Josh Gaoe04ca272018-01-16 15:38:17 -08001020__attribute__((noinline)) extern "C" bool raise_debugger_signal(DebuggerdDumpType dump_type) {
1021 siginfo_t siginfo;
1022 siginfo.si_code = SI_QUEUE;
1023 siginfo.si_pid = getpid();
1024 siginfo.si_uid = getuid();
1025
1026 if (dump_type != kDebuggerdNativeBacktrace && dump_type != kDebuggerdTombstone) {
1027 PLOG(FATAL) << "invalid dump type";
1028 }
1029
1030 siginfo.si_value.sival_int = dump_type == kDebuggerdNativeBacktrace;
1031
Josh Gaoa48b41b2019-12-13 14:11:04 -08001032 if (syscall(__NR_rt_tgsigqueueinfo, getpid(), gettid(), BIONIC_SIGNAL_DEBUGGER, &siginfo) != 0) {
Josh Gaoe04ca272018-01-16 15:38:17 -08001033 PLOG(ERROR) << "libdebuggerd_client: failed to send signal to self";
1034 return false;
1035 }
1036
1037 return true;
1038}
1039
1040TEST_F(CrasherTest, seccomp_tombstone) {
1041 int intercept_result;
1042 unique_fd output_fd;
1043
1044 static const auto dump_type = kDebuggerdTombstone;
1045 StartProcess(
1046 []() {
1047 raise_debugger_signal(dump_type);
1048 _exit(0);
1049 },
1050 &seccomp_fork);
1051
1052 StartIntercept(&output_fd, dump_type);
1053 FinishCrasher();
1054 AssertDeath(0);
1055 FinishIntercept(&intercept_result);
1056 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1057
1058 std::string result;
1059 ConsumeFd(std::move(output_fd), &result);
1060 ASSERT_BACKTRACE_FRAME(result, "raise_debugger_signal");
1061}
1062
Josh Gao6f9eeec2018-09-12 13:55:47 -07001063extern "C" void foo() {
1064 LOG(INFO) << "foo";
1065 std::this_thread::sleep_for(1s);
1066}
1067
1068extern "C" void bar() {
1069 LOG(INFO) << "bar";
1070 std::this_thread::sleep_for(1s);
1071}
1072
Josh Gaoe04ca272018-01-16 15:38:17 -08001073TEST_F(CrasherTest, seccomp_backtrace) {
1074 int intercept_result;
1075 unique_fd output_fd;
1076
1077 static const auto dump_type = kDebuggerdNativeBacktrace;
1078 StartProcess(
1079 []() {
Josh Gao6f9eeec2018-09-12 13:55:47 -07001080 std::thread a(foo);
1081 std::thread b(bar);
1082
1083 std::this_thread::sleep_for(100ms);
1084
Josh Gaoe04ca272018-01-16 15:38:17 -08001085 raise_debugger_signal(dump_type);
1086 _exit(0);
1087 },
1088 &seccomp_fork);
1089
1090 StartIntercept(&output_fd, dump_type);
1091 FinishCrasher();
1092 AssertDeath(0);
1093 FinishIntercept(&intercept_result);
1094 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1095
1096 std::string result;
1097 ConsumeFd(std::move(output_fd), &result);
1098 ASSERT_BACKTRACE_FRAME(result, "raise_debugger_signal");
Josh Gao6f9eeec2018-09-12 13:55:47 -07001099 ASSERT_BACKTRACE_FRAME(result, "foo");
1100 ASSERT_BACKTRACE_FRAME(result, "bar");
Josh Gaoe04ca272018-01-16 15:38:17 -08001101}
1102
1103TEST_F(CrasherTest, seccomp_crash_logcat) {
1104 StartProcess([]() { abort(); }, &seccomp_fork);
1105 FinishCrasher();
1106
1107 // Make sure we don't get SIGSYS when trying to dump a crash to logcat.
1108 AssertDeath(SIGABRT);
1109}
1110
Josh Gaofd13bf02017-08-18 15:37:26 -07001111TEST_F(CrasherTest, competing_tracer) {
1112 int intercept_result;
1113 unique_fd output_fd;
1114 StartProcess([]() {
Josh Gao2b2ae0c2017-08-21 14:31:17 -07001115 raise(SIGABRT);
Josh Gaofd13bf02017-08-18 15:37:26 -07001116 });
1117
1118 StartIntercept(&output_fd);
Josh Gaofd13bf02017-08-18 15:37:26 -07001119
1120 ASSERT_EQ(0, ptrace(PTRACE_SEIZE, crasher_pid, 0, 0));
Josh Gao2b2ae0c2017-08-21 14:31:17 -07001121 FinishCrasher();
Josh Gaofd13bf02017-08-18 15:37:26 -07001122
1123 int status;
Christopher Ferris172b0a02019-09-18 17:48:30 -07001124 ASSERT_EQ(crasher_pid, TEMP_FAILURE_RETRY(waitpid(crasher_pid, &status, 0)));
Josh Gaofd13bf02017-08-18 15:37:26 -07001125 ASSERT_TRUE(WIFSTOPPED(status));
1126 ASSERT_EQ(SIGABRT, WSTOPSIG(status));
1127
1128 ASSERT_EQ(0, ptrace(PTRACE_CONT, crasher_pid, 0, SIGABRT));
1129 FinishIntercept(&intercept_result);
1130 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1131
1132 std::string result;
1133 ConsumeFd(std::move(output_fd), &result);
1134 std::string regex = R"(failed to attach to thread \d+, already traced by )";
1135 regex += std::to_string(gettid());
1136 regex += R"( \(.+debuggerd_test)";
1137 ASSERT_MATCH(result, regex.c_str());
1138
Christopher Ferris172b0a02019-09-18 17:48:30 -07001139 ASSERT_EQ(crasher_pid, TEMP_FAILURE_RETRY(waitpid(crasher_pid, &status, 0)));
Josh Gao2b2ae0c2017-08-21 14:31:17 -07001140 ASSERT_TRUE(WIFSTOPPED(status));
1141 ASSERT_EQ(SIGABRT, WSTOPSIG(status));
1142
Josh Gaofd13bf02017-08-18 15:37:26 -07001143 ASSERT_EQ(0, ptrace(PTRACE_DETACH, crasher_pid, 0, SIGABRT));
1144 AssertDeath(SIGABRT);
1145}
1146
Josh Gaobf06a402018-08-27 16:34:01 -07001147TEST_F(CrasherTest, fdsan_warning_abort_message) {
1148 int intercept_result;
1149 unique_fd output_fd;
1150
1151 StartProcess([]() {
1152 android_fdsan_set_error_level(ANDROID_FDSAN_ERROR_LEVEL_WARN_ONCE);
Christopher Ferris172b0a02019-09-18 17:48:30 -07001153 unique_fd fd(TEMP_FAILURE_RETRY(open("/dev/null", O_RDONLY | O_CLOEXEC)));
Josh Gaobf06a402018-08-27 16:34:01 -07001154 if (fd == -1) {
1155 abort();
1156 }
1157 close(fd.get());
1158 _exit(0);
1159 });
1160
1161 StartIntercept(&output_fd);
1162 FinishCrasher();
1163 AssertDeath(0);
1164 FinishIntercept(&intercept_result);
1165 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1166
1167 std::string result;
1168 ConsumeFd(std::move(output_fd), &result);
1169 ASSERT_MATCH(result, "Abort message: 'attempted to close");
1170}
1171
Josh Gaoc3c8c022017-02-13 16:36:18 -08001172TEST(crash_dump, zombie) {
1173 pid_t forkpid = fork();
1174
Josh Gaoc3c8c022017-02-13 16:36:18 -08001175 pid_t rc;
1176 int status;
1177
1178 if (forkpid == 0) {
1179 errno = 0;
1180 rc = waitpid(-1, &status, WNOHANG | __WALL | __WNOTHREAD);
1181 if (rc != -1 || errno != ECHILD) {
1182 errx(2, "first waitpid returned %d (%s), expected failure with ECHILD", rc, strerror(errno));
1183 }
1184
Josh Gaoa48b41b2019-12-13 14:11:04 -08001185 raise(BIONIC_SIGNAL_DEBUGGER);
Josh Gaoc3c8c022017-02-13 16:36:18 -08001186
1187 errno = 0;
Christopher Ferris172b0a02019-09-18 17:48:30 -07001188 rc = TEMP_FAILURE_RETRY(waitpid(-1, &status, __WALL | __WNOTHREAD));
Josh Gaoc3c8c022017-02-13 16:36:18 -08001189 if (rc != -1 || errno != ECHILD) {
1190 errx(2, "second waitpid returned %d (%s), expected failure with ECHILD", rc, strerror(errno));
1191 }
1192 _exit(0);
1193 } else {
Christopher Ferris172b0a02019-09-18 17:48:30 -07001194 rc = TEMP_FAILURE_RETRY(waitpid(forkpid, &status, 0));
Josh Gaoc3c8c022017-02-13 16:36:18 -08001195 ASSERT_EQ(forkpid, rc);
1196 ASSERT_TRUE(WIFEXITED(status));
1197 ASSERT_EQ(0, WEXITSTATUS(status));
1198 }
1199}
Josh Gao352a8452017-03-30 16:46:21 -07001200
1201TEST(tombstoned, no_notify) {
1202 // Do this a few times.
1203 for (int i = 0; i < 3; ++i) {
1204 pid_t pid = 123'456'789 + i;
1205
1206 unique_fd intercept_fd, output_fd;
Narayan Kamathca5e9082017-06-02 15:42:06 +01001207 InterceptStatus status;
1208 tombstoned_intercept(pid, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
1209 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gao352a8452017-03-30 16:46:21 -07001210
1211 {
1212 unique_fd tombstoned_socket, input_fd;
Narayan Kamatha73df602017-05-24 15:07:25 +01001213 ASSERT_TRUE(tombstoned_connect(pid, &tombstoned_socket, &input_fd, kDebuggerdTombstone));
Josh Gao352a8452017-03-30 16:46:21 -07001214 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), &pid, sizeof(pid)));
1215 }
1216
1217 pid_t read_pid;
1218 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), &read_pid, sizeof(read_pid)));
1219 ASSERT_EQ(read_pid, pid);
1220 }
1221}
1222
1223TEST(tombstoned, stress) {
1224 // Spawn threads to simultaneously do a bunch of failing dumps and a bunch of successful dumps.
1225 static constexpr int kDumpCount = 100;
1226
1227 std::atomic<bool> start(false);
1228 std::vector<std::thread> threads;
1229 threads.emplace_back([&start]() {
1230 while (!start) {
1231 continue;
1232 }
1233
1234 // Use a way out of range pid, to avoid stomping on an actual process.
1235 pid_t pid_base = 1'000'000;
1236
1237 for (int dump = 0; dump < kDumpCount; ++dump) {
1238 pid_t pid = pid_base + dump;
1239
1240 unique_fd intercept_fd, output_fd;
Narayan Kamathca5e9082017-06-02 15:42:06 +01001241 InterceptStatus status;
1242 tombstoned_intercept(pid, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
1243 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gao352a8452017-03-30 16:46:21 -07001244
1245 // Pretend to crash, and then immediately close the socket.
1246 unique_fd sockfd(socket_local_client(kTombstonedCrashSocketName,
1247 ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_SEQPACKET));
1248 if (sockfd == -1) {
1249 FAIL() << "failed to connect to tombstoned: " << strerror(errno);
1250 }
1251 TombstonedCrashPacket packet = {};
1252 packet.packet_type = CrashPacketType::kDumpRequest;
1253 packet.packet.dump_request.pid = pid;
1254 if (TEMP_FAILURE_RETRY(write(sockfd, &packet, sizeof(packet))) != sizeof(packet)) {
1255 FAIL() << "failed to write to tombstoned: " << strerror(errno);
1256 }
1257
1258 continue;
1259 }
1260 });
1261
1262 threads.emplace_back([&start]() {
1263 while (!start) {
1264 continue;
1265 }
1266
1267 // Use a way out of range pid, to avoid stomping on an actual process.
1268 pid_t pid_base = 2'000'000;
1269
1270 for (int dump = 0; dump < kDumpCount; ++dump) {
1271 pid_t pid = pid_base + dump;
1272
1273 unique_fd intercept_fd, output_fd;
Narayan Kamathca5e9082017-06-02 15:42:06 +01001274 InterceptStatus status;
1275 tombstoned_intercept(pid, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
1276 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gao352a8452017-03-30 16:46:21 -07001277
1278 {
1279 unique_fd tombstoned_socket, input_fd;
Narayan Kamatha73df602017-05-24 15:07:25 +01001280 ASSERT_TRUE(tombstoned_connect(pid, &tombstoned_socket, &input_fd, kDebuggerdTombstone));
Josh Gao352a8452017-03-30 16:46:21 -07001281 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), &pid, sizeof(pid)));
1282 tombstoned_notify_completion(tombstoned_socket.get());
1283 }
1284
1285 // TODO: Fix the race that requires this sleep.
1286 std::this_thread::sleep_for(50ms);
1287
1288 pid_t read_pid;
1289 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), &read_pid, sizeof(read_pid)));
1290 ASSERT_EQ(read_pid, pid);
1291 }
1292 });
1293
1294 start = true;
1295
1296 for (std::thread& thread : threads) {
1297 thread.join();
1298 }
1299}
Narayan Kamathca5e9082017-06-02 15:42:06 +01001300
1301TEST(tombstoned, java_trace_intercept_smoke) {
1302 // Using a "real" PID is a little dangerous here - if the test fails
1303 // or crashes, we might end up getting a bogus / unreliable stack
1304 // trace.
1305 const pid_t self = getpid();
1306
1307 unique_fd intercept_fd, output_fd;
1308 InterceptStatus status;
1309 tombstoned_intercept(self, &intercept_fd, &output_fd, &status, kDebuggerdJavaBacktrace);
1310 ASSERT_EQ(InterceptStatus::kRegistered, status);
1311
Josh Gao76e1e302021-01-26 15:53:11 -08001312 // First connect to tombstoned requesting a native tombstone. This
Narayan Kamathca5e9082017-06-02 15:42:06 +01001313 // should result in a "regular" FD and not the installed intercept.
1314 const char native[] = "native";
1315 unique_fd tombstoned_socket, input_fd;
Josh Gao76e1e302021-01-26 15:53:11 -08001316 ASSERT_TRUE(tombstoned_connect(self, &tombstoned_socket, &input_fd, kDebuggerdTombstone));
Narayan Kamathca5e9082017-06-02 15:42:06 +01001317 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), native, sizeof(native)));
1318 tombstoned_notify_completion(tombstoned_socket.get());
1319
1320 // Then, connect to tombstoned asking for a java backtrace. This *should*
1321 // trigger the intercept.
1322 const char java[] = "java";
1323 ASSERT_TRUE(tombstoned_connect(self, &tombstoned_socket, &input_fd, kDebuggerdJavaBacktrace));
1324 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), java, sizeof(java)));
1325 tombstoned_notify_completion(tombstoned_socket.get());
1326
1327 char outbuf[sizeof(java)];
1328 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), outbuf, sizeof(outbuf)));
1329 ASSERT_STREQ("java", outbuf);
1330}
1331
1332TEST(tombstoned, multiple_intercepts) {
1333 const pid_t fake_pid = 1'234'567;
1334 unique_fd intercept_fd, output_fd;
1335 InterceptStatus status;
1336 tombstoned_intercept(fake_pid, &intercept_fd, &output_fd, &status, kDebuggerdJavaBacktrace);
1337 ASSERT_EQ(InterceptStatus::kRegistered, status);
1338
1339 unique_fd intercept_fd_2, output_fd_2;
1340 tombstoned_intercept(fake_pid, &intercept_fd_2, &output_fd_2, &status, kDebuggerdNativeBacktrace);
1341 ASSERT_EQ(InterceptStatus::kFailedAlreadyRegistered, status);
1342}
1343
1344TEST(tombstoned, intercept_any) {
1345 const pid_t fake_pid = 1'234'567;
1346
1347 unique_fd intercept_fd, output_fd;
1348 InterceptStatus status;
1349 tombstoned_intercept(fake_pid, &intercept_fd, &output_fd, &status, kDebuggerdNativeBacktrace);
1350 ASSERT_EQ(InterceptStatus::kRegistered, status);
1351
1352 const char any[] = "any";
1353 unique_fd tombstoned_socket, input_fd;
1354 ASSERT_TRUE(tombstoned_connect(fake_pid, &tombstoned_socket, &input_fd, kDebuggerdAnyIntercept));
1355 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), any, sizeof(any)));
1356 tombstoned_notify_completion(tombstoned_socket.get());
1357
1358 char outbuf[sizeof(any)];
1359 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), outbuf, sizeof(outbuf)));
1360 ASSERT_STREQ("any", outbuf);
1361}
Josh Gao2b22ae12018-09-12 14:51:03 -07001362
1363TEST(tombstoned, interceptless_backtrace) {
1364 // Generate 50 backtraces, and then check to see that we haven't created 50 new tombstones.
1365 auto get_tombstone_timestamps = []() -> std::map<int, time_t> {
1366 std::map<int, time_t> result;
1367 for (int i = 0; i < 99; ++i) {
1368 std::string path = android::base::StringPrintf("/data/tombstones/tombstone_%02d", i);
1369 struct stat st;
1370 if (stat(path.c_str(), &st) == 0) {
1371 result[i] = st.st_mtim.tv_sec;
1372 }
1373 }
1374 return result;
1375 };
1376
1377 auto before = get_tombstone_timestamps();
1378 for (int i = 0; i < 50; ++i) {
1379 raise_debugger_signal(kDebuggerdNativeBacktrace);
1380 }
1381 auto after = get_tombstone_timestamps();
1382
1383 int diff = 0;
1384 for (int i = 0; i < 99; ++i) {
1385 if (after.count(i) == 0) {
1386 continue;
1387 }
1388 if (before.count(i) == 0) {
1389 ++diff;
1390 continue;
1391 }
1392 if (before[i] != after[i]) {
1393 ++diff;
1394 }
1395 }
1396
1397 // We can't be sure that nothing's crash looping in the background.
1398 // This should be good enough, though...
1399 ASSERT_LT(diff, 10) << "too many new tombstones; is something crashing in the background?";
1400}
Christopher Ferris481e8372019-07-15 17:13:24 -07001401
1402static __attribute__((__noinline__)) void overflow_stack(void* p) {
1403 void* buf[1];
1404 buf[0] = p;
1405 static volatile void* global = buf;
1406 if (global) {
1407 global = buf;
1408 overflow_stack(&buf);
1409 }
1410}
1411
1412TEST_F(CrasherTest, stack_overflow) {
1413 int intercept_result;
1414 unique_fd output_fd;
1415 StartProcess([]() { overflow_stack(nullptr); });
1416
1417 StartIntercept(&output_fd);
1418 FinishCrasher();
1419 AssertDeath(SIGSEGV);
1420 FinishIntercept(&intercept_result);
1421
1422 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1423
1424 std::string result;
1425 ConsumeFd(std::move(output_fd), &result);
1426 ASSERT_MATCH(result, R"(Cause: stack pointer[^\n]*stack overflow.\n)");
1427}
Josh Gao76e1e302021-01-26 15:53:11 -08001428
1429TEST(tombstoned, proto) {
1430 const pid_t self = getpid();
1431 unique_fd tombstoned_socket, text_fd, proto_fd;
1432 ASSERT_TRUE(
1433 tombstoned_connect(self, &tombstoned_socket, &text_fd, &proto_fd, kDebuggerdTombstoneProto));
1434
1435 tombstoned_notify_completion(tombstoned_socket.get());
1436
1437 ASSERT_NE(-1, text_fd.get());
1438 ASSERT_NE(-1, proto_fd.get());
1439
1440 struct stat text_st;
1441 ASSERT_EQ(0, fstat(text_fd.get(), &text_st));
1442
1443 // Give tombstoned some time to link the files into place.
1444 std::this_thread::sleep_for(100ms);
1445
1446 // Find the tombstone.
1447 std::optional<int> tombstone_index;
1448 for (int i = 0; i < 50; ++i) {
1449 std::string path = android::base::StringPrintf("/data/tombstones/tombstone_%02d", i);
1450
1451 struct stat st;
1452 if (TEMP_FAILURE_RETRY(stat(path.c_str(), &st)) != 0) {
1453 continue;
1454 }
1455
1456 if (st.st_dev == text_st.st_dev && st.st_ino == text_st.st_ino) {
1457 tombstone_index = i;
1458 break;
1459 }
1460 }
1461
1462 ASSERT_TRUE(tombstone_index);
1463 std::string proto_path =
1464 android::base::StringPrintf("/data/tombstones/tombstone_%02d.pb", *tombstone_index);
1465
1466 struct stat proto_fd_st;
1467 struct stat proto_file_st;
1468 ASSERT_EQ(0, fstat(proto_fd.get(), &proto_fd_st));
1469 ASSERT_EQ(0, stat(proto_path.c_str(), &proto_file_st));
1470
1471 ASSERT_EQ(proto_fd_st.st_dev, proto_file_st.st_dev);
1472 ASSERT_EQ(proto_fd_st.st_ino, proto_file_st.st_ino);
1473}
1474
1475TEST(tombstoned, proto_intercept) {
1476 const pid_t self = getpid();
1477 unique_fd intercept_fd, output_fd;
1478 InterceptStatus status;
1479
1480 tombstoned_intercept(self, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
1481 ASSERT_EQ(InterceptStatus::kRegistered, status);
1482
1483 unique_fd tombstoned_socket, text_fd, proto_fd;
1484 ASSERT_TRUE(
1485 tombstoned_connect(self, &tombstoned_socket, &text_fd, &proto_fd, kDebuggerdTombstoneProto));
1486 ASSERT_TRUE(android::base::WriteStringToFd("foo", text_fd.get()));
1487 tombstoned_notify_completion(tombstoned_socket.get());
1488
1489 text_fd.reset();
1490
1491 std::string output;
1492 ASSERT_TRUE(android::base::ReadFdToString(output_fd, &output));
1493 ASSERT_EQ("foo", output);
1494}