blob: 5b0411119e63b527b31159d54a17fa807d283acf [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>
Christopher Ferrisfe751c52021-04-16 09:40:40 -070018#include <dlfcn.h>
Josh Gaocbe70cb2016-10-18 18:17:52 -070019#include <err.h>
20#include <fcntl.h>
Elliott Hughes03b283a2021-01-15 11:34:26 -080021#include <malloc.h>
Josh Gaocdea7502017-11-01 15:00:40 -070022#include <stdlib.h>
Josh Gao502cfd22017-02-17 01:39:15 -080023#include <sys/capability.h>
Peter Collingbournefe8997a2020-07-20 15:08:52 -070024#include <sys/mman.h>
Josh Gaofca7ca32017-01-23 12:05:35 -080025#include <sys/prctl.h>
Josh Gaofd13bf02017-08-18 15:37:26 -070026#include <sys/ptrace.h>
Josh Gao70adac62018-02-22 11:38:33 -080027#include <sys/resource.h>
Dan Albertc38057a2017-10-11 11:35:40 -070028#include <sys/syscall.h>
Josh Gaocbe70cb2016-10-18 18:17:52 -070029#include <sys/types.h>
Josh Gaofd13bf02017-08-18 15:37:26 -070030#include <unistd.h>
Josh Gaocbe70cb2016-10-18 18:17:52 -070031
32#include <chrono>
33#include <regex>
Christopher Ferrisfe751c52021-04-16 09:40:40 -070034#include <string>
Josh Gaocbe70cb2016-10-18 18:17:52 -070035#include <thread>
36
Josh Gaobf06a402018-08-27 16:34:01 -070037#include <android/fdsan.h>
Josh Gao502cfd22017-02-17 01:39:15 -080038#include <android/set_abort_message.h>
Mitch Phillips7168a212021-03-09 16:53:23 -080039#include <bionic/malloc.h>
Peter Collingbournef8622522020-04-07 14:07:32 -070040#include <bionic/mte.h>
Josh Gaoa48b41b2019-12-13 14:11:04 -080041#include <bionic/reserved_signals.h>
Josh Gao502cfd22017-02-17 01:39:15 -080042
Josh Gao5f87bbd2019-01-09 17:01:49 -080043#include <android-base/cmsg.h>
Josh Gaocbe70cb2016-10-18 18:17:52 -070044#include <android-base/file.h>
45#include <android-base/logging.h>
Josh Gao2e7b8e22017-05-04 17:12:57 -070046#include <android-base/macros.h>
Josh Gaocbe70cb2016-10-18 18:17:52 -070047#include <android-base/parseint.h>
48#include <android-base/properties.h>
Josh Gao2b22ae12018-09-12 14:51:03 -070049#include <android-base/stringprintf.h>
Josh Gaocbe70cb2016-10-18 18:17:52 -070050#include <android-base/strings.h>
Josh Gao30171a82017-04-27 19:48:44 -070051#include <android-base/test_utils.h>
Josh Gaocbe70cb2016-10-18 18:17:52 -070052#include <android-base/unique_fd.h>
53#include <cutils/sockets.h>
Josh Gaocbe70cb2016-10-18 18:17:52 -070054#include <gtest/gtest.h>
55
Josh Gaoe04ca272018-01-16 15:38:17 -080056#include <libminijail.h>
57#include <scoped_minijail.h>
58
Narayan Kamath2d377cd2017-05-10 10:58:59 +010059#include "debuggerd/handler.h"
60#include "protocol.h"
61#include "tombstoned/tombstoned.h"
62#include "util.h"
63
Josh Gaocbe70cb2016-10-18 18:17:52 -070064using namespace std::chrono_literals;
Josh Gao5f87bbd2019-01-09 17:01:49 -080065
66using android::base::SendFileDescriptors;
Josh Gaocbe70cb2016-10-18 18:17:52 -070067using android::base::unique_fd;
68
69#if defined(__LP64__)
Josh Gaocbe70cb2016-10-18 18:17:52 -070070#define ARCH_SUFFIX "64"
71#else
Josh Gaocbe70cb2016-10-18 18:17:52 -070072#define ARCH_SUFFIX ""
73#endif
74
Elliott Hughese4781d52021-03-17 09:15:15 -070075constexpr char kWaitForDebuggerKey[] = "debug.debuggerd.wait_for_debugger";
Josh Gaocbe70cb2016-10-18 18:17:52 -070076
77#define TIMEOUT(seconds, expr) \
78 [&]() { \
79 struct sigaction old_sigaction; \
80 struct sigaction new_sigaction = {}; \
81 new_sigaction.sa_handler = [](int) {}; \
82 if (sigaction(SIGALRM, &new_sigaction, &new_sigaction) != 0) { \
83 err(1, "sigaction failed"); \
84 } \
85 alarm(seconds); \
86 auto value = expr; \
87 int saved_errno = errno; \
88 if (sigaction(SIGALRM, &old_sigaction, nullptr) != 0) { \
89 err(1, "sigaction failed"); \
90 } \
91 alarm(0); \
92 errno = saved_errno; \
93 return value; \
94 }()
95
Chih-Hung Hsieh3249b3a2018-05-11 16:01:21 -070096// Backtrace frame dump could contain:
97// #01 pc 0001cded /data/tmp/debuggerd_test32 (raise_debugger_signal+80)
98// or
99// #01 pc 00022a09 /data/tmp/debuggerd_test32 (offset 0x12000) (raise_debugger_signal+80)
Josh Gaoe04ca272018-01-16 15:38:17 -0800100#define ASSERT_BACKTRACE_FRAME(result, frame_name) \
Chih-Hung Hsieh3249b3a2018-05-11 16:01:21 -0700101 ASSERT_MATCH(result, \
102 R"(#\d\d pc [0-9a-f]+\s+ \S+ (\(offset 0x[0-9a-f]+\) )?\()" frame_name R"(\+)");
Jaesung Chung58778e12017-06-15 18:20:34 +0900103
Mitch Phillips7168a212021-03-09 16:53:23 -0800104// Enable GWP-ASan at the start of this process. GWP-ASan is enabled using
105// process sampling, so we need to ensure we force GWP-ASan on.
106__attribute__((constructor)) static void enable_gwp_asan() {
107 bool force = true;
108 android_mallopt(M_INITIALIZE_GWP_ASAN, &force, sizeof(force));
109}
110
Narayan Kamatha73df602017-05-24 15:07:25 +0100111static void tombstoned_intercept(pid_t target_pid, unique_fd* intercept_fd, unique_fd* output_fd,
Narayan Kamathca5e9082017-06-02 15:42:06 +0100112 InterceptStatus* status, DebuggerdDumpType intercept_type) {
Josh Gao460b3362017-03-30 16:40:47 -0700113 intercept_fd->reset(socket_local_client(kTombstonedInterceptSocketName,
114 ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_SEQPACKET));
115 if (intercept_fd->get() == -1) {
116 FAIL() << "failed to contact tombstoned: " << strerror(errno);
117 }
118
Nick Desaulniers67d52aa2019-10-07 23:28:15 -0700119 InterceptRequest req = {
120 .dump_type = intercept_type,
121 .pid = target_pid,
122 };
Josh Gao460b3362017-03-30 16:40:47 -0700123
124 unique_fd output_pipe_write;
125 if (!Pipe(output_fd, &output_pipe_write)) {
126 FAIL() << "failed to create output pipe: " << strerror(errno);
127 }
128
129 std::string pipe_size_str;
130 int pipe_buffer_size;
131 if (!android::base::ReadFileToString("/proc/sys/fs/pipe-max-size", &pipe_size_str)) {
132 FAIL() << "failed to read /proc/sys/fs/pipe-max-size: " << strerror(errno);
133 }
134
135 pipe_size_str = android::base::Trim(pipe_size_str);
136
137 if (!android::base::ParseInt(pipe_size_str.c_str(), &pipe_buffer_size, 0)) {
138 FAIL() << "failed to parse pipe max size";
139 }
140
141 if (fcntl(output_fd->get(), F_SETPIPE_SZ, pipe_buffer_size) != pipe_buffer_size) {
142 FAIL() << "failed to set pipe size: " << strerror(errno);
143 }
144
Josh Gao5675f3c2017-06-01 12:19:53 -0700145 ASSERT_GE(pipe_buffer_size, 1024 * 1024);
146
Josh Gao5f87bbd2019-01-09 17:01:49 -0800147 ssize_t rc = SendFileDescriptors(intercept_fd->get(), &req, sizeof(req), output_pipe_write.get());
148 output_pipe_write.reset();
149 if (rc != sizeof(req)) {
Josh Gao460b3362017-03-30 16:40:47 -0700150 FAIL() << "failed to send output fd to tombstoned: " << strerror(errno);
151 }
152
153 InterceptResponse response;
Josh Gao5f87bbd2019-01-09 17:01:49 -0800154 rc = TEMP_FAILURE_RETRY(read(intercept_fd->get(), &response, sizeof(response)));
Josh Gao460b3362017-03-30 16:40:47 -0700155 if (rc == -1) {
156 FAIL() << "failed to read response from tombstoned: " << strerror(errno);
157 } else if (rc == 0) {
158 FAIL() << "failed to read response from tombstoned (EOF)";
159 } else if (rc != sizeof(response)) {
160 FAIL() << "received packet of unexpected length from tombstoned: expected " << sizeof(response)
161 << ", received " << rc;
162 }
163
Narayan Kamathca5e9082017-06-02 15:42:06 +0100164 *status = response.status;
Josh Gao460b3362017-03-30 16:40:47 -0700165}
166
Josh Gaocbe70cb2016-10-18 18:17:52 -0700167class CrasherTest : public ::testing::Test {
168 public:
169 pid_t crasher_pid = -1;
Elliott Hughese4781d52021-03-17 09:15:15 -0700170 bool previous_wait_for_debugger;
Josh Gaocbe70cb2016-10-18 18:17:52 -0700171 unique_fd crasher_pipe;
172 unique_fd intercept_fd;
173
174 CrasherTest();
175 ~CrasherTest();
176
Narayan Kamatha73df602017-05-24 15:07:25 +0100177 void StartIntercept(unique_fd* output_fd, DebuggerdDumpType intercept_type = kDebuggerdTombstone);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700178
179 // Returns -1 if we fail to read a response from tombstoned, otherwise the received return code.
180 void FinishIntercept(int* result);
181
Josh Gao2e7b8e22017-05-04 17:12:57 -0700182 void StartProcess(std::function<void()> function, std::function<pid_t()> forker = fork);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700183 void StartCrasher(const std::string& crash_type);
184 void FinishCrasher();
185 void AssertDeath(int signo);
Peter Collingbourne10e428d2020-07-17 14:49:31 -0700186
187 static void Trap(void* ptr);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700188};
189
190CrasherTest::CrasherTest() {
Elliott Hughese4781d52021-03-17 09:15:15 -0700191 previous_wait_for_debugger = android::base::GetBoolProperty(kWaitForDebuggerKey, false);
192 android::base::SetProperty(kWaitForDebuggerKey, "0");
193
194 // Clear the old property too, just in case someone's been using it
195 // on this device. (We only document the new name, but we still support
196 // the old name so we don't break anyone's existing setups.)
197 android::base::SetProperty("debug.debuggerd.wait_for_gdb", "0");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700198}
199
200CrasherTest::~CrasherTest() {
201 if (crasher_pid != -1) {
202 kill(crasher_pid, SIGKILL);
203 int status;
Christopher Ferris172b0a02019-09-18 17:48:30 -0700204 TEMP_FAILURE_RETRY(waitpid(crasher_pid, &status, WUNTRACED));
Josh Gaocbe70cb2016-10-18 18:17:52 -0700205 }
206
Elliott Hughese4781d52021-03-17 09:15:15 -0700207 android::base::SetProperty(kWaitForDebuggerKey, previous_wait_for_debugger ? "1" : "0");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700208}
209
Narayan Kamatha73df602017-05-24 15:07:25 +0100210void CrasherTest::StartIntercept(unique_fd* output_fd, DebuggerdDumpType intercept_type) {
Josh Gaocbe70cb2016-10-18 18:17:52 -0700211 if (crasher_pid == -1) {
212 FAIL() << "crasher hasn't been started";
213 }
214
Narayan Kamathca5e9082017-06-02 15:42:06 +0100215 InterceptStatus status;
216 tombstoned_intercept(crasher_pid, &this->intercept_fd, output_fd, &status, intercept_type);
217 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700218}
219
220void CrasherTest::FinishIntercept(int* result) {
221 InterceptResponse response;
222
Christopher Ferris11555f02019-09-20 14:18:55 -0700223 ssize_t rc = TIMEOUT(30, read(intercept_fd.get(), &response, sizeof(response)));
Josh Gaocbe70cb2016-10-18 18:17:52 -0700224 if (rc == -1) {
225 FAIL() << "failed to read response from tombstoned: " << strerror(errno);
226 } else if (rc == 0) {
227 *result = -1;
228 } else if (rc != sizeof(response)) {
229 FAIL() << "received packet of unexpected length from tombstoned: expected " << sizeof(response)
230 << ", received " << rc;
231 } else {
Josh Gao460b3362017-03-30 16:40:47 -0700232 *result = response.status == InterceptStatus::kStarted ? 1 : 0;
Josh Gaocbe70cb2016-10-18 18:17:52 -0700233 }
234}
235
Josh Gao2e7b8e22017-05-04 17:12:57 -0700236void CrasherTest::StartProcess(std::function<void()> function, std::function<pid_t()> forker) {
Josh Gaofca7ca32017-01-23 12:05:35 -0800237 unique_fd read_pipe;
Josh Gaocbe70cb2016-10-18 18:17:52 -0700238 unique_fd crasher_read_pipe;
239 if (!Pipe(&crasher_read_pipe, &crasher_pipe)) {
240 FAIL() << "failed to create pipe: " << strerror(errno);
241 }
242
Josh Gao2e7b8e22017-05-04 17:12:57 -0700243 crasher_pid = forker();
Josh Gaocbe70cb2016-10-18 18:17:52 -0700244 if (crasher_pid == -1) {
245 FAIL() << "fork failed: " << strerror(errno);
246 } else if (crasher_pid == 0) {
Josh Gao502cfd22017-02-17 01:39:15 -0800247 char dummy;
248 crasher_pipe.reset();
249 TEMP_FAILURE_RETRY(read(crasher_read_pipe.get(), &dummy, 1));
Josh Gaofca7ca32017-01-23 12:05:35 -0800250 function();
251 _exit(0);
252 }
253}
254
Josh Gaocbe70cb2016-10-18 18:17:52 -0700255void CrasherTest::FinishCrasher() {
256 if (crasher_pipe == -1) {
257 FAIL() << "crasher pipe uninitialized";
258 }
259
Christopher Ferris172b0a02019-09-18 17:48:30 -0700260 ssize_t rc = TEMP_FAILURE_RETRY(write(crasher_pipe.get(), "\n", 1));
Josh Gaocbe70cb2016-10-18 18:17:52 -0700261 if (rc == -1) {
262 FAIL() << "failed to write to crasher pipe: " << strerror(errno);
263 } else if (rc == 0) {
264 FAIL() << "crasher pipe was closed";
265 }
266}
267
268void CrasherTest::AssertDeath(int signo) {
269 int status;
Christopher Ferris11555f02019-09-20 14:18:55 -0700270 pid_t pid = TIMEOUT(30, waitpid(crasher_pid, &status, 0));
Josh Gaocbe70cb2016-10-18 18:17:52 -0700271 if (pid != crasher_pid) {
Christopher Ferrisafc0ff72019-06-26 15:08:51 -0700272 printf("failed to wait for crasher (expected pid %d, return value %d): %s\n", crasher_pid, pid,
273 strerror(errno));
Josh Gao2b2ae0c2017-08-21 14:31:17 -0700274 sleep(100);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700275 FAIL() << "failed to wait for crasher: " << strerror(errno);
276 }
277
Josh Gaoe06f2a42017-04-27 16:50:38 -0700278 if (signo == 0) {
Christopher Ferris67022562021-04-16 13:30:32 -0700279 ASSERT_TRUE(WIFEXITED(status)) << "Terminated due to unexpected signal " << WTERMSIG(status);
Josh Gaoe06f2a42017-04-27 16:50:38 -0700280 ASSERT_EQ(0, WEXITSTATUS(signo));
281 } else {
282 ASSERT_FALSE(WIFEXITED(status));
283 ASSERT_TRUE(WIFSIGNALED(status)) << "crasher didn't terminate via a signal";
284 ASSERT_EQ(signo, WTERMSIG(status));
Josh Gaocbe70cb2016-10-18 18:17:52 -0700285 }
Josh Gaocbe70cb2016-10-18 18:17:52 -0700286 crasher_pid = -1;
287}
288
289static void ConsumeFd(unique_fd fd, std::string* output) {
290 constexpr size_t read_length = PAGE_SIZE;
291 std::string result;
292
293 while (true) {
294 size_t offset = result.size();
295 result.resize(result.size() + PAGE_SIZE);
296 ssize_t rc = TEMP_FAILURE_RETRY(read(fd.get(), &result[offset], read_length));
297 if (rc == -1) {
298 FAIL() << "read failed: " << strerror(errno);
299 } else if (rc == 0) {
300 result.resize(result.size() - PAGE_SIZE);
301 break;
302 }
303
304 result.resize(result.size() - PAGE_SIZE + rc);
305 }
306
307 *output = std::move(result);
308}
309
310TEST_F(CrasherTest, smoke) {
311 int intercept_result;
312 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800313 StartProcess([]() {
314 *reinterpret_cast<volatile char*>(0xdead) = '1';
315 });
316
Josh Gaocbe70cb2016-10-18 18:17:52 -0700317 StartIntercept(&output_fd);
318 FinishCrasher();
319 AssertDeath(SIGSEGV);
320 FinishIntercept(&intercept_result);
321
322 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
323
324 std::string result;
325 ConsumeFd(std::move(output_fd), &result);
326 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\), code 1 \(SEGV_MAPERR\), fault addr 0xdead)");
Peter Collingbourne864f15d2020-09-14 20:27:36 -0700327
328 if (mte_supported()) {
329 // Test that the default TAGGED_ADDR_CTRL value is set.
Peter Collingbourne939d0742021-02-02 19:00:45 -0800330 ASSERT_MATCH(result, R"(tagged_addr_ctrl: 000000000007fff3)");
Peter Collingbourne864f15d2020-09-14 20:27:36 -0700331 }
Josh Gaocbe70cb2016-10-18 18:17:52 -0700332}
333
Peter Collingbournef03af882020-03-20 18:09:00 -0700334TEST_F(CrasherTest, tagged_fault_addr) {
335#if !defined(__aarch64__)
336 GTEST_SKIP() << "Requires aarch64";
337#endif
338 int intercept_result;
339 unique_fd output_fd;
340 StartProcess([]() {
341 *reinterpret_cast<volatile char*>(0x100000000000dead) = '1';
342 });
343
344 StartIntercept(&output_fd);
345 FinishCrasher();
346 AssertDeath(SIGSEGV);
347 FinishIntercept(&intercept_result);
348
349 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
350
351 std::string result;
352 ConsumeFd(std::move(output_fd), &result);
353
354 // The address can either be tagged (new kernels) or untagged (old kernels).
355 ASSERT_MATCH(
356 result,
357 R"(signal 11 \(SIGSEGV\), code 1 \(SEGV_MAPERR\), fault addr (0x100000000000dead|0xdead))");
358}
359
Peter Collingbourne10e428d2020-07-17 14:49:31 -0700360// Marked as weak to prevent the compiler from removing the malloc in the caller. In theory, the
361// compiler could still clobber the argument register before trapping, but that's unlikely.
362__attribute__((weak)) void CrasherTest::Trap(void* ptr ATTRIBUTE_UNUSED) {
363 __builtin_trap();
364}
365
366TEST_F(CrasherTest, heap_addr_in_register) {
367#if defined(__i386__)
368 GTEST_SKIP() << "architecture does not pass arguments in registers";
369#endif
370 int intercept_result;
371 unique_fd output_fd;
372 StartProcess([]() {
373 // Crash with a heap pointer in the first argument register.
374 Trap(malloc(1));
375 });
376
377 StartIntercept(&output_fd);
378 FinishCrasher();
379 int status;
380 ASSERT_EQ(crasher_pid, TIMEOUT(30, waitpid(crasher_pid, &status, 0)));
381 ASSERT_TRUE(WIFSIGNALED(status)) << "crasher didn't terminate via a signal";
382 // Don't test the signal number because different architectures use different signals for
383 // __builtin_trap().
384 FinishIntercept(&intercept_result);
385
386 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
387
388 std::string result;
389 ConsumeFd(std::move(output_fd), &result);
390
391#if defined(__aarch64__)
Peter Collingbourne0ea08c22021-02-05 14:59:08 -0800392 ASSERT_MATCH(result, "memory near x0 \\(\\[anon:");
Peter Collingbourne10e428d2020-07-17 14:49:31 -0700393#elif defined(__arm__)
Peter Collingbourne0ea08c22021-02-05 14:59:08 -0800394 ASSERT_MATCH(result, "memory near r0 \\(\\[anon:");
Peter Collingbourne10e428d2020-07-17 14:49:31 -0700395#elif defined(__x86_64__)
Peter Collingbourne0ea08c22021-02-05 14:59:08 -0800396 ASSERT_MATCH(result, "memory near rdi \\(\\[anon:");
Peter Collingbourne10e428d2020-07-17 14:49:31 -0700397#else
398 ASSERT_TRUE(false) << "unsupported architecture";
399#endif
400}
401
Peter Collingbournecd278072020-12-21 14:08:38 -0800402#if defined(__aarch64__)
Peter Collingbournef8622522020-04-07 14:07:32 -0700403static void SetTagCheckingLevelSync() {
Elliott Hughes03b283a2021-01-15 11:34:26 -0800404 if (mallopt(M_BIONIC_SET_HEAP_TAGGING_LEVEL, M_HEAP_TAGGING_LEVEL_SYNC) == 0) {
Peter Collingbournef8622522020-04-07 14:07:32 -0700405 abort();
406 }
407}
408#endif
409
Mitch Phillips7168a212021-03-09 16:53:23 -0800410// Number of iterations required to reliably guarantee a GWP-ASan crash.
411// GWP-ASan's sample rate is not truly nondeterministic, it initialises a
412// thread-local counter at 2*SampleRate, and decrements on each malloc(). Once
413// the counter reaches zero, we provide a sampled allocation. Then, double that
414// figure to allow for left/right allocation alignment, as this is done randomly
415// without bias.
416#define GWP_ASAN_ITERATIONS_TO_ENSURE_CRASH (0x20000)
417
418struct GwpAsanTestParameters {
419 size_t alloc_size;
420 bool free_before_access;
421 int access_offset;
422 std::string cause_needle; // Needle to be found in the "Cause: [GWP-ASan]" line.
423};
424
425struct GwpAsanCrasherTest : CrasherTest, testing::WithParamInterface<GwpAsanTestParameters> {};
426
427GwpAsanTestParameters gwp_asan_tests[] = {
428 {/* alloc_size */ 7, /* free_before_access */ true, /* access_offset */ 0, "Use After Free, 0 bytes into a 7-byte allocation"},
429 {/* alloc_size */ 7, /* free_before_access */ true, /* access_offset */ 1, "Use After Free, 1 byte into a 7-byte allocation"},
430 {/* alloc_size */ 7, /* free_before_access */ false, /* access_offset */ 16, "Buffer Overflow, 9 bytes right of a 7-byte allocation"},
431 {/* alloc_size */ 16, /* free_before_access */ false, /* access_offset */ -1, "Buffer Underflow, 1 byte left of a 16-byte allocation"},
432};
433
434INSTANTIATE_TEST_SUITE_P(GwpAsanTests, GwpAsanCrasherTest, testing::ValuesIn(gwp_asan_tests));
435
436TEST_P(GwpAsanCrasherTest, gwp_asan_uaf) {
437 if (mte_supported()) {
438 // Skip this test on MTE hardware, as MTE will reliably catch these errors
439 // instead of GWP-ASan.
440 GTEST_SKIP() << "Skipped on MTE.";
441 }
442
443 GwpAsanTestParameters params = GetParam();
444
445 int intercept_result;
446 unique_fd output_fd;
447 StartProcess([&params]() {
448 for (unsigned i = 0; i < GWP_ASAN_ITERATIONS_TO_ENSURE_CRASH; ++i) {
449 volatile char* p = reinterpret_cast<volatile char*>(malloc(params.alloc_size));
450 if (params.free_before_access) free(static_cast<void*>(const_cast<char*>(p)));
451 p[params.access_offset] = 42;
452 if (!params.free_before_access) free(static_cast<void*>(const_cast<char*>(p)));
453 }
454 });
455
456 StartIntercept(&output_fd);
457 FinishCrasher();
458 AssertDeath(SIGSEGV);
459 FinishIntercept(&intercept_result);
460
461 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
462
463 std::string result;
464 ConsumeFd(std::move(output_fd), &result);
465
466 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\), code 2 \(SEGV_ACCERR\))");
467 ASSERT_MATCH(result, R"(Cause: \[GWP-ASan\]: )" + params.cause_needle);
468 if (params.free_before_access) {
469 ASSERT_MATCH(result, R"(deallocated by thread .*
470 #00 pc)");
471 }
472 ASSERT_MATCH(result, R"(allocated by thread .*
473 #00 pc)");
474}
475
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800476struct SizeParamCrasherTest : CrasherTest, testing::WithParamInterface<size_t> {};
477
478INSTANTIATE_TEST_SUITE_P(Sizes, SizeParamCrasherTest, testing::Values(16, 131072));
479
480TEST_P(SizeParamCrasherTest, mte_uaf) {
Peter Collingbournecd278072020-12-21 14:08:38 -0800481#if defined(__aarch64__)
Peter Collingbournef8622522020-04-07 14:07:32 -0700482 if (!mte_supported()) {
483 GTEST_SKIP() << "Requires MTE";
484 }
485
486 int intercept_result;
487 unique_fd output_fd;
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800488 StartProcess([&]() {
Peter Collingbournef8622522020-04-07 14:07:32 -0700489 SetTagCheckingLevelSync();
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800490 volatile int* p = (volatile int*)malloc(GetParam());
Peter Collingbournef8622522020-04-07 14:07:32 -0700491 free((void *)p);
492 p[0] = 42;
493 });
494
495 StartIntercept(&output_fd);
496 FinishCrasher();
497 AssertDeath(SIGSEGV);
498 FinishIntercept(&intercept_result);
499
500 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
501
502 std::string result;
503 ConsumeFd(std::move(output_fd), &result);
504
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800505 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\))");
506 ASSERT_MATCH(result, R"(Cause: \[MTE\]: Use After Free, 0 bytes into a )" +
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800507 std::to_string(GetParam()) + R"(-byte allocation)");
Peter Collingbournebbe69052020-05-08 10:11:19 -0700508 ASSERT_MATCH(result, R"(deallocated by thread .*
509 #00 pc)");
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800510 ASSERT_MATCH(result, R"(allocated by thread .*
511 #00 pc)");
Peter Collingbournef8622522020-04-07 14:07:32 -0700512#else
Peter Collingbournecd278072020-12-21 14:08:38 -0800513 GTEST_SKIP() << "Requires aarch64";
Peter Collingbournef8622522020-04-07 14:07:32 -0700514#endif
515}
516
Peter Collingbournedc476342021-05-12 15:56:43 -0700517TEST_P(SizeParamCrasherTest, mte_oob_uaf) {
518#if defined(__aarch64__)
519 if (!mte_supported()) {
520 GTEST_SKIP() << "Requires MTE";
521 }
522
523 int intercept_result;
524 unique_fd output_fd;
525 StartProcess([&]() {
526 SetTagCheckingLevelSync();
527 volatile int* p = (volatile int*)malloc(GetParam());
528 free((void *)p);
529 p[-1] = 42;
530 });
531
532 StartIntercept(&output_fd);
533 FinishCrasher();
534 AssertDeath(SIGSEGV);
535 FinishIntercept(&intercept_result);
536
537 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
538
539 std::string result;
540 ConsumeFd(std::move(output_fd), &result);
541
542 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\))");
543 ASSERT_NOT_MATCH(result, R"(Cause: \[MTE\]: Use After Free, 4 bytes left)");
544#else
545 GTEST_SKIP() << "Requires aarch64";
546#endif
547}
548
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800549TEST_P(SizeParamCrasherTest, mte_overflow) {
Peter Collingbournecd278072020-12-21 14:08:38 -0800550#if defined(__aarch64__)
Peter Collingbournef8622522020-04-07 14:07:32 -0700551 if (!mte_supported()) {
552 GTEST_SKIP() << "Requires MTE";
553 }
554
555 int intercept_result;
556 unique_fd output_fd;
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800557 StartProcess([&]() {
Peter Collingbournef8622522020-04-07 14:07:32 -0700558 SetTagCheckingLevelSync();
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800559 volatile char* p = (volatile char*)malloc(GetParam());
560 p[GetParam()] = 42;
Peter Collingbournef8622522020-04-07 14:07:32 -0700561 });
562
563 StartIntercept(&output_fd);
564 FinishCrasher();
565 AssertDeath(SIGSEGV);
566 FinishIntercept(&intercept_result);
567
568 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
569
570 std::string result;
571 ConsumeFd(std::move(output_fd), &result);
572
573 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\))");
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800574 ASSERT_MATCH(result, R"(Cause: \[MTE\]: Buffer Overflow, 0 bytes right of a )" +
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800575 std::to_string(GetParam()) + R"(-byte allocation)");
576 ASSERT_MATCH(result, R"(allocated by thread .*
Peter Collingbournebbe69052020-05-08 10:11:19 -0700577 #00 pc)");
Peter Collingbournef8622522020-04-07 14:07:32 -0700578#else
Peter Collingbournecd278072020-12-21 14:08:38 -0800579 GTEST_SKIP() << "Requires aarch64";
Peter Collingbournef8622522020-04-07 14:07:32 -0700580#endif
581}
582
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800583TEST_P(SizeParamCrasherTest, mte_underflow) {
Peter Collingbournecd278072020-12-21 14:08:38 -0800584#if defined(__aarch64__)
Peter Collingbournef8622522020-04-07 14:07:32 -0700585 if (!mte_supported()) {
586 GTEST_SKIP() << "Requires MTE";
587 }
588
589 int intercept_result;
590 unique_fd output_fd;
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800591 StartProcess([&]() {
Peter Collingbournef8622522020-04-07 14:07:32 -0700592 SetTagCheckingLevelSync();
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800593 volatile int* p = (volatile int*)malloc(GetParam());
Peter Collingbournef8622522020-04-07 14:07:32 -0700594 p[-1] = 42;
595 });
596
597 StartIntercept(&output_fd);
598 FinishCrasher();
599 AssertDeath(SIGSEGV);
600 FinishIntercept(&intercept_result);
601
602 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
603
604 std::string result;
605 ConsumeFd(std::move(output_fd), &result);
606
607 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\), code 9 \(SEGV_MTESERR\))");
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800608 ASSERT_MATCH(result, R"(Cause: \[MTE\]: Buffer Underflow, 4 bytes left of a )" +
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800609 std::to_string(GetParam()) + R"(-byte allocation)");
610 ASSERT_MATCH(result, R"(allocated by thread .*
Peter Collingbournebbe69052020-05-08 10:11:19 -0700611 #00 pc)");
Peter Collingbournef8622522020-04-07 14:07:32 -0700612#else
Peter Collingbournecd278072020-12-21 14:08:38 -0800613 GTEST_SKIP() << "Requires aarch64";
Peter Collingbournef8622522020-04-07 14:07:32 -0700614#endif
615}
616
617TEST_F(CrasherTest, mte_multiple_causes) {
Peter Collingbournecd278072020-12-21 14:08:38 -0800618#if defined(__aarch64__)
Peter Collingbournef8622522020-04-07 14:07:32 -0700619 if (!mte_supported()) {
620 GTEST_SKIP() << "Requires MTE";
621 }
622
623 int intercept_result;
624 unique_fd output_fd;
625 StartProcess([]() {
626 SetTagCheckingLevelSync();
627
628 // Make two allocations with the same tag and close to one another. Check for both properties
629 // with a bounds check -- this relies on the fact that only if the allocations have the same tag
630 // would they be measured as closer than 128 bytes to each other. Otherwise they would be about
631 // (some non-zero value << 56) apart.
632 //
633 // The out-of-bounds access will be considered either an overflow of one or an underflow of the
634 // other.
635 std::set<uintptr_t> allocs;
636 for (int i = 0; i != 4096; ++i) {
637 uintptr_t alloc = reinterpret_cast<uintptr_t>(malloc(16));
638 auto it = allocs.insert(alloc).first;
639 if (it != allocs.begin() && *std::prev(it) + 128 > alloc) {
640 *reinterpret_cast<int*>(*std::prev(it) + 16) = 42;
641 }
642 if (std::next(it) != allocs.end() && alloc + 128 > *std::next(it)) {
643 *reinterpret_cast<int*>(alloc + 16) = 42;
644 }
645 }
646 });
647
648 StartIntercept(&output_fd);
649 FinishCrasher();
650 AssertDeath(SIGSEGV);
651 FinishIntercept(&intercept_result);
652
653 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
654
655 std::string result;
656 ConsumeFd(std::move(output_fd), &result);
657
658 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\))");
659 ASSERT_MATCH(
660 result,
661 R"(Note: multiple potential causes for this crash were detected, listing them in decreasing order of probability.)");
662
663 // Adjacent untracked allocations may cause us to see the wrong underflow here (or only
664 // overflows), so we can't match explicitly for an underflow message.
665 ASSERT_MATCH(result, R"(Cause: \[MTE\]: Buffer Overflow, 0 bytes right of a 16-byte allocation)");
666#else
Peter Collingbournecd278072020-12-21 14:08:38 -0800667 GTEST_SKIP() << "Requires aarch64";
Peter Collingbournef8622522020-04-07 14:07:32 -0700668#endif
669}
670
Peter Collingbournecd278072020-12-21 14:08:38 -0800671#if defined(__aarch64__)
Peter Collingbournefe8997a2020-07-20 15:08:52 -0700672static uintptr_t CreateTagMapping() {
673 uintptr_t mapping =
674 reinterpret_cast<uintptr_t>(mmap(nullptr, getpagesize(), PROT_READ | PROT_WRITE | PROT_MTE,
675 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0));
676 if (reinterpret_cast<void*>(mapping) == MAP_FAILED) {
677 return 0;
678 }
679 __asm__ __volatile__(".arch_extension mte; stg %0, [%0]"
680 :
681 : "r"(mapping + (1ULL << 56))
682 : "memory");
683 return mapping;
684}
685#endif
686
687TEST_F(CrasherTest, mte_tag_dump) {
Peter Collingbournecd278072020-12-21 14:08:38 -0800688#if defined(__aarch64__)
Peter Collingbournefe8997a2020-07-20 15:08:52 -0700689 if (!mte_supported()) {
690 GTEST_SKIP() << "Requires MTE";
691 }
692
693 int intercept_result;
694 unique_fd output_fd;
695 StartProcess([&]() {
696 SetTagCheckingLevelSync();
697 Trap(reinterpret_cast<void *>(CreateTagMapping()));
698 });
699
700 StartIntercept(&output_fd);
701 FinishCrasher();
702 AssertDeath(SIGTRAP);
703 FinishIntercept(&intercept_result);
704
705 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
706
707 std::string result;
708 ConsumeFd(std::move(output_fd), &result);
709
710 ASSERT_MATCH(result, R"(memory near x0:
711.*
712.*
713 01.............0 0000000000000000 0000000000000000 ................
714 00.............0)");
715#else
Peter Collingbournecd278072020-12-21 14:08:38 -0800716 GTEST_SKIP() << "Requires aarch64";
Peter Collingbournefe8997a2020-07-20 15:08:52 -0700717#endif
718}
719
Josh Gaocdea7502017-11-01 15:00:40 -0700720TEST_F(CrasherTest, LD_PRELOAD) {
721 int intercept_result;
722 unique_fd output_fd;
723 StartProcess([]() {
724 setenv("LD_PRELOAD", "nonexistent.so", 1);
725 *reinterpret_cast<volatile char*>(0xdead) = '1';
726 });
727
728 StartIntercept(&output_fd);
729 FinishCrasher();
730 AssertDeath(SIGSEGV);
731 FinishIntercept(&intercept_result);
732
733 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
734
735 std::string result;
736 ConsumeFd(std::move(output_fd), &result);
737 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\), code 1 \(SEGV_MAPERR\), fault addr 0xdead)");
738}
739
Josh Gaocbe70cb2016-10-18 18:17:52 -0700740TEST_F(CrasherTest, abort) {
741 int intercept_result;
742 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800743 StartProcess([]() {
744 abort();
745 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700746 StartIntercept(&output_fd);
747 FinishCrasher();
748 AssertDeath(SIGABRT);
749 FinishIntercept(&intercept_result);
750
751 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
752
753 std::string result;
754 ConsumeFd(std::move(output_fd), &result);
Andreas Gampe26cbafb2017-06-22 20:14:43 -0700755 ASSERT_BACKTRACE_FRAME(result, "abort");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700756}
757
758TEST_F(CrasherTest, signal) {
759 int intercept_result;
760 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800761 StartProcess([]() {
Josh Gao2b2ae0c2017-08-21 14:31:17 -0700762 while (true) {
763 sleep(1);
764 }
Josh Gao502cfd22017-02-17 01:39:15 -0800765 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700766 StartIntercept(&output_fd);
Josh Gao2b2ae0c2017-08-21 14:31:17 -0700767 FinishCrasher();
Josh Gaocbe70cb2016-10-18 18:17:52 -0700768 ASSERT_EQ(0, kill(crasher_pid, SIGSEGV));
769
770 AssertDeath(SIGSEGV);
771 FinishIntercept(&intercept_result);
772
773 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
774
775 std::string result;
776 ConsumeFd(std::move(output_fd), &result);
Elliott Hughes89722702018-05-02 10:47:00 -0700777 ASSERT_MATCH(
778 result,
779 R"(signal 11 \(SIGSEGV\), code 0 \(SI_USER from pid \d+, uid \d+\), fault addr --------)");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700780 ASSERT_MATCH(result, R"(backtrace:)");
781}
782
783TEST_F(CrasherTest, abort_message) {
784 int intercept_result;
785 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800786 StartProcess([]() {
Josh Gao1cc7bd82018-02-13 13:16:17 -0800787 // Arrived at experimentally;
788 // logd truncates at 4062.
789 // strlen("Abort message: ''") is 17.
790 // That's 4045, but we also want a NUL.
791 char buf[4045 + 1];
792 memset(buf, 'x', sizeof(buf));
793 buf[sizeof(buf) - 1] = '\0';
794 android_set_abort_message(buf);
Josh Gao502cfd22017-02-17 01:39:15 -0800795 abort();
796 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700797 StartIntercept(&output_fd);
798 FinishCrasher();
799 AssertDeath(SIGABRT);
800 FinishIntercept(&intercept_result);
801
802 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
803
804 std::string result;
805 ConsumeFd(std::move(output_fd), &result);
Josh Gao1cc7bd82018-02-13 13:16:17 -0800806 ASSERT_MATCH(result, R"(Abort message: 'x{4045}')");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700807}
808
Josh Gaoe06f2a42017-04-27 16:50:38 -0700809TEST_F(CrasherTest, abort_message_backtrace) {
810 int intercept_result;
811 unique_fd output_fd;
812 StartProcess([]() {
813 android_set_abort_message("not actually aborting");
Josh Gaoa48b41b2019-12-13 14:11:04 -0800814 raise(BIONIC_SIGNAL_DEBUGGER);
Josh Gaoe06f2a42017-04-27 16:50:38 -0700815 exit(0);
816 });
817 StartIntercept(&output_fd);
818 FinishCrasher();
819 AssertDeath(0);
820 FinishIntercept(&intercept_result);
821
822 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
823
824 std::string result;
825 ConsumeFd(std::move(output_fd), &result);
826 ASSERT_NOT_MATCH(result, R"(Abort message:)");
827}
828
Josh Gaocbe70cb2016-10-18 18:17:52 -0700829TEST_F(CrasherTest, intercept_timeout) {
830 int intercept_result;
831 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800832 StartProcess([]() {
833 abort();
834 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700835 StartIntercept(&output_fd);
836
837 // Don't let crasher finish until we timeout.
838 FinishIntercept(&intercept_result);
839
840 ASSERT_NE(1, intercept_result) << "tombstoned reported success? (intercept_result = "
841 << intercept_result << ")";
842
843 FinishCrasher();
844 AssertDeath(SIGABRT);
845}
846
Elliott Hughese4781d52021-03-17 09:15:15 -0700847TEST_F(CrasherTest, wait_for_debugger) {
848 if (!android::base::SetProperty(kWaitForDebuggerKey, "1")) {
849 FAIL() << "failed to enable wait_for_debugger";
Josh Gaocbe70cb2016-10-18 18:17:52 -0700850 }
851 sleep(1);
852
Josh Gao502cfd22017-02-17 01:39:15 -0800853 StartProcess([]() {
854 abort();
855 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700856 FinishCrasher();
857
858 int status;
Christopher Ferris172b0a02019-09-18 17:48:30 -0700859 ASSERT_EQ(crasher_pid, TEMP_FAILURE_RETRY(waitpid(crasher_pid, &status, WUNTRACED)));
Josh Gaocbe70cb2016-10-18 18:17:52 -0700860 ASSERT_TRUE(WIFSTOPPED(status));
861 ASSERT_EQ(SIGSTOP, WSTOPSIG(status));
862
863 ASSERT_EQ(0, kill(crasher_pid, SIGCONT));
864
865 AssertDeath(SIGABRT);
866}
867
Josh Gaocbe70cb2016-10-18 18:17:52 -0700868TEST_F(CrasherTest, backtrace) {
869 std::string result;
870 int intercept_result;
871 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800872
873 StartProcess([]() {
874 abort();
875 });
Narayan Kamatha73df602017-05-24 15:07:25 +0100876 StartIntercept(&output_fd, kDebuggerdNativeBacktrace);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700877
878 std::this_thread::sleep_for(500ms);
879
880 sigval val;
881 val.sival_int = 1;
Josh Gaoa48b41b2019-12-13 14:11:04 -0800882 ASSERT_EQ(0, sigqueue(crasher_pid, BIONIC_SIGNAL_DEBUGGER, val)) << strerror(errno);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700883 FinishIntercept(&intercept_result);
884 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
885 ConsumeFd(std::move(output_fd), &result);
Jaesung Chung58778e12017-06-15 18:20:34 +0900886 ASSERT_BACKTRACE_FRAME(result, "read");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700887
888 int status;
889 ASSERT_EQ(0, waitpid(crasher_pid, &status, WNOHANG | WUNTRACED));
890
891 StartIntercept(&output_fd);
892 FinishCrasher();
893 AssertDeath(SIGABRT);
894 FinishIntercept(&intercept_result);
895 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
896 ConsumeFd(std::move(output_fd), &result);
Andreas Gampe26cbafb2017-06-22 20:14:43 -0700897 ASSERT_BACKTRACE_FRAME(result, "abort");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700898}
Josh Gaofca7ca32017-01-23 12:05:35 -0800899
900TEST_F(CrasherTest, PR_SET_DUMPABLE_0_crash) {
Josh Gao502cfd22017-02-17 01:39:15 -0800901 int intercept_result;
902 unique_fd output_fd;
Josh Gaofca7ca32017-01-23 12:05:35 -0800903 StartProcess([]() {
904 prctl(PR_SET_DUMPABLE, 0);
Josh Gao502cfd22017-02-17 01:39:15 -0800905 abort();
Josh Gaofca7ca32017-01-23 12:05:35 -0800906 });
Josh Gao502cfd22017-02-17 01:39:15 -0800907
908 StartIntercept(&output_fd);
909 FinishCrasher();
910 AssertDeath(SIGABRT);
911 FinishIntercept(&intercept_result);
912
913 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
914
915 std::string result;
916 ConsumeFd(std::move(output_fd), &result);
Andreas Gampe26cbafb2017-06-22 20:14:43 -0700917 ASSERT_BACKTRACE_FRAME(result, "abort");
Josh Gaofca7ca32017-01-23 12:05:35 -0800918}
919
Josh Gao502cfd22017-02-17 01:39:15 -0800920TEST_F(CrasherTest, capabilities) {
921 ASSERT_EQ(0U, getuid()) << "capability test requires root";
922
Josh Gaofca7ca32017-01-23 12:05:35 -0800923 StartProcess([]() {
Josh Gao502cfd22017-02-17 01:39:15 -0800924 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) != 0) {
925 err(1, "failed to set PR_SET_KEEPCAPS");
926 }
927
928 if (setresuid(1, 1, 1) != 0) {
929 err(1, "setresuid failed");
930 }
931
932 __user_cap_header_struct capheader;
933 __user_cap_data_struct capdata[2];
934 memset(&capheader, 0, sizeof(capheader));
935 memset(&capdata, 0, sizeof(capdata));
936
937 capheader.version = _LINUX_CAPABILITY_VERSION_3;
938 capheader.pid = 0;
939
940 // Turn on every third capability.
941 static_assert(CAP_LAST_CAP > 33, "CAP_LAST_CAP <= 32");
942 for (int i = 0; i < CAP_LAST_CAP; i += 3) {
943 capdata[CAP_TO_INDEX(i)].permitted |= CAP_TO_MASK(i);
944 capdata[CAP_TO_INDEX(i)].effective |= CAP_TO_MASK(i);
945 }
946
947 // Make sure CAP_SYS_PTRACE is off.
948 capdata[CAP_TO_INDEX(CAP_SYS_PTRACE)].permitted &= ~(CAP_TO_MASK(CAP_SYS_PTRACE));
949 capdata[CAP_TO_INDEX(CAP_SYS_PTRACE)].effective &= ~(CAP_TO_MASK(CAP_SYS_PTRACE));
950
951 if (capset(&capheader, &capdata[0]) != 0) {
952 err(1, "capset failed");
953 }
954
955 if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_CLEAR_ALL, 0, 0, 0) != 0) {
956 err(1, "failed to drop ambient capabilities");
957 }
958
Josh Gaoa5199a92017-04-03 13:18:34 -0700959 pthread_setname_np(pthread_self(), "thread_name");
Josh Gao502cfd22017-02-17 01:39:15 -0800960 raise(SIGSYS);
Josh Gaofca7ca32017-01-23 12:05:35 -0800961 });
Josh Gao502cfd22017-02-17 01:39:15 -0800962
963 unique_fd output_fd;
964 StartIntercept(&output_fd);
965 FinishCrasher();
966 AssertDeath(SIGSYS);
967
968 std::string result;
969 int intercept_result;
970 FinishIntercept(&intercept_result);
971 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
972 ConsumeFd(std::move(output_fd), &result);
Josh Gaoa5199a92017-04-03 13:18:34 -0700973 ASSERT_MATCH(result, R"(name: thread_name\s+>>> .+debuggerd_test(32|64) <<<)");
Jaesung Chung58778e12017-06-15 18:20:34 +0900974 ASSERT_BACKTRACE_FRAME(result, "tgkill");
Josh Gaofca7ca32017-01-23 12:05:35 -0800975}
Josh Gaoc3c8c022017-02-13 16:36:18 -0800976
Josh Gao2e7b8e22017-05-04 17:12:57 -0700977TEST_F(CrasherTest, fake_pid) {
978 int intercept_result;
979 unique_fd output_fd;
980
981 // Prime the getpid/gettid caches.
982 UNUSED(getpid());
983 UNUSED(gettid());
984
985 std::function<pid_t()> clone_fn = []() {
986 return syscall(__NR_clone, SIGCHLD, nullptr, nullptr, nullptr, nullptr);
987 };
988 StartProcess(
989 []() {
990 ASSERT_NE(getpid(), syscall(__NR_getpid));
991 ASSERT_NE(gettid(), syscall(__NR_gettid));
992 raise(SIGSEGV);
993 },
994 clone_fn);
995
996 StartIntercept(&output_fd);
997 FinishCrasher();
998 AssertDeath(SIGSEGV);
999 FinishIntercept(&intercept_result);
1000
1001 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1002
1003 std::string result;
1004 ConsumeFd(std::move(output_fd), &result);
Jaesung Chung58778e12017-06-15 18:20:34 +09001005 ASSERT_BACKTRACE_FRAME(result, "tgkill");
Josh Gao2e7b8e22017-05-04 17:12:57 -07001006}
1007
Josh Gaoe04ca272018-01-16 15:38:17 -08001008static const char* const kDebuggerdSeccompPolicy =
1009 "/system/etc/seccomp_policy/crash_dump." ABI_STRING ".policy";
1010
Josh Gao70adac62018-02-22 11:38:33 -08001011static pid_t seccomp_fork_impl(void (*prejail)()) {
Josh Gao6f9eeec2018-09-12 13:55:47 -07001012 std::string policy;
1013 if (!android::base::ReadFileToString(kDebuggerdSeccompPolicy, &policy)) {
1014 PLOG(FATAL) << "failed to read policy file";
1015 }
1016
1017 // Allow a bunch of syscalls used by the tests.
1018 policy += "\nclone: 1";
1019 policy += "\nsigaltstack: 1";
1020 policy += "\nnanosleep: 1";
Christopher Ferrisab606682019-09-17 15:31:47 -07001021 policy += "\ngetrlimit: 1";
1022 policy += "\nugetrlimit: 1";
Josh Gao6f9eeec2018-09-12 13:55:47 -07001023
1024 FILE* tmp_file = tmpfile();
1025 if (!tmp_file) {
1026 PLOG(FATAL) << "tmpfile failed";
1027 }
1028
Christopher Ferris172b0a02019-09-18 17:48:30 -07001029 unique_fd tmp_fd(TEMP_FAILURE_RETRY(dup(fileno(tmp_file))));
Josh Gao6f9eeec2018-09-12 13:55:47 -07001030 if (!android::base::WriteStringToFd(policy, tmp_fd.get())) {
1031 PLOG(FATAL) << "failed to write policy to tmpfile";
1032 }
1033
1034 if (lseek(tmp_fd.get(), 0, SEEK_SET) != 0) {
1035 PLOG(FATAL) << "failed to seek tmp_fd";
Josh Gaoe04ca272018-01-16 15:38:17 -08001036 }
1037
1038 ScopedMinijail jail{minijail_new()};
1039 if (!jail) {
1040 LOG(FATAL) << "failed to create minijail";
1041 }
1042
1043 minijail_no_new_privs(jail.get());
1044 minijail_log_seccomp_filter_failures(jail.get());
1045 minijail_use_seccomp_filter(jail.get());
Josh Gao6f9eeec2018-09-12 13:55:47 -07001046 minijail_parse_seccomp_filters_from_fd(jail.get(), tmp_fd.release());
Josh Gaoe04ca272018-01-16 15:38:17 -08001047
1048 pid_t result = fork();
1049 if (result == -1) {
1050 return result;
1051 } else if (result != 0) {
1052 return result;
1053 }
1054
1055 // Spawn and detach a thread that spins forever.
1056 std::atomic<bool> thread_ready(false);
1057 std::thread thread([&jail, &thread_ready]() {
1058 minijail_enter(jail.get());
1059 thread_ready = true;
1060 for (;;)
1061 ;
1062 });
1063 thread.detach();
1064
1065 while (!thread_ready) {
1066 continue;
1067 }
1068
Josh Gao70adac62018-02-22 11:38:33 -08001069 if (prejail) {
1070 prejail();
1071 }
1072
Josh Gaoe04ca272018-01-16 15:38:17 -08001073 minijail_enter(jail.get());
1074 return result;
1075}
1076
Josh Gao70adac62018-02-22 11:38:33 -08001077static pid_t seccomp_fork() {
1078 return seccomp_fork_impl(nullptr);
1079}
1080
Josh Gaoe04ca272018-01-16 15:38:17 -08001081TEST_F(CrasherTest, seccomp_crash) {
1082 int intercept_result;
1083 unique_fd output_fd;
1084
1085 StartProcess([]() { abort(); }, &seccomp_fork);
1086
1087 StartIntercept(&output_fd);
1088 FinishCrasher();
1089 AssertDeath(SIGABRT);
1090 FinishIntercept(&intercept_result);
1091 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1092
1093 std::string result;
1094 ConsumeFd(std::move(output_fd), &result);
1095 ASSERT_BACKTRACE_FRAME(result, "abort");
1096}
1097
Josh Gao70adac62018-02-22 11:38:33 -08001098static pid_t seccomp_fork_rlimit() {
1099 return seccomp_fork_impl([]() {
1100 struct rlimit rlim = {
1101 .rlim_cur = 512 * 1024 * 1024,
1102 .rlim_max = 512 * 1024 * 1024,
1103 };
1104
1105 if (setrlimit(RLIMIT_AS, &rlim) != 0) {
1106 raise(SIGINT);
1107 }
1108 });
1109}
1110
1111TEST_F(CrasherTest, seccomp_crash_oom) {
1112 int intercept_result;
1113 unique_fd output_fd;
1114
1115 StartProcess(
1116 []() {
1117 std::vector<void*> vec;
1118 for (int i = 0; i < 512; ++i) {
1119 char* buf = static_cast<char*>(malloc(1024 * 1024));
1120 if (!buf) {
1121 abort();
1122 }
1123 memset(buf, 0xff, 1024 * 1024);
1124 vec.push_back(buf);
1125 }
1126 },
1127 &seccomp_fork_rlimit);
1128
1129 StartIntercept(&output_fd);
1130 FinishCrasher();
1131 AssertDeath(SIGABRT);
1132 FinishIntercept(&intercept_result);
1133 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1134
1135 // We can't actually generate a backtrace, just make sure that the process terminates.
1136}
1137
Josh Gaoe04ca272018-01-16 15:38:17 -08001138__attribute__((noinline)) extern "C" bool raise_debugger_signal(DebuggerdDumpType dump_type) {
1139 siginfo_t siginfo;
1140 siginfo.si_code = SI_QUEUE;
1141 siginfo.si_pid = getpid();
1142 siginfo.si_uid = getuid();
1143
1144 if (dump_type != kDebuggerdNativeBacktrace && dump_type != kDebuggerdTombstone) {
1145 PLOG(FATAL) << "invalid dump type";
1146 }
1147
1148 siginfo.si_value.sival_int = dump_type == kDebuggerdNativeBacktrace;
1149
Josh Gaoa48b41b2019-12-13 14:11:04 -08001150 if (syscall(__NR_rt_tgsigqueueinfo, getpid(), gettid(), BIONIC_SIGNAL_DEBUGGER, &siginfo) != 0) {
Josh Gaoe04ca272018-01-16 15:38:17 -08001151 PLOG(ERROR) << "libdebuggerd_client: failed to send signal to self";
1152 return false;
1153 }
1154
1155 return true;
1156}
1157
1158TEST_F(CrasherTest, seccomp_tombstone) {
1159 int intercept_result;
1160 unique_fd output_fd;
1161
1162 static const auto dump_type = kDebuggerdTombstone;
1163 StartProcess(
1164 []() {
1165 raise_debugger_signal(dump_type);
1166 _exit(0);
1167 },
1168 &seccomp_fork);
1169
1170 StartIntercept(&output_fd, dump_type);
1171 FinishCrasher();
1172 AssertDeath(0);
1173 FinishIntercept(&intercept_result);
1174 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1175
1176 std::string result;
1177 ConsumeFd(std::move(output_fd), &result);
1178 ASSERT_BACKTRACE_FRAME(result, "raise_debugger_signal");
1179}
1180
Josh Gao6f9eeec2018-09-12 13:55:47 -07001181extern "C" void foo() {
1182 LOG(INFO) << "foo";
1183 std::this_thread::sleep_for(1s);
1184}
1185
1186extern "C" void bar() {
1187 LOG(INFO) << "bar";
1188 std::this_thread::sleep_for(1s);
1189}
1190
Josh Gaoe04ca272018-01-16 15:38:17 -08001191TEST_F(CrasherTest, seccomp_backtrace) {
1192 int intercept_result;
1193 unique_fd output_fd;
1194
1195 static const auto dump_type = kDebuggerdNativeBacktrace;
1196 StartProcess(
1197 []() {
Josh Gao6f9eeec2018-09-12 13:55:47 -07001198 std::thread a(foo);
1199 std::thread b(bar);
1200
1201 std::this_thread::sleep_for(100ms);
1202
Josh Gaoe04ca272018-01-16 15:38:17 -08001203 raise_debugger_signal(dump_type);
1204 _exit(0);
1205 },
1206 &seccomp_fork);
1207
1208 StartIntercept(&output_fd, dump_type);
1209 FinishCrasher();
1210 AssertDeath(0);
1211 FinishIntercept(&intercept_result);
1212 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1213
1214 std::string result;
1215 ConsumeFd(std::move(output_fd), &result);
1216 ASSERT_BACKTRACE_FRAME(result, "raise_debugger_signal");
Josh Gao6f9eeec2018-09-12 13:55:47 -07001217 ASSERT_BACKTRACE_FRAME(result, "foo");
1218 ASSERT_BACKTRACE_FRAME(result, "bar");
Josh Gaoe04ca272018-01-16 15:38:17 -08001219}
1220
1221TEST_F(CrasherTest, seccomp_crash_logcat) {
1222 StartProcess([]() { abort(); }, &seccomp_fork);
1223 FinishCrasher();
1224
1225 // Make sure we don't get SIGSYS when trying to dump a crash to logcat.
1226 AssertDeath(SIGABRT);
1227}
1228
Josh Gaofd13bf02017-08-18 15:37:26 -07001229TEST_F(CrasherTest, competing_tracer) {
1230 int intercept_result;
1231 unique_fd output_fd;
1232 StartProcess([]() {
Josh Gao2b2ae0c2017-08-21 14:31:17 -07001233 raise(SIGABRT);
Josh Gaofd13bf02017-08-18 15:37:26 -07001234 });
1235
1236 StartIntercept(&output_fd);
Josh Gaofd13bf02017-08-18 15:37:26 -07001237
1238 ASSERT_EQ(0, ptrace(PTRACE_SEIZE, crasher_pid, 0, 0));
Josh Gao2b2ae0c2017-08-21 14:31:17 -07001239 FinishCrasher();
Josh Gaofd13bf02017-08-18 15:37:26 -07001240
1241 int status;
Christopher Ferris172b0a02019-09-18 17:48:30 -07001242 ASSERT_EQ(crasher_pid, TEMP_FAILURE_RETRY(waitpid(crasher_pid, &status, 0)));
Josh Gaofd13bf02017-08-18 15:37:26 -07001243 ASSERT_TRUE(WIFSTOPPED(status));
1244 ASSERT_EQ(SIGABRT, WSTOPSIG(status));
1245
1246 ASSERT_EQ(0, ptrace(PTRACE_CONT, crasher_pid, 0, SIGABRT));
1247 FinishIntercept(&intercept_result);
1248 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1249
1250 std::string result;
1251 ConsumeFd(std::move(output_fd), &result);
1252 std::string regex = R"(failed to attach to thread \d+, already traced by )";
1253 regex += std::to_string(gettid());
1254 regex += R"( \(.+debuggerd_test)";
1255 ASSERT_MATCH(result, regex.c_str());
1256
Christopher Ferris172b0a02019-09-18 17:48:30 -07001257 ASSERT_EQ(crasher_pid, TEMP_FAILURE_RETRY(waitpid(crasher_pid, &status, 0)));
Josh Gao2b2ae0c2017-08-21 14:31:17 -07001258 ASSERT_TRUE(WIFSTOPPED(status));
1259 ASSERT_EQ(SIGABRT, WSTOPSIG(status));
1260
Josh Gaofd13bf02017-08-18 15:37:26 -07001261 ASSERT_EQ(0, ptrace(PTRACE_DETACH, crasher_pid, 0, SIGABRT));
1262 AssertDeath(SIGABRT);
1263}
1264
Josh Gaobf06a402018-08-27 16:34:01 -07001265TEST_F(CrasherTest, fdsan_warning_abort_message) {
1266 int intercept_result;
1267 unique_fd output_fd;
1268
1269 StartProcess([]() {
1270 android_fdsan_set_error_level(ANDROID_FDSAN_ERROR_LEVEL_WARN_ONCE);
Christopher Ferris172b0a02019-09-18 17:48:30 -07001271 unique_fd fd(TEMP_FAILURE_RETRY(open("/dev/null", O_RDONLY | O_CLOEXEC)));
Josh Gaobf06a402018-08-27 16:34:01 -07001272 if (fd == -1) {
1273 abort();
1274 }
1275 close(fd.get());
1276 _exit(0);
1277 });
1278
1279 StartIntercept(&output_fd);
1280 FinishCrasher();
1281 AssertDeath(0);
1282 FinishIntercept(&intercept_result);
1283 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1284
1285 std::string result;
1286 ConsumeFd(std::move(output_fd), &result);
1287 ASSERT_MATCH(result, "Abort message: 'attempted to close");
1288}
1289
Josh Gaoc3c8c022017-02-13 16:36:18 -08001290TEST(crash_dump, zombie) {
1291 pid_t forkpid = fork();
1292
Josh Gaoc3c8c022017-02-13 16:36:18 -08001293 pid_t rc;
1294 int status;
1295
1296 if (forkpid == 0) {
1297 errno = 0;
1298 rc = waitpid(-1, &status, WNOHANG | __WALL | __WNOTHREAD);
1299 if (rc != -1 || errno != ECHILD) {
1300 errx(2, "first waitpid returned %d (%s), expected failure with ECHILD", rc, strerror(errno));
1301 }
1302
Josh Gaoa48b41b2019-12-13 14:11:04 -08001303 raise(BIONIC_SIGNAL_DEBUGGER);
Josh Gaoc3c8c022017-02-13 16:36:18 -08001304
1305 errno = 0;
Christopher Ferris172b0a02019-09-18 17:48:30 -07001306 rc = TEMP_FAILURE_RETRY(waitpid(-1, &status, __WALL | __WNOTHREAD));
Josh Gaoc3c8c022017-02-13 16:36:18 -08001307 if (rc != -1 || errno != ECHILD) {
1308 errx(2, "second waitpid returned %d (%s), expected failure with ECHILD", rc, strerror(errno));
1309 }
1310 _exit(0);
1311 } else {
Christopher Ferris172b0a02019-09-18 17:48:30 -07001312 rc = TEMP_FAILURE_RETRY(waitpid(forkpid, &status, 0));
Josh Gaoc3c8c022017-02-13 16:36:18 -08001313 ASSERT_EQ(forkpid, rc);
1314 ASSERT_TRUE(WIFEXITED(status));
1315 ASSERT_EQ(0, WEXITSTATUS(status));
1316 }
1317}
Josh Gao352a8452017-03-30 16:46:21 -07001318
1319TEST(tombstoned, no_notify) {
1320 // Do this a few times.
1321 for (int i = 0; i < 3; ++i) {
1322 pid_t pid = 123'456'789 + i;
1323
1324 unique_fd intercept_fd, output_fd;
Narayan Kamathca5e9082017-06-02 15:42:06 +01001325 InterceptStatus status;
1326 tombstoned_intercept(pid, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
1327 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gao352a8452017-03-30 16:46:21 -07001328
1329 {
1330 unique_fd tombstoned_socket, input_fd;
Narayan Kamatha73df602017-05-24 15:07:25 +01001331 ASSERT_TRUE(tombstoned_connect(pid, &tombstoned_socket, &input_fd, kDebuggerdTombstone));
Josh Gao352a8452017-03-30 16:46:21 -07001332 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), &pid, sizeof(pid)));
1333 }
1334
1335 pid_t read_pid;
1336 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), &read_pid, sizeof(read_pid)));
1337 ASSERT_EQ(read_pid, pid);
1338 }
1339}
1340
1341TEST(tombstoned, stress) {
1342 // Spawn threads to simultaneously do a bunch of failing dumps and a bunch of successful dumps.
1343 static constexpr int kDumpCount = 100;
1344
1345 std::atomic<bool> start(false);
1346 std::vector<std::thread> threads;
1347 threads.emplace_back([&start]() {
1348 while (!start) {
1349 continue;
1350 }
1351
1352 // Use a way out of range pid, to avoid stomping on an actual process.
1353 pid_t pid_base = 1'000'000;
1354
1355 for (int dump = 0; dump < kDumpCount; ++dump) {
1356 pid_t pid = pid_base + dump;
1357
1358 unique_fd intercept_fd, output_fd;
Narayan Kamathca5e9082017-06-02 15:42:06 +01001359 InterceptStatus status;
1360 tombstoned_intercept(pid, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
1361 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gao352a8452017-03-30 16:46:21 -07001362
1363 // Pretend to crash, and then immediately close the socket.
1364 unique_fd sockfd(socket_local_client(kTombstonedCrashSocketName,
1365 ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_SEQPACKET));
1366 if (sockfd == -1) {
1367 FAIL() << "failed to connect to tombstoned: " << strerror(errno);
1368 }
1369 TombstonedCrashPacket packet = {};
1370 packet.packet_type = CrashPacketType::kDumpRequest;
1371 packet.packet.dump_request.pid = pid;
1372 if (TEMP_FAILURE_RETRY(write(sockfd, &packet, sizeof(packet))) != sizeof(packet)) {
1373 FAIL() << "failed to write to tombstoned: " << strerror(errno);
1374 }
1375
1376 continue;
1377 }
1378 });
1379
1380 threads.emplace_back([&start]() {
1381 while (!start) {
1382 continue;
1383 }
1384
1385 // Use a way out of range pid, to avoid stomping on an actual process.
1386 pid_t pid_base = 2'000'000;
1387
1388 for (int dump = 0; dump < kDumpCount; ++dump) {
1389 pid_t pid = pid_base + dump;
1390
1391 unique_fd intercept_fd, output_fd;
Narayan Kamathca5e9082017-06-02 15:42:06 +01001392 InterceptStatus status;
1393 tombstoned_intercept(pid, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
1394 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gao352a8452017-03-30 16:46:21 -07001395
1396 {
1397 unique_fd tombstoned_socket, input_fd;
Narayan Kamatha73df602017-05-24 15:07:25 +01001398 ASSERT_TRUE(tombstoned_connect(pid, &tombstoned_socket, &input_fd, kDebuggerdTombstone));
Josh Gao352a8452017-03-30 16:46:21 -07001399 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), &pid, sizeof(pid)));
1400 tombstoned_notify_completion(tombstoned_socket.get());
1401 }
1402
1403 // TODO: Fix the race that requires this sleep.
1404 std::this_thread::sleep_for(50ms);
1405
1406 pid_t read_pid;
1407 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), &read_pid, sizeof(read_pid)));
1408 ASSERT_EQ(read_pid, pid);
1409 }
1410 });
1411
1412 start = true;
1413
1414 for (std::thread& thread : threads) {
1415 thread.join();
1416 }
1417}
Narayan Kamathca5e9082017-06-02 15:42:06 +01001418
1419TEST(tombstoned, java_trace_intercept_smoke) {
1420 // Using a "real" PID is a little dangerous here - if the test fails
1421 // or crashes, we might end up getting a bogus / unreliable stack
1422 // trace.
1423 const pid_t self = getpid();
1424
1425 unique_fd intercept_fd, output_fd;
1426 InterceptStatus status;
1427 tombstoned_intercept(self, &intercept_fd, &output_fd, &status, kDebuggerdJavaBacktrace);
1428 ASSERT_EQ(InterceptStatus::kRegistered, status);
1429
Josh Gao76e1e302021-01-26 15:53:11 -08001430 // First connect to tombstoned requesting a native tombstone. This
Narayan Kamathca5e9082017-06-02 15:42:06 +01001431 // should result in a "regular" FD and not the installed intercept.
1432 const char native[] = "native";
1433 unique_fd tombstoned_socket, input_fd;
Josh Gao76e1e302021-01-26 15:53:11 -08001434 ASSERT_TRUE(tombstoned_connect(self, &tombstoned_socket, &input_fd, kDebuggerdTombstone));
Narayan Kamathca5e9082017-06-02 15:42:06 +01001435 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), native, sizeof(native)));
1436 tombstoned_notify_completion(tombstoned_socket.get());
1437
1438 // Then, connect to tombstoned asking for a java backtrace. This *should*
1439 // trigger the intercept.
1440 const char java[] = "java";
1441 ASSERT_TRUE(tombstoned_connect(self, &tombstoned_socket, &input_fd, kDebuggerdJavaBacktrace));
1442 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), java, sizeof(java)));
1443 tombstoned_notify_completion(tombstoned_socket.get());
1444
1445 char outbuf[sizeof(java)];
1446 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), outbuf, sizeof(outbuf)));
1447 ASSERT_STREQ("java", outbuf);
1448}
1449
1450TEST(tombstoned, multiple_intercepts) {
1451 const pid_t fake_pid = 1'234'567;
1452 unique_fd intercept_fd, output_fd;
1453 InterceptStatus status;
1454 tombstoned_intercept(fake_pid, &intercept_fd, &output_fd, &status, kDebuggerdJavaBacktrace);
1455 ASSERT_EQ(InterceptStatus::kRegistered, status);
1456
1457 unique_fd intercept_fd_2, output_fd_2;
1458 tombstoned_intercept(fake_pid, &intercept_fd_2, &output_fd_2, &status, kDebuggerdNativeBacktrace);
1459 ASSERT_EQ(InterceptStatus::kFailedAlreadyRegistered, status);
1460}
1461
1462TEST(tombstoned, intercept_any) {
1463 const pid_t fake_pid = 1'234'567;
1464
1465 unique_fd intercept_fd, output_fd;
1466 InterceptStatus status;
1467 tombstoned_intercept(fake_pid, &intercept_fd, &output_fd, &status, kDebuggerdNativeBacktrace);
1468 ASSERT_EQ(InterceptStatus::kRegistered, status);
1469
1470 const char any[] = "any";
1471 unique_fd tombstoned_socket, input_fd;
1472 ASSERT_TRUE(tombstoned_connect(fake_pid, &tombstoned_socket, &input_fd, kDebuggerdAnyIntercept));
1473 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), any, sizeof(any)));
1474 tombstoned_notify_completion(tombstoned_socket.get());
1475
1476 char outbuf[sizeof(any)];
1477 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), outbuf, sizeof(outbuf)));
1478 ASSERT_STREQ("any", outbuf);
1479}
Josh Gao2b22ae12018-09-12 14:51:03 -07001480
1481TEST(tombstoned, interceptless_backtrace) {
1482 // Generate 50 backtraces, and then check to see that we haven't created 50 new tombstones.
1483 auto get_tombstone_timestamps = []() -> std::map<int, time_t> {
1484 std::map<int, time_t> result;
1485 for (int i = 0; i < 99; ++i) {
1486 std::string path = android::base::StringPrintf("/data/tombstones/tombstone_%02d", i);
1487 struct stat st;
1488 if (stat(path.c_str(), &st) == 0) {
1489 result[i] = st.st_mtim.tv_sec;
1490 }
1491 }
1492 return result;
1493 };
1494
1495 auto before = get_tombstone_timestamps();
1496 for (int i = 0; i < 50; ++i) {
1497 raise_debugger_signal(kDebuggerdNativeBacktrace);
1498 }
1499 auto after = get_tombstone_timestamps();
1500
1501 int diff = 0;
1502 for (int i = 0; i < 99; ++i) {
1503 if (after.count(i) == 0) {
1504 continue;
1505 }
1506 if (before.count(i) == 0) {
1507 ++diff;
1508 continue;
1509 }
1510 if (before[i] != after[i]) {
1511 ++diff;
1512 }
1513 }
1514
1515 // We can't be sure that nothing's crash looping in the background.
1516 // This should be good enough, though...
1517 ASSERT_LT(diff, 10) << "too many new tombstones; is something crashing in the background?";
1518}
Christopher Ferris481e8372019-07-15 17:13:24 -07001519
1520static __attribute__((__noinline__)) void overflow_stack(void* p) {
1521 void* buf[1];
1522 buf[0] = p;
1523 static volatile void* global = buf;
1524 if (global) {
1525 global = buf;
1526 overflow_stack(&buf);
1527 }
1528}
1529
1530TEST_F(CrasherTest, stack_overflow) {
1531 int intercept_result;
1532 unique_fd output_fd;
1533 StartProcess([]() { overflow_stack(nullptr); });
1534
1535 StartIntercept(&output_fd);
1536 FinishCrasher();
1537 AssertDeath(SIGSEGV);
1538 FinishIntercept(&intercept_result);
1539
1540 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1541
1542 std::string result;
1543 ConsumeFd(std::move(output_fd), &result);
1544 ASSERT_MATCH(result, R"(Cause: stack pointer[^\n]*stack overflow.\n)");
1545}
Josh Gao76e1e302021-01-26 15:53:11 -08001546
Christopher Ferrisfe751c52021-04-16 09:40:40 -07001547static bool CopySharedLibrary(const char* tmp_dir, std::string* tmp_so_name) {
1548 std::string test_lib(testing::internal::GetArgvs()[0]);
1549 auto const value = test_lib.find_last_of('/');
1550 if (value == std::string::npos) {
1551 test_lib = "./";
1552 } else {
1553 test_lib = test_lib.substr(0, value + 1) + "./";
1554 }
1555 test_lib += "libcrash_test.so";
1556
1557 *tmp_so_name = std::string(tmp_dir) + "/libcrash_test.so";
1558 std::string cp_cmd = android::base::StringPrintf("cp %s %s", test_lib.c_str(), tmp_dir);
1559
1560 // Copy the shared so to a tempory directory.
1561 return system(cp_cmd.c_str()) == 0;
1562}
1563
1564TEST_F(CrasherTest, unreadable_elf) {
1565 int intercept_result;
1566 unique_fd output_fd;
1567 StartProcess([]() {
1568 TemporaryDir td;
1569 std::string tmp_so_name;
1570 if (!CopySharedLibrary(td.path, &tmp_so_name)) {
1571 _exit(1);
1572 }
1573 void* handle = dlopen(tmp_so_name.c_str(), RTLD_NOW);
1574 if (handle == nullptr) {
1575 _exit(1);
1576 }
1577 // Delete the original shared library so that we get the warning
1578 // about unreadable elf files.
1579 if (unlink(tmp_so_name.c_str()) == -1) {
1580 _exit(1);
1581 }
1582 void (*crash_func)() = reinterpret_cast<void (*)()>(dlsym(handle, "crash"));
1583 if (crash_func == nullptr) {
1584 _exit(1);
1585 }
1586 crash_func();
1587 });
1588
1589 StartIntercept(&output_fd);
1590 FinishCrasher();
1591 AssertDeath(SIGSEGV);
1592 FinishIntercept(&intercept_result);
1593
1594 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1595
1596 std::string result;
1597 ConsumeFd(std::move(output_fd), &result);
1598 ASSERT_MATCH(result, R"(NOTE: Function names and BuildId information is missing )");
1599}
1600
Josh Gao76e1e302021-01-26 15:53:11 -08001601TEST(tombstoned, proto) {
1602 const pid_t self = getpid();
1603 unique_fd tombstoned_socket, text_fd, proto_fd;
1604 ASSERT_TRUE(
1605 tombstoned_connect(self, &tombstoned_socket, &text_fd, &proto_fd, kDebuggerdTombstoneProto));
1606
1607 tombstoned_notify_completion(tombstoned_socket.get());
1608
1609 ASSERT_NE(-1, text_fd.get());
1610 ASSERT_NE(-1, proto_fd.get());
1611
1612 struct stat text_st;
1613 ASSERT_EQ(0, fstat(text_fd.get(), &text_st));
1614
1615 // Give tombstoned some time to link the files into place.
1616 std::this_thread::sleep_for(100ms);
1617
1618 // Find the tombstone.
Christopher Ferris35da2882021-02-17 15:39:06 -08001619 std::optional<std::string> tombstone_file;
1620 std::unique_ptr<DIR, decltype(&closedir)> dir_h(opendir("/data/tombstones"), closedir);
1621 ASSERT_TRUE(dir_h != nullptr);
1622 std::regex tombstone_re("tombstone_\\d+");
1623 dirent* entry;
1624 while ((entry = readdir(dir_h.get())) != nullptr) {
1625 if (!std::regex_match(entry->d_name, tombstone_re)) {
1626 continue;
1627 }
1628 std::string path = android::base::StringPrintf("/data/tombstones/%s", entry->d_name);
Josh Gao76e1e302021-01-26 15:53:11 -08001629
1630 struct stat st;
1631 if (TEMP_FAILURE_RETRY(stat(path.c_str(), &st)) != 0) {
1632 continue;
1633 }
1634
1635 if (st.st_dev == text_st.st_dev && st.st_ino == text_st.st_ino) {
Christopher Ferris35da2882021-02-17 15:39:06 -08001636 tombstone_file = path;
Josh Gao76e1e302021-01-26 15:53:11 -08001637 break;
1638 }
1639 }
1640
Christopher Ferris35da2882021-02-17 15:39:06 -08001641 ASSERT_TRUE(tombstone_file);
1642 std::string proto_path = tombstone_file.value() + ".pb";
Josh Gao76e1e302021-01-26 15:53:11 -08001643
1644 struct stat proto_fd_st;
1645 struct stat proto_file_st;
1646 ASSERT_EQ(0, fstat(proto_fd.get(), &proto_fd_st));
1647 ASSERT_EQ(0, stat(proto_path.c_str(), &proto_file_st));
1648
1649 ASSERT_EQ(proto_fd_st.st_dev, proto_file_st.st_dev);
1650 ASSERT_EQ(proto_fd_st.st_ino, proto_file_st.st_ino);
1651}
1652
1653TEST(tombstoned, proto_intercept) {
1654 const pid_t self = getpid();
1655 unique_fd intercept_fd, output_fd;
1656 InterceptStatus status;
1657
1658 tombstoned_intercept(self, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
1659 ASSERT_EQ(InterceptStatus::kRegistered, status);
1660
1661 unique_fd tombstoned_socket, text_fd, proto_fd;
1662 ASSERT_TRUE(
1663 tombstoned_connect(self, &tombstoned_socket, &text_fd, &proto_fd, kDebuggerdTombstoneProto));
1664 ASSERT_TRUE(android::base::WriteStringToFd("foo", text_fd.get()));
1665 tombstoned_notify_completion(tombstoned_socket.get());
1666
1667 text_fd.reset();
1668
1669 std::string output;
1670 ASSERT_TRUE(android::base::ReadFdToString(output_fd, &output));
1671 ASSERT_EQ("foo", output);
1672}