blob: 193bf6b7cd74519a092963213a5db719be4d105b [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
Christopher Ferris35da2882021-02-17 15:39:06 -080017#include <dirent.h>
Josh Gaocbe70cb2016-10-18 18:17:52 -070018#include <err.h>
19#include <fcntl.h>
Elliott Hughes03b283a2021-01-15 11:34:26 -080020#include <malloc.h>
Josh Gaocdea7502017-11-01 15:00:40 -070021#include <stdlib.h>
Josh Gao502cfd22017-02-17 01:39:15 -080022#include <sys/capability.h>
Peter Collingbournefe8997a2020-07-20 15:08:52 -070023#include <sys/mman.h>
Josh Gaofca7ca32017-01-23 12:05:35 -080024#include <sys/prctl.h>
Josh Gaofd13bf02017-08-18 15:37:26 -070025#include <sys/ptrace.h>
Josh Gao70adac62018-02-22 11:38:33 -080026#include <sys/resource.h>
Dan Albertc38057a2017-10-11 11:35:40 -070027#include <sys/syscall.h>
Josh Gaocbe70cb2016-10-18 18:17:52 -070028#include <sys/types.h>
Josh Gaofd13bf02017-08-18 15:37:26 -070029#include <unistd.h>
Josh Gaocbe70cb2016-10-18 18:17:52 -070030
31#include <chrono>
32#include <regex>
33#include <thread>
34
Josh Gaobf06a402018-08-27 16:34:01 -070035#include <android/fdsan.h>
Josh Gao502cfd22017-02-17 01:39:15 -080036#include <android/set_abort_message.h>
Mitch Phillips7168a212021-03-09 16:53:23 -080037#include <bionic/malloc.h>
Peter Collingbournef8622522020-04-07 14:07:32 -070038#include <bionic/mte.h>
Josh Gaoa48b41b2019-12-13 14:11:04 -080039#include <bionic/reserved_signals.h>
Josh Gao502cfd22017-02-17 01:39:15 -080040
Josh Gao5f87bbd2019-01-09 17:01:49 -080041#include <android-base/cmsg.h>
Josh Gaocbe70cb2016-10-18 18:17:52 -070042#include <android-base/file.h>
43#include <android-base/logging.h>
Josh Gao2e7b8e22017-05-04 17:12:57 -070044#include <android-base/macros.h>
Josh Gaocbe70cb2016-10-18 18:17:52 -070045#include <android-base/parseint.h>
46#include <android-base/properties.h>
Josh Gao2b22ae12018-09-12 14:51:03 -070047#include <android-base/stringprintf.h>
Josh Gaocbe70cb2016-10-18 18:17:52 -070048#include <android-base/strings.h>
Josh Gao30171a82017-04-27 19:48:44 -070049#include <android-base/test_utils.h>
Josh Gaocbe70cb2016-10-18 18:17:52 -070050#include <android-base/unique_fd.h>
51#include <cutils/sockets.h>
Josh Gaocbe70cb2016-10-18 18:17:52 -070052#include <gtest/gtest.h>
53
Josh Gaoe04ca272018-01-16 15:38:17 -080054#include <libminijail.h>
55#include <scoped_minijail.h>
56
Narayan Kamath2d377cd2017-05-10 10:58:59 +010057#include "debuggerd/handler.h"
58#include "protocol.h"
59#include "tombstoned/tombstoned.h"
60#include "util.h"
61
Josh Gaocbe70cb2016-10-18 18:17:52 -070062using namespace std::chrono_literals;
Josh Gao5f87bbd2019-01-09 17:01:49 -080063
64using android::base::SendFileDescriptors;
Josh Gaocbe70cb2016-10-18 18:17:52 -070065using android::base::unique_fd;
66
67#if defined(__LP64__)
Josh Gaocbe70cb2016-10-18 18:17:52 -070068#define ARCH_SUFFIX "64"
69#else
Josh Gaocbe70cb2016-10-18 18:17:52 -070070#define ARCH_SUFFIX ""
71#endif
72
Elliott Hughese4781d52021-03-17 09:15:15 -070073constexpr char kWaitForDebuggerKey[] = "debug.debuggerd.wait_for_debugger";
Josh Gaocbe70cb2016-10-18 18:17:52 -070074
75#define TIMEOUT(seconds, expr) \
76 [&]() { \
77 struct sigaction old_sigaction; \
78 struct sigaction new_sigaction = {}; \
79 new_sigaction.sa_handler = [](int) {}; \
80 if (sigaction(SIGALRM, &new_sigaction, &new_sigaction) != 0) { \
81 err(1, "sigaction failed"); \
82 } \
83 alarm(seconds); \
84 auto value = expr; \
85 int saved_errno = errno; \
86 if (sigaction(SIGALRM, &old_sigaction, nullptr) != 0) { \
87 err(1, "sigaction failed"); \
88 } \
89 alarm(0); \
90 errno = saved_errno; \
91 return value; \
92 }()
93
Chih-Hung Hsieh3249b3a2018-05-11 16:01:21 -070094// Backtrace frame dump could contain:
95// #01 pc 0001cded /data/tmp/debuggerd_test32 (raise_debugger_signal+80)
96// or
97// #01 pc 00022a09 /data/tmp/debuggerd_test32 (offset 0x12000) (raise_debugger_signal+80)
Josh Gaoe04ca272018-01-16 15:38:17 -080098#define ASSERT_BACKTRACE_FRAME(result, frame_name) \
Chih-Hung Hsieh3249b3a2018-05-11 16:01:21 -070099 ASSERT_MATCH(result, \
100 R"(#\d\d pc [0-9a-f]+\s+ \S+ (\(offset 0x[0-9a-f]+\) )?\()" frame_name R"(\+)");
Jaesung Chung58778e12017-06-15 18:20:34 +0900101
Mitch Phillips7168a212021-03-09 16:53:23 -0800102// Enable GWP-ASan at the start of this process. GWP-ASan is enabled using
103// process sampling, so we need to ensure we force GWP-ASan on.
104__attribute__((constructor)) static void enable_gwp_asan() {
105 bool force = true;
106 android_mallopt(M_INITIALIZE_GWP_ASAN, &force, sizeof(force));
107}
108
Narayan Kamatha73df602017-05-24 15:07:25 +0100109static void tombstoned_intercept(pid_t target_pid, unique_fd* intercept_fd, unique_fd* output_fd,
Narayan Kamathca5e9082017-06-02 15:42:06 +0100110 InterceptStatus* status, DebuggerdDumpType intercept_type) {
Josh Gao460b3362017-03-30 16:40:47 -0700111 intercept_fd->reset(socket_local_client(kTombstonedInterceptSocketName,
112 ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_SEQPACKET));
113 if (intercept_fd->get() == -1) {
114 FAIL() << "failed to contact tombstoned: " << strerror(errno);
115 }
116
Nick Desaulniers67d52aa2019-10-07 23:28:15 -0700117 InterceptRequest req = {
118 .dump_type = intercept_type,
119 .pid = target_pid,
120 };
Josh Gao460b3362017-03-30 16:40:47 -0700121
122 unique_fd output_pipe_write;
123 if (!Pipe(output_fd, &output_pipe_write)) {
124 FAIL() << "failed to create output pipe: " << strerror(errno);
125 }
126
127 std::string pipe_size_str;
128 int pipe_buffer_size;
129 if (!android::base::ReadFileToString("/proc/sys/fs/pipe-max-size", &pipe_size_str)) {
130 FAIL() << "failed to read /proc/sys/fs/pipe-max-size: " << strerror(errno);
131 }
132
133 pipe_size_str = android::base::Trim(pipe_size_str);
134
135 if (!android::base::ParseInt(pipe_size_str.c_str(), &pipe_buffer_size, 0)) {
136 FAIL() << "failed to parse pipe max size";
137 }
138
139 if (fcntl(output_fd->get(), F_SETPIPE_SZ, pipe_buffer_size) != pipe_buffer_size) {
140 FAIL() << "failed to set pipe size: " << strerror(errno);
141 }
142
Josh Gao5675f3c2017-06-01 12:19:53 -0700143 ASSERT_GE(pipe_buffer_size, 1024 * 1024);
144
Josh Gao5f87bbd2019-01-09 17:01:49 -0800145 ssize_t rc = SendFileDescriptors(intercept_fd->get(), &req, sizeof(req), output_pipe_write.get());
146 output_pipe_write.reset();
147 if (rc != sizeof(req)) {
Josh Gao460b3362017-03-30 16:40:47 -0700148 FAIL() << "failed to send output fd to tombstoned: " << strerror(errno);
149 }
150
151 InterceptResponse response;
Josh Gao5f87bbd2019-01-09 17:01:49 -0800152 rc = TEMP_FAILURE_RETRY(read(intercept_fd->get(), &response, sizeof(response)));
Josh Gao460b3362017-03-30 16:40:47 -0700153 if (rc == -1) {
154 FAIL() << "failed to read response from tombstoned: " << strerror(errno);
155 } else if (rc == 0) {
156 FAIL() << "failed to read response from tombstoned (EOF)";
157 } else if (rc != sizeof(response)) {
158 FAIL() << "received packet of unexpected length from tombstoned: expected " << sizeof(response)
159 << ", received " << rc;
160 }
161
Narayan Kamathca5e9082017-06-02 15:42:06 +0100162 *status = response.status;
Josh Gao460b3362017-03-30 16:40:47 -0700163}
164
Josh Gaocbe70cb2016-10-18 18:17:52 -0700165class CrasherTest : public ::testing::Test {
166 public:
167 pid_t crasher_pid = -1;
Elliott Hughese4781d52021-03-17 09:15:15 -0700168 bool previous_wait_for_debugger;
Josh Gaocbe70cb2016-10-18 18:17:52 -0700169 unique_fd crasher_pipe;
170 unique_fd intercept_fd;
171
172 CrasherTest();
173 ~CrasherTest();
174
Narayan Kamatha73df602017-05-24 15:07:25 +0100175 void StartIntercept(unique_fd* output_fd, DebuggerdDumpType intercept_type = kDebuggerdTombstone);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700176
177 // Returns -1 if we fail to read a response from tombstoned, otherwise the received return code.
178 void FinishIntercept(int* result);
179
Josh Gao2e7b8e22017-05-04 17:12:57 -0700180 void StartProcess(std::function<void()> function, std::function<pid_t()> forker = fork);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700181 void StartCrasher(const std::string& crash_type);
182 void FinishCrasher();
183 void AssertDeath(int signo);
Peter Collingbourne10e428d2020-07-17 14:49:31 -0700184
185 static void Trap(void* ptr);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700186};
187
188CrasherTest::CrasherTest() {
Elliott Hughese4781d52021-03-17 09:15:15 -0700189 previous_wait_for_debugger = android::base::GetBoolProperty(kWaitForDebuggerKey, false);
190 android::base::SetProperty(kWaitForDebuggerKey, "0");
191
192 // Clear the old property too, just in case someone's been using it
193 // on this device. (We only document the new name, but we still support
194 // the old name so we don't break anyone's existing setups.)
195 android::base::SetProperty("debug.debuggerd.wait_for_gdb", "0");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700196}
197
198CrasherTest::~CrasherTest() {
199 if (crasher_pid != -1) {
200 kill(crasher_pid, SIGKILL);
201 int status;
Christopher Ferris172b0a02019-09-18 17:48:30 -0700202 TEMP_FAILURE_RETRY(waitpid(crasher_pid, &status, WUNTRACED));
Josh Gaocbe70cb2016-10-18 18:17:52 -0700203 }
204
Elliott Hughese4781d52021-03-17 09:15:15 -0700205 android::base::SetProperty(kWaitForDebuggerKey, previous_wait_for_debugger ? "1" : "0");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700206}
207
Narayan Kamatha73df602017-05-24 15:07:25 +0100208void CrasherTest::StartIntercept(unique_fd* output_fd, DebuggerdDumpType intercept_type) {
Josh Gaocbe70cb2016-10-18 18:17:52 -0700209 if (crasher_pid == -1) {
210 FAIL() << "crasher hasn't been started";
211 }
212
Narayan Kamathca5e9082017-06-02 15:42:06 +0100213 InterceptStatus status;
214 tombstoned_intercept(crasher_pid, &this->intercept_fd, output_fd, &status, intercept_type);
215 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700216}
217
218void CrasherTest::FinishIntercept(int* result) {
219 InterceptResponse response;
220
Christopher Ferris11555f02019-09-20 14:18:55 -0700221 ssize_t rc = TIMEOUT(30, read(intercept_fd.get(), &response, sizeof(response)));
Josh Gaocbe70cb2016-10-18 18:17:52 -0700222 if (rc == -1) {
223 FAIL() << "failed to read response from tombstoned: " << strerror(errno);
224 } else if (rc == 0) {
225 *result = -1;
226 } else if (rc != sizeof(response)) {
227 FAIL() << "received packet of unexpected length from tombstoned: expected " << sizeof(response)
228 << ", received " << rc;
229 } else {
Josh Gao460b3362017-03-30 16:40:47 -0700230 *result = response.status == InterceptStatus::kStarted ? 1 : 0;
Josh Gaocbe70cb2016-10-18 18:17:52 -0700231 }
232}
233
Josh Gao2e7b8e22017-05-04 17:12:57 -0700234void CrasherTest::StartProcess(std::function<void()> function, std::function<pid_t()> forker) {
Josh Gaofca7ca32017-01-23 12:05:35 -0800235 unique_fd read_pipe;
Josh Gaocbe70cb2016-10-18 18:17:52 -0700236 unique_fd crasher_read_pipe;
237 if (!Pipe(&crasher_read_pipe, &crasher_pipe)) {
238 FAIL() << "failed to create pipe: " << strerror(errno);
239 }
240
Josh Gao2e7b8e22017-05-04 17:12:57 -0700241 crasher_pid = forker();
Josh Gaocbe70cb2016-10-18 18:17:52 -0700242 if (crasher_pid == -1) {
243 FAIL() << "fork failed: " << strerror(errno);
244 } else if (crasher_pid == 0) {
Josh Gao502cfd22017-02-17 01:39:15 -0800245 char dummy;
246 crasher_pipe.reset();
247 TEMP_FAILURE_RETRY(read(crasher_read_pipe.get(), &dummy, 1));
Josh Gaofca7ca32017-01-23 12:05:35 -0800248 function();
249 _exit(0);
250 }
251}
252
Josh Gaocbe70cb2016-10-18 18:17:52 -0700253void CrasherTest::FinishCrasher() {
254 if (crasher_pipe == -1) {
255 FAIL() << "crasher pipe uninitialized";
256 }
257
Christopher Ferris172b0a02019-09-18 17:48:30 -0700258 ssize_t rc = TEMP_FAILURE_RETRY(write(crasher_pipe.get(), "\n", 1));
Josh Gaocbe70cb2016-10-18 18:17:52 -0700259 if (rc == -1) {
260 FAIL() << "failed to write to crasher pipe: " << strerror(errno);
261 } else if (rc == 0) {
262 FAIL() << "crasher pipe was closed";
263 }
264}
265
266void CrasherTest::AssertDeath(int signo) {
267 int status;
Christopher Ferris11555f02019-09-20 14:18:55 -0700268 pid_t pid = TIMEOUT(30, waitpid(crasher_pid, &status, 0));
Josh Gaocbe70cb2016-10-18 18:17:52 -0700269 if (pid != crasher_pid) {
Christopher Ferrisafc0ff72019-06-26 15:08:51 -0700270 printf("failed to wait for crasher (expected pid %d, return value %d): %s\n", crasher_pid, pid,
271 strerror(errno));
Josh Gao2b2ae0c2017-08-21 14:31:17 -0700272 sleep(100);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700273 FAIL() << "failed to wait for crasher: " << strerror(errno);
274 }
275
Josh Gaoe06f2a42017-04-27 16:50:38 -0700276 if (signo == 0) {
277 ASSERT_TRUE(WIFEXITED(status));
278 ASSERT_EQ(0, WEXITSTATUS(signo));
279 } else {
280 ASSERT_FALSE(WIFEXITED(status));
281 ASSERT_TRUE(WIFSIGNALED(status)) << "crasher didn't terminate via a signal";
282 ASSERT_EQ(signo, WTERMSIG(status));
Josh Gaocbe70cb2016-10-18 18:17:52 -0700283 }
Josh Gaocbe70cb2016-10-18 18:17:52 -0700284 crasher_pid = -1;
285}
286
287static void ConsumeFd(unique_fd fd, std::string* output) {
288 constexpr size_t read_length = PAGE_SIZE;
289 std::string result;
290
291 while (true) {
292 size_t offset = result.size();
293 result.resize(result.size() + PAGE_SIZE);
294 ssize_t rc = TEMP_FAILURE_RETRY(read(fd.get(), &result[offset], read_length));
295 if (rc == -1) {
296 FAIL() << "read failed: " << strerror(errno);
297 } else if (rc == 0) {
298 result.resize(result.size() - PAGE_SIZE);
299 break;
300 }
301
302 result.resize(result.size() - PAGE_SIZE + rc);
303 }
304
305 *output = std::move(result);
306}
307
308TEST_F(CrasherTest, smoke) {
309 int intercept_result;
310 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800311 StartProcess([]() {
312 *reinterpret_cast<volatile char*>(0xdead) = '1';
313 });
314
Josh Gaocbe70cb2016-10-18 18:17:52 -0700315 StartIntercept(&output_fd);
316 FinishCrasher();
317 AssertDeath(SIGSEGV);
318 FinishIntercept(&intercept_result);
319
320 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
321
322 std::string result;
323 ConsumeFd(std::move(output_fd), &result);
324 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\), code 1 \(SEGV_MAPERR\), fault addr 0xdead)");
Peter Collingbourne864f15d2020-09-14 20:27:36 -0700325
326 if (mte_supported()) {
327 // Test that the default TAGGED_ADDR_CTRL value is set.
Peter Collingbourne939d0742021-02-02 19:00:45 -0800328 ASSERT_MATCH(result, R"(tagged_addr_ctrl: 000000000007fff3)");
Peter Collingbourne864f15d2020-09-14 20:27:36 -0700329 }
Josh Gaocbe70cb2016-10-18 18:17:52 -0700330}
331
Peter Collingbournef03af882020-03-20 18:09:00 -0700332TEST_F(CrasherTest, tagged_fault_addr) {
333#if !defined(__aarch64__)
334 GTEST_SKIP() << "Requires aarch64";
335#endif
336 int intercept_result;
337 unique_fd output_fd;
338 StartProcess([]() {
339 *reinterpret_cast<volatile char*>(0x100000000000dead) = '1';
340 });
341
342 StartIntercept(&output_fd);
343 FinishCrasher();
344 AssertDeath(SIGSEGV);
345 FinishIntercept(&intercept_result);
346
347 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
348
349 std::string result;
350 ConsumeFd(std::move(output_fd), &result);
351
352 // The address can either be tagged (new kernels) or untagged (old kernels).
353 ASSERT_MATCH(
354 result,
355 R"(signal 11 \(SIGSEGV\), code 1 \(SEGV_MAPERR\), fault addr (0x100000000000dead|0xdead))");
356}
357
Peter Collingbourne10e428d2020-07-17 14:49:31 -0700358// Marked as weak to prevent the compiler from removing the malloc in the caller. In theory, the
359// compiler could still clobber the argument register before trapping, but that's unlikely.
360__attribute__((weak)) void CrasherTest::Trap(void* ptr ATTRIBUTE_UNUSED) {
361 __builtin_trap();
362}
363
364TEST_F(CrasherTest, heap_addr_in_register) {
365#if defined(__i386__)
366 GTEST_SKIP() << "architecture does not pass arguments in registers";
367#endif
368 int intercept_result;
369 unique_fd output_fd;
370 StartProcess([]() {
371 // Crash with a heap pointer in the first argument register.
372 Trap(malloc(1));
373 });
374
375 StartIntercept(&output_fd);
376 FinishCrasher();
377 int status;
378 ASSERT_EQ(crasher_pid, TIMEOUT(30, waitpid(crasher_pid, &status, 0)));
379 ASSERT_TRUE(WIFSIGNALED(status)) << "crasher didn't terminate via a signal";
380 // Don't test the signal number because different architectures use different signals for
381 // __builtin_trap().
382 FinishIntercept(&intercept_result);
383
384 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
385
386 std::string result;
387 ConsumeFd(std::move(output_fd), &result);
388
389#if defined(__aarch64__)
Peter Collingbourne0ea08c22021-02-05 14:59:08 -0800390 ASSERT_MATCH(result, "memory near x0 \\(\\[anon:");
Peter Collingbourne10e428d2020-07-17 14:49:31 -0700391#elif defined(__arm__)
Peter Collingbourne0ea08c22021-02-05 14:59:08 -0800392 ASSERT_MATCH(result, "memory near r0 \\(\\[anon:");
Peter Collingbourne10e428d2020-07-17 14:49:31 -0700393#elif defined(__x86_64__)
Peter Collingbourne0ea08c22021-02-05 14:59:08 -0800394 ASSERT_MATCH(result, "memory near rdi \\(\\[anon:");
Peter Collingbourne10e428d2020-07-17 14:49:31 -0700395#else
396 ASSERT_TRUE(false) << "unsupported architecture";
397#endif
398}
399
Peter Collingbournecd278072020-12-21 14:08:38 -0800400#if defined(__aarch64__)
Peter Collingbournef8622522020-04-07 14:07:32 -0700401static void SetTagCheckingLevelSync() {
Elliott Hughes03b283a2021-01-15 11:34:26 -0800402 if (mallopt(M_BIONIC_SET_HEAP_TAGGING_LEVEL, M_HEAP_TAGGING_LEVEL_SYNC) == 0) {
Peter Collingbournef8622522020-04-07 14:07:32 -0700403 abort();
404 }
405}
406#endif
407
Mitch Phillips7168a212021-03-09 16:53:23 -0800408// Number of iterations required to reliably guarantee a GWP-ASan crash.
409// GWP-ASan's sample rate is not truly nondeterministic, it initialises a
410// thread-local counter at 2*SampleRate, and decrements on each malloc(). Once
411// the counter reaches zero, we provide a sampled allocation. Then, double that
412// figure to allow for left/right allocation alignment, as this is done randomly
413// without bias.
414#define GWP_ASAN_ITERATIONS_TO_ENSURE_CRASH (0x20000)
415
416struct GwpAsanTestParameters {
417 size_t alloc_size;
418 bool free_before_access;
419 int access_offset;
420 std::string cause_needle; // Needle to be found in the "Cause: [GWP-ASan]" line.
421};
422
423struct GwpAsanCrasherTest : CrasherTest, testing::WithParamInterface<GwpAsanTestParameters> {};
424
425GwpAsanTestParameters gwp_asan_tests[] = {
426 {/* alloc_size */ 7, /* free_before_access */ true, /* access_offset */ 0, "Use After Free, 0 bytes into a 7-byte allocation"},
427 {/* alloc_size */ 7, /* free_before_access */ true, /* access_offset */ 1, "Use After Free, 1 byte into a 7-byte allocation"},
428 {/* alloc_size */ 7, /* free_before_access */ false, /* access_offset */ 16, "Buffer Overflow, 9 bytes right of a 7-byte allocation"},
429 {/* alloc_size */ 16, /* free_before_access */ false, /* access_offset */ -1, "Buffer Underflow, 1 byte left of a 16-byte allocation"},
430};
431
432INSTANTIATE_TEST_SUITE_P(GwpAsanTests, GwpAsanCrasherTest, testing::ValuesIn(gwp_asan_tests));
433
434TEST_P(GwpAsanCrasherTest, gwp_asan_uaf) {
435 if (mte_supported()) {
436 // Skip this test on MTE hardware, as MTE will reliably catch these errors
437 // instead of GWP-ASan.
438 GTEST_SKIP() << "Skipped on MTE.";
439 }
440
441 GwpAsanTestParameters params = GetParam();
442
443 int intercept_result;
444 unique_fd output_fd;
445 StartProcess([&params]() {
446 for (unsigned i = 0; i < GWP_ASAN_ITERATIONS_TO_ENSURE_CRASH; ++i) {
447 volatile char* p = reinterpret_cast<volatile char*>(malloc(params.alloc_size));
448 if (params.free_before_access) free(static_cast<void*>(const_cast<char*>(p)));
449 p[params.access_offset] = 42;
450 if (!params.free_before_access) free(static_cast<void*>(const_cast<char*>(p)));
451 }
452 });
453
454 StartIntercept(&output_fd);
455 FinishCrasher();
456 AssertDeath(SIGSEGV);
457 FinishIntercept(&intercept_result);
458
459 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
460
461 std::string result;
462 ConsumeFd(std::move(output_fd), &result);
463
464 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\), code 2 \(SEGV_ACCERR\))");
465 ASSERT_MATCH(result, R"(Cause: \[GWP-ASan\]: )" + params.cause_needle);
466 if (params.free_before_access) {
467 ASSERT_MATCH(result, R"(deallocated by thread .*
468 #00 pc)");
469 }
470 ASSERT_MATCH(result, R"(allocated by thread .*
471 #00 pc)");
472}
473
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800474struct SizeParamCrasherTest : CrasherTest, testing::WithParamInterface<size_t> {};
475
476INSTANTIATE_TEST_SUITE_P(Sizes, SizeParamCrasherTest, testing::Values(16, 131072));
477
478TEST_P(SizeParamCrasherTest, mte_uaf) {
Peter Collingbournecd278072020-12-21 14:08:38 -0800479#if defined(__aarch64__)
Peter Collingbournef8622522020-04-07 14:07:32 -0700480 if (!mte_supported()) {
481 GTEST_SKIP() << "Requires MTE";
482 }
483
484 int intercept_result;
485 unique_fd output_fd;
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800486 StartProcess([&]() {
Peter Collingbournef8622522020-04-07 14:07:32 -0700487 SetTagCheckingLevelSync();
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800488 volatile int* p = (volatile int*)malloc(GetParam());
Peter Collingbournef8622522020-04-07 14:07:32 -0700489 free((void *)p);
490 p[0] = 42;
491 });
492
493 StartIntercept(&output_fd);
494 FinishCrasher();
495 AssertDeath(SIGSEGV);
496 FinishIntercept(&intercept_result);
497
498 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
499
500 std::string result;
501 ConsumeFd(std::move(output_fd), &result);
502
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800503 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\))");
504 ASSERT_MATCH(result, R"(Cause: \[MTE\]: Use After Free, 0 bytes into a )" +
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800505 std::to_string(GetParam()) + R"(-byte allocation)");
Peter Collingbournebbe69052020-05-08 10:11:19 -0700506 ASSERT_MATCH(result, R"(deallocated by thread .*
507 #00 pc)");
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800508 ASSERT_MATCH(result, R"(allocated by thread .*
509 #00 pc)");
Peter Collingbournef8622522020-04-07 14:07:32 -0700510#else
Peter Collingbournecd278072020-12-21 14:08:38 -0800511 GTEST_SKIP() << "Requires aarch64";
Peter Collingbournef8622522020-04-07 14:07:32 -0700512#endif
513}
514
Peter Collingbournedc476342021-05-12 15:56:43 -0700515TEST_P(SizeParamCrasherTest, mte_oob_uaf) {
516#if defined(__aarch64__)
517 if (!mte_supported()) {
518 GTEST_SKIP() << "Requires MTE";
519 }
520
521 int intercept_result;
522 unique_fd output_fd;
523 StartProcess([&]() {
524 SetTagCheckingLevelSync();
525 volatile int* p = (volatile int*)malloc(GetParam());
526 free((void *)p);
527 p[-1] = 42;
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_NOT_MATCH(result, R"(Cause: \[MTE\]: Use After Free, 4 bytes left)");
542#else
543 GTEST_SKIP() << "Requires aarch64";
544#endif
545}
546
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800547TEST_P(SizeParamCrasherTest, mte_overflow) {
Peter Collingbournecd278072020-12-21 14:08:38 -0800548#if defined(__aarch64__)
Peter Collingbournef8622522020-04-07 14:07:32 -0700549 if (!mte_supported()) {
550 GTEST_SKIP() << "Requires MTE";
551 }
552
553 int intercept_result;
554 unique_fd output_fd;
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800555 StartProcess([&]() {
Peter Collingbournef8622522020-04-07 14:07:32 -0700556 SetTagCheckingLevelSync();
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800557 volatile char* p = (volatile char*)malloc(GetParam());
558 p[GetParam()] = 42;
Peter Collingbournef8622522020-04-07 14:07:32 -0700559 });
560
561 StartIntercept(&output_fd);
562 FinishCrasher();
563 AssertDeath(SIGSEGV);
564 FinishIntercept(&intercept_result);
565
566 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
567
568 std::string result;
569 ConsumeFd(std::move(output_fd), &result);
570
571 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\))");
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800572 ASSERT_MATCH(result, R"(Cause: \[MTE\]: Buffer Overflow, 0 bytes right of a )" +
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800573 std::to_string(GetParam()) + R"(-byte allocation)");
574 ASSERT_MATCH(result, R"(allocated by thread .*
Peter Collingbournebbe69052020-05-08 10:11:19 -0700575 #00 pc)");
Peter Collingbournef8622522020-04-07 14:07:32 -0700576#else
Peter Collingbournecd278072020-12-21 14:08:38 -0800577 GTEST_SKIP() << "Requires aarch64";
Peter Collingbournef8622522020-04-07 14:07:32 -0700578#endif
579}
580
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800581TEST_P(SizeParamCrasherTest, mte_underflow) {
Peter Collingbournecd278072020-12-21 14:08:38 -0800582#if defined(__aarch64__)
Peter Collingbournef8622522020-04-07 14:07:32 -0700583 if (!mte_supported()) {
584 GTEST_SKIP() << "Requires MTE";
585 }
586
587 int intercept_result;
588 unique_fd output_fd;
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800589 StartProcess([&]() {
Peter Collingbournef8622522020-04-07 14:07:32 -0700590 SetTagCheckingLevelSync();
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800591 volatile int* p = (volatile int*)malloc(GetParam());
Peter Collingbournef8622522020-04-07 14:07:32 -0700592 p[-1] = 42;
593 });
594
595 StartIntercept(&output_fd);
596 FinishCrasher();
597 AssertDeath(SIGSEGV);
598 FinishIntercept(&intercept_result);
599
600 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
601
602 std::string result;
603 ConsumeFd(std::move(output_fd), &result);
604
605 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\), code 9 \(SEGV_MTESERR\))");
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800606 ASSERT_MATCH(result, R"(Cause: \[MTE\]: Buffer Underflow, 4 bytes left of a )" +
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800607 std::to_string(GetParam()) + R"(-byte allocation)");
608 ASSERT_MATCH(result, R"(allocated by thread .*
Peter Collingbournebbe69052020-05-08 10:11:19 -0700609 #00 pc)");
Peter Collingbournef8622522020-04-07 14:07:32 -0700610#else
Peter Collingbournecd278072020-12-21 14:08:38 -0800611 GTEST_SKIP() << "Requires aarch64";
Peter Collingbournef8622522020-04-07 14:07:32 -0700612#endif
613}
614
615TEST_F(CrasherTest, mte_multiple_causes) {
Peter Collingbournecd278072020-12-21 14:08:38 -0800616#if defined(__aarch64__)
Peter Collingbournef8622522020-04-07 14:07:32 -0700617 if (!mte_supported()) {
618 GTEST_SKIP() << "Requires MTE";
619 }
620
621 int intercept_result;
622 unique_fd output_fd;
623 StartProcess([]() {
624 SetTagCheckingLevelSync();
625
626 // Make two allocations with the same tag and close to one another. Check for both properties
627 // with a bounds check -- this relies on the fact that only if the allocations have the same tag
628 // would they be measured as closer than 128 bytes to each other. Otherwise they would be about
629 // (some non-zero value << 56) apart.
630 //
631 // The out-of-bounds access will be considered either an overflow of one or an underflow of the
632 // other.
633 std::set<uintptr_t> allocs;
634 for (int i = 0; i != 4096; ++i) {
635 uintptr_t alloc = reinterpret_cast<uintptr_t>(malloc(16));
636 auto it = allocs.insert(alloc).first;
637 if (it != allocs.begin() && *std::prev(it) + 128 > alloc) {
638 *reinterpret_cast<int*>(*std::prev(it) + 16) = 42;
639 }
640 if (std::next(it) != allocs.end() && alloc + 128 > *std::next(it)) {
641 *reinterpret_cast<int*>(alloc + 16) = 42;
642 }
643 }
644 });
645
646 StartIntercept(&output_fd);
647 FinishCrasher();
648 AssertDeath(SIGSEGV);
649 FinishIntercept(&intercept_result);
650
651 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
652
653 std::string result;
654 ConsumeFd(std::move(output_fd), &result);
655
656 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\))");
657 ASSERT_MATCH(
658 result,
659 R"(Note: multiple potential causes for this crash were detected, listing them in decreasing order of probability.)");
660
661 // Adjacent untracked allocations may cause us to see the wrong underflow here (or only
662 // overflows), so we can't match explicitly for an underflow message.
663 ASSERT_MATCH(result, R"(Cause: \[MTE\]: Buffer Overflow, 0 bytes right of a 16-byte allocation)");
664#else
Peter Collingbournecd278072020-12-21 14:08:38 -0800665 GTEST_SKIP() << "Requires aarch64";
Peter Collingbournef8622522020-04-07 14:07:32 -0700666#endif
667}
668
Peter Collingbournecd278072020-12-21 14:08:38 -0800669#if defined(__aarch64__)
Peter Collingbournefe8997a2020-07-20 15:08:52 -0700670static uintptr_t CreateTagMapping() {
671 uintptr_t mapping =
672 reinterpret_cast<uintptr_t>(mmap(nullptr, getpagesize(), PROT_READ | PROT_WRITE | PROT_MTE,
673 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0));
674 if (reinterpret_cast<void*>(mapping) == MAP_FAILED) {
675 return 0;
676 }
677 __asm__ __volatile__(".arch_extension mte; stg %0, [%0]"
678 :
679 : "r"(mapping + (1ULL << 56))
680 : "memory");
681 return mapping;
682}
683#endif
684
685TEST_F(CrasherTest, mte_tag_dump) {
Peter Collingbournecd278072020-12-21 14:08:38 -0800686#if defined(__aarch64__)
Peter Collingbournefe8997a2020-07-20 15:08:52 -0700687 if (!mte_supported()) {
688 GTEST_SKIP() << "Requires MTE";
689 }
690
691 int intercept_result;
692 unique_fd output_fd;
693 StartProcess([&]() {
694 SetTagCheckingLevelSync();
695 Trap(reinterpret_cast<void *>(CreateTagMapping()));
696 });
697
698 StartIntercept(&output_fd);
699 FinishCrasher();
700 AssertDeath(SIGTRAP);
701 FinishIntercept(&intercept_result);
702
703 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
704
705 std::string result;
706 ConsumeFd(std::move(output_fd), &result);
707
708 ASSERT_MATCH(result, R"(memory near x0:
709.*
710.*
711 01.............0 0000000000000000 0000000000000000 ................
712 00.............0)");
713#else
Peter Collingbournecd278072020-12-21 14:08:38 -0800714 GTEST_SKIP() << "Requires aarch64";
Peter Collingbournefe8997a2020-07-20 15:08:52 -0700715#endif
716}
717
Josh Gaocdea7502017-11-01 15:00:40 -0700718TEST_F(CrasherTest, LD_PRELOAD) {
719 int intercept_result;
720 unique_fd output_fd;
721 StartProcess([]() {
722 setenv("LD_PRELOAD", "nonexistent.so", 1);
723 *reinterpret_cast<volatile char*>(0xdead) = '1';
724 });
725
726 StartIntercept(&output_fd);
727 FinishCrasher();
728 AssertDeath(SIGSEGV);
729 FinishIntercept(&intercept_result);
730
731 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
732
733 std::string result;
734 ConsumeFd(std::move(output_fd), &result);
735 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\), code 1 \(SEGV_MAPERR\), fault addr 0xdead)");
736}
737
Josh Gaocbe70cb2016-10-18 18:17:52 -0700738TEST_F(CrasherTest, abort) {
739 int intercept_result;
740 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800741 StartProcess([]() {
742 abort();
743 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700744 StartIntercept(&output_fd);
745 FinishCrasher();
746 AssertDeath(SIGABRT);
747 FinishIntercept(&intercept_result);
748
749 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
750
751 std::string result;
752 ConsumeFd(std::move(output_fd), &result);
Andreas Gampe26cbafb2017-06-22 20:14:43 -0700753 ASSERT_BACKTRACE_FRAME(result, "abort");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700754}
755
756TEST_F(CrasherTest, signal) {
757 int intercept_result;
758 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800759 StartProcess([]() {
Josh Gao2b2ae0c2017-08-21 14:31:17 -0700760 while (true) {
761 sleep(1);
762 }
Josh Gao502cfd22017-02-17 01:39:15 -0800763 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700764 StartIntercept(&output_fd);
Josh Gao2b2ae0c2017-08-21 14:31:17 -0700765 FinishCrasher();
Josh Gaocbe70cb2016-10-18 18:17:52 -0700766 ASSERT_EQ(0, kill(crasher_pid, SIGSEGV));
767
768 AssertDeath(SIGSEGV);
769 FinishIntercept(&intercept_result);
770
771 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
772
773 std::string result;
774 ConsumeFd(std::move(output_fd), &result);
Elliott Hughes89722702018-05-02 10:47:00 -0700775 ASSERT_MATCH(
776 result,
777 R"(signal 11 \(SIGSEGV\), code 0 \(SI_USER from pid \d+, uid \d+\), fault addr --------)");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700778 ASSERT_MATCH(result, R"(backtrace:)");
779}
780
781TEST_F(CrasherTest, abort_message) {
782 int intercept_result;
783 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800784 StartProcess([]() {
Josh Gao1cc7bd82018-02-13 13:16:17 -0800785 // Arrived at experimentally;
786 // logd truncates at 4062.
787 // strlen("Abort message: ''") is 17.
788 // That's 4045, but we also want a NUL.
789 char buf[4045 + 1];
790 memset(buf, 'x', sizeof(buf));
791 buf[sizeof(buf) - 1] = '\0';
792 android_set_abort_message(buf);
Josh Gao502cfd22017-02-17 01:39:15 -0800793 abort();
794 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700795 StartIntercept(&output_fd);
796 FinishCrasher();
797 AssertDeath(SIGABRT);
798 FinishIntercept(&intercept_result);
799
800 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
801
802 std::string result;
803 ConsumeFd(std::move(output_fd), &result);
Josh Gao1cc7bd82018-02-13 13:16:17 -0800804 ASSERT_MATCH(result, R"(Abort message: 'x{4045}')");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700805}
806
Josh Gaoe06f2a42017-04-27 16:50:38 -0700807TEST_F(CrasherTest, abort_message_backtrace) {
808 int intercept_result;
809 unique_fd output_fd;
810 StartProcess([]() {
811 android_set_abort_message("not actually aborting");
Josh Gaoa48b41b2019-12-13 14:11:04 -0800812 raise(BIONIC_SIGNAL_DEBUGGER);
Josh Gaoe06f2a42017-04-27 16:50:38 -0700813 exit(0);
814 });
815 StartIntercept(&output_fd);
816 FinishCrasher();
817 AssertDeath(0);
818 FinishIntercept(&intercept_result);
819
820 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
821
822 std::string result;
823 ConsumeFd(std::move(output_fd), &result);
824 ASSERT_NOT_MATCH(result, R"(Abort message:)");
825}
826
Josh Gaocbe70cb2016-10-18 18:17:52 -0700827TEST_F(CrasherTest, intercept_timeout) {
828 int intercept_result;
829 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800830 StartProcess([]() {
831 abort();
832 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700833 StartIntercept(&output_fd);
834
835 // Don't let crasher finish until we timeout.
836 FinishIntercept(&intercept_result);
837
838 ASSERT_NE(1, intercept_result) << "tombstoned reported success? (intercept_result = "
839 << intercept_result << ")";
840
841 FinishCrasher();
842 AssertDeath(SIGABRT);
843}
844
Elliott Hughese4781d52021-03-17 09:15:15 -0700845TEST_F(CrasherTest, wait_for_debugger) {
846 if (!android::base::SetProperty(kWaitForDebuggerKey, "1")) {
847 FAIL() << "failed to enable wait_for_debugger";
Josh Gaocbe70cb2016-10-18 18:17:52 -0700848 }
849 sleep(1);
850
Josh Gao502cfd22017-02-17 01:39:15 -0800851 StartProcess([]() {
852 abort();
853 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700854 FinishCrasher();
855
856 int status;
Christopher Ferris172b0a02019-09-18 17:48:30 -0700857 ASSERT_EQ(crasher_pid, TEMP_FAILURE_RETRY(waitpid(crasher_pid, &status, WUNTRACED)));
Josh Gaocbe70cb2016-10-18 18:17:52 -0700858 ASSERT_TRUE(WIFSTOPPED(status));
859 ASSERT_EQ(SIGSTOP, WSTOPSIG(status));
860
861 ASSERT_EQ(0, kill(crasher_pid, SIGCONT));
862
863 AssertDeath(SIGABRT);
864}
865
Josh Gaocbe70cb2016-10-18 18:17:52 -0700866TEST_F(CrasherTest, backtrace) {
867 std::string result;
868 int intercept_result;
869 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800870
871 StartProcess([]() {
872 abort();
873 });
Narayan Kamatha73df602017-05-24 15:07:25 +0100874 StartIntercept(&output_fd, kDebuggerdNativeBacktrace);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700875
876 std::this_thread::sleep_for(500ms);
877
878 sigval val;
879 val.sival_int = 1;
Josh Gaoa48b41b2019-12-13 14:11:04 -0800880 ASSERT_EQ(0, sigqueue(crasher_pid, BIONIC_SIGNAL_DEBUGGER, val)) << strerror(errno);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700881 FinishIntercept(&intercept_result);
882 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
883 ConsumeFd(std::move(output_fd), &result);
Jaesung Chung58778e12017-06-15 18:20:34 +0900884 ASSERT_BACKTRACE_FRAME(result, "read");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700885
886 int status;
887 ASSERT_EQ(0, waitpid(crasher_pid, &status, WNOHANG | WUNTRACED));
888
889 StartIntercept(&output_fd);
890 FinishCrasher();
891 AssertDeath(SIGABRT);
892 FinishIntercept(&intercept_result);
893 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
894 ConsumeFd(std::move(output_fd), &result);
Andreas Gampe26cbafb2017-06-22 20:14:43 -0700895 ASSERT_BACKTRACE_FRAME(result, "abort");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700896}
Josh Gaofca7ca32017-01-23 12:05:35 -0800897
898TEST_F(CrasherTest, PR_SET_DUMPABLE_0_crash) {
Josh Gao502cfd22017-02-17 01:39:15 -0800899 int intercept_result;
900 unique_fd output_fd;
Josh Gaofca7ca32017-01-23 12:05:35 -0800901 StartProcess([]() {
902 prctl(PR_SET_DUMPABLE, 0);
Josh Gao502cfd22017-02-17 01:39:15 -0800903 abort();
Josh Gaofca7ca32017-01-23 12:05:35 -0800904 });
Josh Gao502cfd22017-02-17 01:39:15 -0800905
906 StartIntercept(&output_fd);
907 FinishCrasher();
908 AssertDeath(SIGABRT);
909 FinishIntercept(&intercept_result);
910
911 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
912
913 std::string result;
914 ConsumeFd(std::move(output_fd), &result);
Andreas Gampe26cbafb2017-06-22 20:14:43 -0700915 ASSERT_BACKTRACE_FRAME(result, "abort");
Josh Gaofca7ca32017-01-23 12:05:35 -0800916}
917
Josh Gao502cfd22017-02-17 01:39:15 -0800918TEST_F(CrasherTest, capabilities) {
919 ASSERT_EQ(0U, getuid()) << "capability test requires root";
920
Josh Gaofca7ca32017-01-23 12:05:35 -0800921 StartProcess([]() {
Josh Gao502cfd22017-02-17 01:39:15 -0800922 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) != 0) {
923 err(1, "failed to set PR_SET_KEEPCAPS");
924 }
925
926 if (setresuid(1, 1, 1) != 0) {
927 err(1, "setresuid failed");
928 }
929
930 __user_cap_header_struct capheader;
931 __user_cap_data_struct capdata[2];
932 memset(&capheader, 0, sizeof(capheader));
933 memset(&capdata, 0, sizeof(capdata));
934
935 capheader.version = _LINUX_CAPABILITY_VERSION_3;
936 capheader.pid = 0;
937
938 // Turn on every third capability.
939 static_assert(CAP_LAST_CAP > 33, "CAP_LAST_CAP <= 32");
940 for (int i = 0; i < CAP_LAST_CAP; i += 3) {
941 capdata[CAP_TO_INDEX(i)].permitted |= CAP_TO_MASK(i);
942 capdata[CAP_TO_INDEX(i)].effective |= CAP_TO_MASK(i);
943 }
944
945 // Make sure CAP_SYS_PTRACE is off.
946 capdata[CAP_TO_INDEX(CAP_SYS_PTRACE)].permitted &= ~(CAP_TO_MASK(CAP_SYS_PTRACE));
947 capdata[CAP_TO_INDEX(CAP_SYS_PTRACE)].effective &= ~(CAP_TO_MASK(CAP_SYS_PTRACE));
948
949 if (capset(&capheader, &capdata[0]) != 0) {
950 err(1, "capset failed");
951 }
952
953 if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_CLEAR_ALL, 0, 0, 0) != 0) {
954 err(1, "failed to drop ambient capabilities");
955 }
956
Josh Gaoa5199a92017-04-03 13:18:34 -0700957 pthread_setname_np(pthread_self(), "thread_name");
Josh Gao502cfd22017-02-17 01:39:15 -0800958 raise(SIGSYS);
Josh Gaofca7ca32017-01-23 12:05:35 -0800959 });
Josh Gao502cfd22017-02-17 01:39:15 -0800960
961 unique_fd output_fd;
962 StartIntercept(&output_fd);
963 FinishCrasher();
964 AssertDeath(SIGSYS);
965
966 std::string result;
967 int intercept_result;
968 FinishIntercept(&intercept_result);
969 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
970 ConsumeFd(std::move(output_fd), &result);
Josh Gaoa5199a92017-04-03 13:18:34 -0700971 ASSERT_MATCH(result, R"(name: thread_name\s+>>> .+debuggerd_test(32|64) <<<)");
Jaesung Chung58778e12017-06-15 18:20:34 +0900972 ASSERT_BACKTRACE_FRAME(result, "tgkill");
Josh Gaofca7ca32017-01-23 12:05:35 -0800973}
Josh Gaoc3c8c022017-02-13 16:36:18 -0800974
Josh Gao2e7b8e22017-05-04 17:12:57 -0700975TEST_F(CrasherTest, fake_pid) {
976 int intercept_result;
977 unique_fd output_fd;
978
979 // Prime the getpid/gettid caches.
980 UNUSED(getpid());
981 UNUSED(gettid());
982
983 std::function<pid_t()> clone_fn = []() {
984 return syscall(__NR_clone, SIGCHLD, nullptr, nullptr, nullptr, nullptr);
985 };
986 StartProcess(
987 []() {
988 ASSERT_NE(getpid(), syscall(__NR_getpid));
989 ASSERT_NE(gettid(), syscall(__NR_gettid));
990 raise(SIGSEGV);
991 },
992 clone_fn);
993
994 StartIntercept(&output_fd);
995 FinishCrasher();
996 AssertDeath(SIGSEGV);
997 FinishIntercept(&intercept_result);
998
999 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1000
1001 std::string result;
1002 ConsumeFd(std::move(output_fd), &result);
Jaesung Chung58778e12017-06-15 18:20:34 +09001003 ASSERT_BACKTRACE_FRAME(result, "tgkill");
Josh Gao2e7b8e22017-05-04 17:12:57 -07001004}
1005
Josh Gaoe04ca272018-01-16 15:38:17 -08001006static const char* const kDebuggerdSeccompPolicy =
1007 "/system/etc/seccomp_policy/crash_dump." ABI_STRING ".policy";
1008
Josh Gao70adac62018-02-22 11:38:33 -08001009static pid_t seccomp_fork_impl(void (*prejail)()) {
Josh Gao6f9eeec2018-09-12 13:55:47 -07001010 std::string policy;
1011 if (!android::base::ReadFileToString(kDebuggerdSeccompPolicy, &policy)) {
1012 PLOG(FATAL) << "failed to read policy file";
1013 }
1014
1015 // Allow a bunch of syscalls used by the tests.
1016 policy += "\nclone: 1";
1017 policy += "\nsigaltstack: 1";
1018 policy += "\nnanosleep: 1";
Christopher Ferrisab606682019-09-17 15:31:47 -07001019 policy += "\ngetrlimit: 1";
1020 policy += "\nugetrlimit: 1";
Josh Gao6f9eeec2018-09-12 13:55:47 -07001021
1022 FILE* tmp_file = tmpfile();
1023 if (!tmp_file) {
1024 PLOG(FATAL) << "tmpfile failed";
1025 }
1026
Christopher Ferris172b0a02019-09-18 17:48:30 -07001027 unique_fd tmp_fd(TEMP_FAILURE_RETRY(dup(fileno(tmp_file))));
Josh Gao6f9eeec2018-09-12 13:55:47 -07001028 if (!android::base::WriteStringToFd(policy, tmp_fd.get())) {
1029 PLOG(FATAL) << "failed to write policy to tmpfile";
1030 }
1031
1032 if (lseek(tmp_fd.get(), 0, SEEK_SET) != 0) {
1033 PLOG(FATAL) << "failed to seek tmp_fd";
Josh Gaoe04ca272018-01-16 15:38:17 -08001034 }
1035
1036 ScopedMinijail jail{minijail_new()};
1037 if (!jail) {
1038 LOG(FATAL) << "failed to create minijail";
1039 }
1040
1041 minijail_no_new_privs(jail.get());
1042 minijail_log_seccomp_filter_failures(jail.get());
1043 minijail_use_seccomp_filter(jail.get());
Josh Gao6f9eeec2018-09-12 13:55:47 -07001044 minijail_parse_seccomp_filters_from_fd(jail.get(), tmp_fd.release());
Josh Gaoe04ca272018-01-16 15:38:17 -08001045
1046 pid_t result = fork();
1047 if (result == -1) {
1048 return result;
1049 } else if (result != 0) {
1050 return result;
1051 }
1052
1053 // Spawn and detach a thread that spins forever.
1054 std::atomic<bool> thread_ready(false);
1055 std::thread thread([&jail, &thread_ready]() {
1056 minijail_enter(jail.get());
1057 thread_ready = true;
1058 for (;;)
1059 ;
1060 });
1061 thread.detach();
1062
1063 while (!thread_ready) {
1064 continue;
1065 }
1066
Josh Gao70adac62018-02-22 11:38:33 -08001067 if (prejail) {
1068 prejail();
1069 }
1070
Josh Gaoe04ca272018-01-16 15:38:17 -08001071 minijail_enter(jail.get());
1072 return result;
1073}
1074
Josh Gao70adac62018-02-22 11:38:33 -08001075static pid_t seccomp_fork() {
1076 return seccomp_fork_impl(nullptr);
1077}
1078
Josh Gaoe04ca272018-01-16 15:38:17 -08001079TEST_F(CrasherTest, seccomp_crash) {
1080 int intercept_result;
1081 unique_fd output_fd;
1082
1083 StartProcess([]() { abort(); }, &seccomp_fork);
1084
1085 StartIntercept(&output_fd);
1086 FinishCrasher();
1087 AssertDeath(SIGABRT);
1088 FinishIntercept(&intercept_result);
1089 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1090
1091 std::string result;
1092 ConsumeFd(std::move(output_fd), &result);
1093 ASSERT_BACKTRACE_FRAME(result, "abort");
1094}
1095
Josh Gao70adac62018-02-22 11:38:33 -08001096static pid_t seccomp_fork_rlimit() {
1097 return seccomp_fork_impl([]() {
1098 struct rlimit rlim = {
1099 .rlim_cur = 512 * 1024 * 1024,
1100 .rlim_max = 512 * 1024 * 1024,
1101 };
1102
1103 if (setrlimit(RLIMIT_AS, &rlim) != 0) {
1104 raise(SIGINT);
1105 }
1106 });
1107}
1108
1109TEST_F(CrasherTest, seccomp_crash_oom) {
1110 int intercept_result;
1111 unique_fd output_fd;
1112
1113 StartProcess(
1114 []() {
1115 std::vector<void*> vec;
1116 for (int i = 0; i < 512; ++i) {
1117 char* buf = static_cast<char*>(malloc(1024 * 1024));
1118 if (!buf) {
1119 abort();
1120 }
1121 memset(buf, 0xff, 1024 * 1024);
1122 vec.push_back(buf);
1123 }
1124 },
1125 &seccomp_fork_rlimit);
1126
1127 StartIntercept(&output_fd);
1128 FinishCrasher();
1129 AssertDeath(SIGABRT);
1130 FinishIntercept(&intercept_result);
1131 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1132
1133 // We can't actually generate a backtrace, just make sure that the process terminates.
1134}
1135
Josh Gaoe04ca272018-01-16 15:38:17 -08001136__attribute__((noinline)) extern "C" bool raise_debugger_signal(DebuggerdDumpType dump_type) {
1137 siginfo_t siginfo;
1138 siginfo.si_code = SI_QUEUE;
1139 siginfo.si_pid = getpid();
1140 siginfo.si_uid = getuid();
1141
1142 if (dump_type != kDebuggerdNativeBacktrace && dump_type != kDebuggerdTombstone) {
1143 PLOG(FATAL) << "invalid dump type";
1144 }
1145
1146 siginfo.si_value.sival_int = dump_type == kDebuggerdNativeBacktrace;
1147
Josh Gaoa48b41b2019-12-13 14:11:04 -08001148 if (syscall(__NR_rt_tgsigqueueinfo, getpid(), gettid(), BIONIC_SIGNAL_DEBUGGER, &siginfo) != 0) {
Josh Gaoe04ca272018-01-16 15:38:17 -08001149 PLOG(ERROR) << "libdebuggerd_client: failed to send signal to self";
1150 return false;
1151 }
1152
1153 return true;
1154}
1155
1156TEST_F(CrasherTest, seccomp_tombstone) {
1157 int intercept_result;
1158 unique_fd output_fd;
1159
1160 static const auto dump_type = kDebuggerdTombstone;
1161 StartProcess(
1162 []() {
1163 raise_debugger_signal(dump_type);
1164 _exit(0);
1165 },
1166 &seccomp_fork);
1167
1168 StartIntercept(&output_fd, dump_type);
1169 FinishCrasher();
1170 AssertDeath(0);
1171 FinishIntercept(&intercept_result);
1172 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1173
1174 std::string result;
1175 ConsumeFd(std::move(output_fd), &result);
1176 ASSERT_BACKTRACE_FRAME(result, "raise_debugger_signal");
1177}
1178
Josh Gao6f9eeec2018-09-12 13:55:47 -07001179extern "C" void foo() {
1180 LOG(INFO) << "foo";
1181 std::this_thread::sleep_for(1s);
1182}
1183
1184extern "C" void bar() {
1185 LOG(INFO) << "bar";
1186 std::this_thread::sleep_for(1s);
1187}
1188
Josh Gaoe04ca272018-01-16 15:38:17 -08001189TEST_F(CrasherTest, seccomp_backtrace) {
1190 int intercept_result;
1191 unique_fd output_fd;
1192
1193 static const auto dump_type = kDebuggerdNativeBacktrace;
1194 StartProcess(
1195 []() {
Josh Gao6f9eeec2018-09-12 13:55:47 -07001196 std::thread a(foo);
1197 std::thread b(bar);
1198
1199 std::this_thread::sleep_for(100ms);
1200
Josh Gaoe04ca272018-01-16 15:38:17 -08001201 raise_debugger_signal(dump_type);
1202 _exit(0);
1203 },
1204 &seccomp_fork);
1205
1206 StartIntercept(&output_fd, dump_type);
1207 FinishCrasher();
1208 AssertDeath(0);
1209 FinishIntercept(&intercept_result);
1210 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1211
1212 std::string result;
1213 ConsumeFd(std::move(output_fd), &result);
1214 ASSERT_BACKTRACE_FRAME(result, "raise_debugger_signal");
Josh Gao6f9eeec2018-09-12 13:55:47 -07001215 ASSERT_BACKTRACE_FRAME(result, "foo");
1216 ASSERT_BACKTRACE_FRAME(result, "bar");
Josh Gaoe04ca272018-01-16 15:38:17 -08001217}
1218
1219TEST_F(CrasherTest, seccomp_crash_logcat) {
1220 StartProcess([]() { abort(); }, &seccomp_fork);
1221 FinishCrasher();
1222
1223 // Make sure we don't get SIGSYS when trying to dump a crash to logcat.
1224 AssertDeath(SIGABRT);
1225}
1226
Josh Gaofd13bf02017-08-18 15:37:26 -07001227TEST_F(CrasherTest, competing_tracer) {
1228 int intercept_result;
1229 unique_fd output_fd;
1230 StartProcess([]() {
Josh Gao2b2ae0c2017-08-21 14:31:17 -07001231 raise(SIGABRT);
Josh Gaofd13bf02017-08-18 15:37:26 -07001232 });
1233
1234 StartIntercept(&output_fd);
Josh Gaofd13bf02017-08-18 15:37:26 -07001235
1236 ASSERT_EQ(0, ptrace(PTRACE_SEIZE, crasher_pid, 0, 0));
Josh Gao2b2ae0c2017-08-21 14:31:17 -07001237 FinishCrasher();
Josh Gaofd13bf02017-08-18 15:37:26 -07001238
1239 int status;
Christopher Ferris172b0a02019-09-18 17:48:30 -07001240 ASSERT_EQ(crasher_pid, TEMP_FAILURE_RETRY(waitpid(crasher_pid, &status, 0)));
Josh Gaofd13bf02017-08-18 15:37:26 -07001241 ASSERT_TRUE(WIFSTOPPED(status));
1242 ASSERT_EQ(SIGABRT, WSTOPSIG(status));
1243
1244 ASSERT_EQ(0, ptrace(PTRACE_CONT, crasher_pid, 0, SIGABRT));
1245 FinishIntercept(&intercept_result);
1246 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1247
1248 std::string result;
1249 ConsumeFd(std::move(output_fd), &result);
1250 std::string regex = R"(failed to attach to thread \d+, already traced by )";
1251 regex += std::to_string(gettid());
1252 regex += R"( \(.+debuggerd_test)";
1253 ASSERT_MATCH(result, regex.c_str());
1254
Christopher Ferris172b0a02019-09-18 17:48:30 -07001255 ASSERT_EQ(crasher_pid, TEMP_FAILURE_RETRY(waitpid(crasher_pid, &status, 0)));
Josh Gao2b2ae0c2017-08-21 14:31:17 -07001256 ASSERT_TRUE(WIFSTOPPED(status));
1257 ASSERT_EQ(SIGABRT, WSTOPSIG(status));
1258
Josh Gaofd13bf02017-08-18 15:37:26 -07001259 ASSERT_EQ(0, ptrace(PTRACE_DETACH, crasher_pid, 0, SIGABRT));
1260 AssertDeath(SIGABRT);
1261}
1262
Josh Gaobf06a402018-08-27 16:34:01 -07001263TEST_F(CrasherTest, fdsan_warning_abort_message) {
1264 int intercept_result;
1265 unique_fd output_fd;
1266
1267 StartProcess([]() {
1268 android_fdsan_set_error_level(ANDROID_FDSAN_ERROR_LEVEL_WARN_ONCE);
Christopher Ferris172b0a02019-09-18 17:48:30 -07001269 unique_fd fd(TEMP_FAILURE_RETRY(open("/dev/null", O_RDONLY | O_CLOEXEC)));
Josh Gaobf06a402018-08-27 16:34:01 -07001270 if (fd == -1) {
1271 abort();
1272 }
1273 close(fd.get());
1274 _exit(0);
1275 });
1276
1277 StartIntercept(&output_fd);
1278 FinishCrasher();
1279 AssertDeath(0);
1280 FinishIntercept(&intercept_result);
1281 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1282
1283 std::string result;
1284 ConsumeFd(std::move(output_fd), &result);
1285 ASSERT_MATCH(result, "Abort message: 'attempted to close");
1286}
1287
Josh Gaoc3c8c022017-02-13 16:36:18 -08001288TEST(crash_dump, zombie) {
1289 pid_t forkpid = fork();
1290
Josh Gaoc3c8c022017-02-13 16:36:18 -08001291 pid_t rc;
1292 int status;
1293
1294 if (forkpid == 0) {
1295 errno = 0;
1296 rc = waitpid(-1, &status, WNOHANG | __WALL | __WNOTHREAD);
1297 if (rc != -1 || errno != ECHILD) {
1298 errx(2, "first waitpid returned %d (%s), expected failure with ECHILD", rc, strerror(errno));
1299 }
1300
Josh Gaoa48b41b2019-12-13 14:11:04 -08001301 raise(BIONIC_SIGNAL_DEBUGGER);
Josh Gaoc3c8c022017-02-13 16:36:18 -08001302
1303 errno = 0;
Christopher Ferris172b0a02019-09-18 17:48:30 -07001304 rc = TEMP_FAILURE_RETRY(waitpid(-1, &status, __WALL | __WNOTHREAD));
Josh Gaoc3c8c022017-02-13 16:36:18 -08001305 if (rc != -1 || errno != ECHILD) {
1306 errx(2, "second waitpid returned %d (%s), expected failure with ECHILD", rc, strerror(errno));
1307 }
1308 _exit(0);
1309 } else {
Christopher Ferris172b0a02019-09-18 17:48:30 -07001310 rc = TEMP_FAILURE_RETRY(waitpid(forkpid, &status, 0));
Josh Gaoc3c8c022017-02-13 16:36:18 -08001311 ASSERT_EQ(forkpid, rc);
1312 ASSERT_TRUE(WIFEXITED(status));
1313 ASSERT_EQ(0, WEXITSTATUS(status));
1314 }
1315}
Josh Gao352a8452017-03-30 16:46:21 -07001316
1317TEST(tombstoned, no_notify) {
1318 // Do this a few times.
1319 for (int i = 0; i < 3; ++i) {
1320 pid_t pid = 123'456'789 + i;
1321
1322 unique_fd intercept_fd, output_fd;
Narayan Kamathca5e9082017-06-02 15:42:06 +01001323 InterceptStatus status;
1324 tombstoned_intercept(pid, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
1325 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gao352a8452017-03-30 16:46:21 -07001326
1327 {
1328 unique_fd tombstoned_socket, input_fd;
Narayan Kamatha73df602017-05-24 15:07:25 +01001329 ASSERT_TRUE(tombstoned_connect(pid, &tombstoned_socket, &input_fd, kDebuggerdTombstone));
Josh Gao352a8452017-03-30 16:46:21 -07001330 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), &pid, sizeof(pid)));
1331 }
1332
1333 pid_t read_pid;
1334 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), &read_pid, sizeof(read_pid)));
1335 ASSERT_EQ(read_pid, pid);
1336 }
1337}
1338
1339TEST(tombstoned, stress) {
1340 // Spawn threads to simultaneously do a bunch of failing dumps and a bunch of successful dumps.
1341 static constexpr int kDumpCount = 100;
1342
1343 std::atomic<bool> start(false);
1344 std::vector<std::thread> threads;
1345 threads.emplace_back([&start]() {
1346 while (!start) {
1347 continue;
1348 }
1349
1350 // Use a way out of range pid, to avoid stomping on an actual process.
1351 pid_t pid_base = 1'000'000;
1352
1353 for (int dump = 0; dump < kDumpCount; ++dump) {
1354 pid_t pid = pid_base + dump;
1355
1356 unique_fd intercept_fd, output_fd;
Narayan Kamathca5e9082017-06-02 15:42:06 +01001357 InterceptStatus status;
1358 tombstoned_intercept(pid, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
1359 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gao352a8452017-03-30 16:46:21 -07001360
1361 // Pretend to crash, and then immediately close the socket.
1362 unique_fd sockfd(socket_local_client(kTombstonedCrashSocketName,
1363 ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_SEQPACKET));
1364 if (sockfd == -1) {
1365 FAIL() << "failed to connect to tombstoned: " << strerror(errno);
1366 }
1367 TombstonedCrashPacket packet = {};
1368 packet.packet_type = CrashPacketType::kDumpRequest;
1369 packet.packet.dump_request.pid = pid;
1370 if (TEMP_FAILURE_RETRY(write(sockfd, &packet, sizeof(packet))) != sizeof(packet)) {
1371 FAIL() << "failed to write to tombstoned: " << strerror(errno);
1372 }
1373
1374 continue;
1375 }
1376 });
1377
1378 threads.emplace_back([&start]() {
1379 while (!start) {
1380 continue;
1381 }
1382
1383 // Use a way out of range pid, to avoid stomping on an actual process.
1384 pid_t pid_base = 2'000'000;
1385
1386 for (int dump = 0; dump < kDumpCount; ++dump) {
1387 pid_t pid = pid_base + dump;
1388
1389 unique_fd intercept_fd, output_fd;
Narayan Kamathca5e9082017-06-02 15:42:06 +01001390 InterceptStatus status;
1391 tombstoned_intercept(pid, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
1392 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gao352a8452017-03-30 16:46:21 -07001393
1394 {
1395 unique_fd tombstoned_socket, input_fd;
Narayan Kamatha73df602017-05-24 15:07:25 +01001396 ASSERT_TRUE(tombstoned_connect(pid, &tombstoned_socket, &input_fd, kDebuggerdTombstone));
Josh Gao352a8452017-03-30 16:46:21 -07001397 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), &pid, sizeof(pid)));
1398 tombstoned_notify_completion(tombstoned_socket.get());
1399 }
1400
1401 // TODO: Fix the race that requires this sleep.
1402 std::this_thread::sleep_for(50ms);
1403
1404 pid_t read_pid;
1405 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), &read_pid, sizeof(read_pid)));
1406 ASSERT_EQ(read_pid, pid);
1407 }
1408 });
1409
1410 start = true;
1411
1412 for (std::thread& thread : threads) {
1413 thread.join();
1414 }
1415}
Narayan Kamathca5e9082017-06-02 15:42:06 +01001416
1417TEST(tombstoned, java_trace_intercept_smoke) {
1418 // Using a "real" PID is a little dangerous here - if the test fails
1419 // or crashes, we might end up getting a bogus / unreliable stack
1420 // trace.
1421 const pid_t self = getpid();
1422
1423 unique_fd intercept_fd, output_fd;
1424 InterceptStatus status;
1425 tombstoned_intercept(self, &intercept_fd, &output_fd, &status, kDebuggerdJavaBacktrace);
1426 ASSERT_EQ(InterceptStatus::kRegistered, status);
1427
Josh Gao76e1e302021-01-26 15:53:11 -08001428 // First connect to tombstoned requesting a native tombstone. This
Narayan Kamathca5e9082017-06-02 15:42:06 +01001429 // should result in a "regular" FD and not the installed intercept.
1430 const char native[] = "native";
1431 unique_fd tombstoned_socket, input_fd;
Josh Gao76e1e302021-01-26 15:53:11 -08001432 ASSERT_TRUE(tombstoned_connect(self, &tombstoned_socket, &input_fd, kDebuggerdTombstone));
Narayan Kamathca5e9082017-06-02 15:42:06 +01001433 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), native, sizeof(native)));
1434 tombstoned_notify_completion(tombstoned_socket.get());
1435
1436 // Then, connect to tombstoned asking for a java backtrace. This *should*
1437 // trigger the intercept.
1438 const char java[] = "java";
1439 ASSERT_TRUE(tombstoned_connect(self, &tombstoned_socket, &input_fd, kDebuggerdJavaBacktrace));
1440 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), java, sizeof(java)));
1441 tombstoned_notify_completion(tombstoned_socket.get());
1442
1443 char outbuf[sizeof(java)];
1444 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), outbuf, sizeof(outbuf)));
1445 ASSERT_STREQ("java", outbuf);
1446}
1447
1448TEST(tombstoned, multiple_intercepts) {
1449 const pid_t fake_pid = 1'234'567;
1450 unique_fd intercept_fd, output_fd;
1451 InterceptStatus status;
1452 tombstoned_intercept(fake_pid, &intercept_fd, &output_fd, &status, kDebuggerdJavaBacktrace);
1453 ASSERT_EQ(InterceptStatus::kRegistered, status);
1454
1455 unique_fd intercept_fd_2, output_fd_2;
1456 tombstoned_intercept(fake_pid, &intercept_fd_2, &output_fd_2, &status, kDebuggerdNativeBacktrace);
1457 ASSERT_EQ(InterceptStatus::kFailedAlreadyRegistered, status);
1458}
1459
1460TEST(tombstoned, intercept_any) {
1461 const pid_t fake_pid = 1'234'567;
1462
1463 unique_fd intercept_fd, output_fd;
1464 InterceptStatus status;
1465 tombstoned_intercept(fake_pid, &intercept_fd, &output_fd, &status, kDebuggerdNativeBacktrace);
1466 ASSERT_EQ(InterceptStatus::kRegistered, status);
1467
1468 const char any[] = "any";
1469 unique_fd tombstoned_socket, input_fd;
1470 ASSERT_TRUE(tombstoned_connect(fake_pid, &tombstoned_socket, &input_fd, kDebuggerdAnyIntercept));
1471 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), any, sizeof(any)));
1472 tombstoned_notify_completion(tombstoned_socket.get());
1473
1474 char outbuf[sizeof(any)];
1475 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), outbuf, sizeof(outbuf)));
1476 ASSERT_STREQ("any", outbuf);
1477}
Josh Gao2b22ae12018-09-12 14:51:03 -07001478
1479TEST(tombstoned, interceptless_backtrace) {
1480 // Generate 50 backtraces, and then check to see that we haven't created 50 new tombstones.
1481 auto get_tombstone_timestamps = []() -> std::map<int, time_t> {
1482 std::map<int, time_t> result;
1483 for (int i = 0; i < 99; ++i) {
1484 std::string path = android::base::StringPrintf("/data/tombstones/tombstone_%02d", i);
1485 struct stat st;
1486 if (stat(path.c_str(), &st) == 0) {
1487 result[i] = st.st_mtim.tv_sec;
1488 }
1489 }
1490 return result;
1491 };
1492
1493 auto before = get_tombstone_timestamps();
1494 for (int i = 0; i < 50; ++i) {
1495 raise_debugger_signal(kDebuggerdNativeBacktrace);
1496 }
1497 auto after = get_tombstone_timestamps();
1498
1499 int diff = 0;
1500 for (int i = 0; i < 99; ++i) {
1501 if (after.count(i) == 0) {
1502 continue;
1503 }
1504 if (before.count(i) == 0) {
1505 ++diff;
1506 continue;
1507 }
1508 if (before[i] != after[i]) {
1509 ++diff;
1510 }
1511 }
1512
1513 // We can't be sure that nothing's crash looping in the background.
1514 // This should be good enough, though...
1515 ASSERT_LT(diff, 10) << "too many new tombstones; is something crashing in the background?";
1516}
Christopher Ferris481e8372019-07-15 17:13:24 -07001517
1518static __attribute__((__noinline__)) void overflow_stack(void* p) {
1519 void* buf[1];
1520 buf[0] = p;
1521 static volatile void* global = buf;
1522 if (global) {
1523 global = buf;
1524 overflow_stack(&buf);
1525 }
1526}
1527
1528TEST_F(CrasherTest, stack_overflow) {
1529 int intercept_result;
1530 unique_fd output_fd;
1531 StartProcess([]() { overflow_stack(nullptr); });
1532
1533 StartIntercept(&output_fd);
1534 FinishCrasher();
1535 AssertDeath(SIGSEGV);
1536 FinishIntercept(&intercept_result);
1537
1538 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1539
1540 std::string result;
1541 ConsumeFd(std::move(output_fd), &result);
1542 ASSERT_MATCH(result, R"(Cause: stack pointer[^\n]*stack overflow.\n)");
1543}
Josh Gao76e1e302021-01-26 15:53:11 -08001544
1545TEST(tombstoned, proto) {
1546 const pid_t self = getpid();
1547 unique_fd tombstoned_socket, text_fd, proto_fd;
1548 ASSERT_TRUE(
1549 tombstoned_connect(self, &tombstoned_socket, &text_fd, &proto_fd, kDebuggerdTombstoneProto));
1550
1551 tombstoned_notify_completion(tombstoned_socket.get());
1552
1553 ASSERT_NE(-1, text_fd.get());
1554 ASSERT_NE(-1, proto_fd.get());
1555
1556 struct stat text_st;
1557 ASSERT_EQ(0, fstat(text_fd.get(), &text_st));
1558
1559 // Give tombstoned some time to link the files into place.
1560 std::this_thread::sleep_for(100ms);
1561
1562 // Find the tombstone.
Christopher Ferris35da2882021-02-17 15:39:06 -08001563 std::optional<std::string> tombstone_file;
1564 std::unique_ptr<DIR, decltype(&closedir)> dir_h(opendir("/data/tombstones"), closedir);
1565 ASSERT_TRUE(dir_h != nullptr);
1566 std::regex tombstone_re("tombstone_\\d+");
1567 dirent* entry;
1568 while ((entry = readdir(dir_h.get())) != nullptr) {
1569 if (!std::regex_match(entry->d_name, tombstone_re)) {
1570 continue;
1571 }
1572 std::string path = android::base::StringPrintf("/data/tombstones/%s", entry->d_name);
Josh Gao76e1e302021-01-26 15:53:11 -08001573
1574 struct stat st;
1575 if (TEMP_FAILURE_RETRY(stat(path.c_str(), &st)) != 0) {
1576 continue;
1577 }
1578
1579 if (st.st_dev == text_st.st_dev && st.st_ino == text_st.st_ino) {
Christopher Ferris35da2882021-02-17 15:39:06 -08001580 tombstone_file = path;
Josh Gao76e1e302021-01-26 15:53:11 -08001581 break;
1582 }
1583 }
1584
Christopher Ferris35da2882021-02-17 15:39:06 -08001585 ASSERT_TRUE(tombstone_file);
1586 std::string proto_path = tombstone_file.value() + ".pb";
Josh Gao76e1e302021-01-26 15:53:11 -08001587
1588 struct stat proto_fd_st;
1589 struct stat proto_file_st;
1590 ASSERT_EQ(0, fstat(proto_fd.get(), &proto_fd_st));
1591 ASSERT_EQ(0, stat(proto_path.c_str(), &proto_file_st));
1592
1593 ASSERT_EQ(proto_fd_st.st_dev, proto_file_st.st_dev);
1594 ASSERT_EQ(proto_fd_st.st_ino, proto_file_st.st_ino);
1595}
1596
1597TEST(tombstoned, proto_intercept) {
1598 const pid_t self = getpid();
1599 unique_fd intercept_fd, output_fd;
1600 InterceptStatus status;
1601
1602 tombstoned_intercept(self, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
1603 ASSERT_EQ(InterceptStatus::kRegistered, status);
1604
1605 unique_fd tombstoned_socket, text_fd, proto_fd;
1606 ASSERT_TRUE(
1607 tombstoned_connect(self, &tombstoned_socket, &text_fd, &proto_fd, kDebuggerdTombstoneProto));
1608 ASSERT_TRUE(android::base::WriteStringToFd("foo", text_fd.get()));
1609 tombstoned_notify_completion(tombstoned_socket.get());
1610
1611 text_fd.reset();
1612
1613 std::string output;
1614 ASSERT_TRUE(android::base::ReadFdToString(output_fd, &output));
1615 ASSERT_EQ("foo", output);
1616}