blob: eb3738e66b95a0c4c3557373230c09e3cfd809ca [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 Collingbournebb4b49c2021-01-06 21:02:19 -0800517TEST_P(SizeParamCrasherTest, mte_overflow) {
Peter Collingbournecd278072020-12-21 14:08:38 -0800518#if defined(__aarch64__)
Peter Collingbournef8622522020-04-07 14:07:32 -0700519 if (!mte_supported()) {
520 GTEST_SKIP() << "Requires MTE";
521 }
522
523 int intercept_result;
524 unique_fd output_fd;
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800525 StartProcess([&]() {
Peter Collingbournef8622522020-04-07 14:07:32 -0700526 SetTagCheckingLevelSync();
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800527 volatile char* p = (volatile char*)malloc(GetParam());
528 p[GetParam()] = 42;
Peter Collingbournef8622522020-04-07 14:07:32 -0700529 });
530
531 StartIntercept(&output_fd);
532 FinishCrasher();
533 AssertDeath(SIGSEGV);
534 FinishIntercept(&intercept_result);
535
536 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
537
538 std::string result;
539 ConsumeFd(std::move(output_fd), &result);
540
541 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\))");
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800542 ASSERT_MATCH(result, R"(Cause: \[MTE\]: Buffer Overflow, 0 bytes right of a )" +
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800543 std::to_string(GetParam()) + R"(-byte allocation)");
544 ASSERT_MATCH(result, R"(allocated by thread .*
Peter Collingbournebbe69052020-05-08 10:11:19 -0700545 #00 pc)");
Peter Collingbournef8622522020-04-07 14:07:32 -0700546#else
Peter Collingbournecd278072020-12-21 14:08:38 -0800547 GTEST_SKIP() << "Requires aarch64";
Peter Collingbournef8622522020-04-07 14:07:32 -0700548#endif
549}
550
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800551TEST_P(SizeParamCrasherTest, mte_underflow) {
Peter Collingbournecd278072020-12-21 14:08:38 -0800552#if defined(__aarch64__)
Peter Collingbournef8622522020-04-07 14:07:32 -0700553 if (!mte_supported()) {
554 GTEST_SKIP() << "Requires MTE";
555 }
556
557 int intercept_result;
558 unique_fd output_fd;
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800559 StartProcess([&]() {
Peter Collingbournef8622522020-04-07 14:07:32 -0700560 SetTagCheckingLevelSync();
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800561 volatile int* p = (volatile int*)malloc(GetParam());
Peter Collingbournef8622522020-04-07 14:07:32 -0700562 p[-1] = 42;
563 });
564
565 StartIntercept(&output_fd);
566 FinishCrasher();
567 AssertDeath(SIGSEGV);
568 FinishIntercept(&intercept_result);
569
570 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
571
572 std::string result;
573 ConsumeFd(std::move(output_fd), &result);
574
575 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\), code 9 \(SEGV_MTESERR\))");
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800576 ASSERT_MATCH(result, R"(Cause: \[MTE\]: Buffer Underflow, 4 bytes left of a )" +
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800577 std::to_string(GetParam()) + R"(-byte allocation)");
578 ASSERT_MATCH(result, R"(allocated by thread .*
Peter Collingbournebbe69052020-05-08 10:11:19 -0700579 #00 pc)");
Peter Collingbournef8622522020-04-07 14:07:32 -0700580#else
Peter Collingbournecd278072020-12-21 14:08:38 -0800581 GTEST_SKIP() << "Requires aarch64";
Peter Collingbournef8622522020-04-07 14:07:32 -0700582#endif
583}
584
585TEST_F(CrasherTest, mte_multiple_causes) {
Peter Collingbournecd278072020-12-21 14:08:38 -0800586#if defined(__aarch64__)
Peter Collingbournef8622522020-04-07 14:07:32 -0700587 if (!mte_supported()) {
588 GTEST_SKIP() << "Requires MTE";
589 }
590
591 int intercept_result;
592 unique_fd output_fd;
593 StartProcess([]() {
594 SetTagCheckingLevelSync();
595
596 // Make two allocations with the same tag and close to one another. Check for both properties
597 // with a bounds check -- this relies on the fact that only if the allocations have the same tag
598 // would they be measured as closer than 128 bytes to each other. Otherwise they would be about
599 // (some non-zero value << 56) apart.
600 //
601 // The out-of-bounds access will be considered either an overflow of one or an underflow of the
602 // other.
603 std::set<uintptr_t> allocs;
604 for (int i = 0; i != 4096; ++i) {
605 uintptr_t alloc = reinterpret_cast<uintptr_t>(malloc(16));
606 auto it = allocs.insert(alloc).first;
607 if (it != allocs.begin() && *std::prev(it) + 128 > alloc) {
608 *reinterpret_cast<int*>(*std::prev(it) + 16) = 42;
609 }
610 if (std::next(it) != allocs.end() && alloc + 128 > *std::next(it)) {
611 *reinterpret_cast<int*>(alloc + 16) = 42;
612 }
613 }
614 });
615
616 StartIntercept(&output_fd);
617 FinishCrasher();
618 AssertDeath(SIGSEGV);
619 FinishIntercept(&intercept_result);
620
621 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
622
623 std::string result;
624 ConsumeFd(std::move(output_fd), &result);
625
626 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\))");
627 ASSERT_MATCH(
628 result,
629 R"(Note: multiple potential causes for this crash were detected, listing them in decreasing order of probability.)");
630
631 // Adjacent untracked allocations may cause us to see the wrong underflow here (or only
632 // overflows), so we can't match explicitly for an underflow message.
633 ASSERT_MATCH(result, R"(Cause: \[MTE\]: Buffer Overflow, 0 bytes right of a 16-byte allocation)");
634#else
Peter Collingbournecd278072020-12-21 14:08:38 -0800635 GTEST_SKIP() << "Requires aarch64";
Peter Collingbournef8622522020-04-07 14:07:32 -0700636#endif
637}
638
Peter Collingbournecd278072020-12-21 14:08:38 -0800639#if defined(__aarch64__)
Peter Collingbournefe8997a2020-07-20 15:08:52 -0700640static uintptr_t CreateTagMapping() {
641 uintptr_t mapping =
642 reinterpret_cast<uintptr_t>(mmap(nullptr, getpagesize(), PROT_READ | PROT_WRITE | PROT_MTE,
643 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0));
644 if (reinterpret_cast<void*>(mapping) == MAP_FAILED) {
645 return 0;
646 }
647 __asm__ __volatile__(".arch_extension mte; stg %0, [%0]"
648 :
649 : "r"(mapping + (1ULL << 56))
650 : "memory");
651 return mapping;
652}
653#endif
654
655TEST_F(CrasherTest, mte_tag_dump) {
Peter Collingbournecd278072020-12-21 14:08:38 -0800656#if defined(__aarch64__)
Peter Collingbournefe8997a2020-07-20 15:08:52 -0700657 if (!mte_supported()) {
658 GTEST_SKIP() << "Requires MTE";
659 }
660
661 int intercept_result;
662 unique_fd output_fd;
663 StartProcess([&]() {
664 SetTagCheckingLevelSync();
665 Trap(reinterpret_cast<void *>(CreateTagMapping()));
666 });
667
668 StartIntercept(&output_fd);
669 FinishCrasher();
670 AssertDeath(SIGTRAP);
671 FinishIntercept(&intercept_result);
672
673 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
674
675 std::string result;
676 ConsumeFd(std::move(output_fd), &result);
677
678 ASSERT_MATCH(result, R"(memory near x0:
679.*
680.*
681 01.............0 0000000000000000 0000000000000000 ................
682 00.............0)");
683#else
Peter Collingbournecd278072020-12-21 14:08:38 -0800684 GTEST_SKIP() << "Requires aarch64";
Peter Collingbournefe8997a2020-07-20 15:08:52 -0700685#endif
686}
687
Josh Gaocdea7502017-11-01 15:00:40 -0700688TEST_F(CrasherTest, LD_PRELOAD) {
689 int intercept_result;
690 unique_fd output_fd;
691 StartProcess([]() {
692 setenv("LD_PRELOAD", "nonexistent.so", 1);
693 *reinterpret_cast<volatile char*>(0xdead) = '1';
694 });
695
696 StartIntercept(&output_fd);
697 FinishCrasher();
698 AssertDeath(SIGSEGV);
699 FinishIntercept(&intercept_result);
700
701 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
702
703 std::string result;
704 ConsumeFd(std::move(output_fd), &result);
705 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\), code 1 \(SEGV_MAPERR\), fault addr 0xdead)");
706}
707
Josh Gaocbe70cb2016-10-18 18:17:52 -0700708TEST_F(CrasherTest, abort) {
709 int intercept_result;
710 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800711 StartProcess([]() {
712 abort();
713 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700714 StartIntercept(&output_fd);
715 FinishCrasher();
716 AssertDeath(SIGABRT);
717 FinishIntercept(&intercept_result);
718
719 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
720
721 std::string result;
722 ConsumeFd(std::move(output_fd), &result);
Andreas Gampe26cbafb2017-06-22 20:14:43 -0700723 ASSERT_BACKTRACE_FRAME(result, "abort");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700724}
725
726TEST_F(CrasherTest, signal) {
727 int intercept_result;
728 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800729 StartProcess([]() {
Josh Gao2b2ae0c2017-08-21 14:31:17 -0700730 while (true) {
731 sleep(1);
732 }
Josh Gao502cfd22017-02-17 01:39:15 -0800733 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700734 StartIntercept(&output_fd);
Josh Gao2b2ae0c2017-08-21 14:31:17 -0700735 FinishCrasher();
Josh Gaocbe70cb2016-10-18 18:17:52 -0700736 ASSERT_EQ(0, kill(crasher_pid, SIGSEGV));
737
738 AssertDeath(SIGSEGV);
739 FinishIntercept(&intercept_result);
740
741 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
742
743 std::string result;
744 ConsumeFd(std::move(output_fd), &result);
Elliott Hughes89722702018-05-02 10:47:00 -0700745 ASSERT_MATCH(
746 result,
747 R"(signal 11 \(SIGSEGV\), code 0 \(SI_USER from pid \d+, uid \d+\), fault addr --------)");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700748 ASSERT_MATCH(result, R"(backtrace:)");
749}
750
751TEST_F(CrasherTest, abort_message) {
752 int intercept_result;
753 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800754 StartProcess([]() {
Josh Gao1cc7bd82018-02-13 13:16:17 -0800755 // Arrived at experimentally;
756 // logd truncates at 4062.
757 // strlen("Abort message: ''") is 17.
758 // That's 4045, but we also want a NUL.
759 char buf[4045 + 1];
760 memset(buf, 'x', sizeof(buf));
761 buf[sizeof(buf) - 1] = '\0';
762 android_set_abort_message(buf);
Josh Gao502cfd22017-02-17 01:39:15 -0800763 abort();
764 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700765 StartIntercept(&output_fd);
766 FinishCrasher();
767 AssertDeath(SIGABRT);
768 FinishIntercept(&intercept_result);
769
770 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
771
772 std::string result;
773 ConsumeFd(std::move(output_fd), &result);
Josh Gao1cc7bd82018-02-13 13:16:17 -0800774 ASSERT_MATCH(result, R"(Abort message: 'x{4045}')");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700775}
776
Josh Gaoe06f2a42017-04-27 16:50:38 -0700777TEST_F(CrasherTest, abort_message_backtrace) {
778 int intercept_result;
779 unique_fd output_fd;
780 StartProcess([]() {
781 android_set_abort_message("not actually aborting");
Josh Gaoa48b41b2019-12-13 14:11:04 -0800782 raise(BIONIC_SIGNAL_DEBUGGER);
Josh Gaoe06f2a42017-04-27 16:50:38 -0700783 exit(0);
784 });
785 StartIntercept(&output_fd);
786 FinishCrasher();
787 AssertDeath(0);
788 FinishIntercept(&intercept_result);
789
790 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
791
792 std::string result;
793 ConsumeFd(std::move(output_fd), &result);
794 ASSERT_NOT_MATCH(result, R"(Abort message:)");
795}
796
Josh Gaocbe70cb2016-10-18 18:17:52 -0700797TEST_F(CrasherTest, intercept_timeout) {
798 int intercept_result;
799 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800800 StartProcess([]() {
801 abort();
802 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700803 StartIntercept(&output_fd);
804
805 // Don't let crasher finish until we timeout.
806 FinishIntercept(&intercept_result);
807
808 ASSERT_NE(1, intercept_result) << "tombstoned reported success? (intercept_result = "
809 << intercept_result << ")";
810
811 FinishCrasher();
812 AssertDeath(SIGABRT);
813}
814
Elliott Hughese4781d52021-03-17 09:15:15 -0700815TEST_F(CrasherTest, wait_for_debugger) {
816 if (!android::base::SetProperty(kWaitForDebuggerKey, "1")) {
817 FAIL() << "failed to enable wait_for_debugger";
Josh Gaocbe70cb2016-10-18 18:17:52 -0700818 }
819 sleep(1);
820
Josh Gao502cfd22017-02-17 01:39:15 -0800821 StartProcess([]() {
822 abort();
823 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700824 FinishCrasher();
825
826 int status;
Christopher Ferris172b0a02019-09-18 17:48:30 -0700827 ASSERT_EQ(crasher_pid, TEMP_FAILURE_RETRY(waitpid(crasher_pid, &status, WUNTRACED)));
Josh Gaocbe70cb2016-10-18 18:17:52 -0700828 ASSERT_TRUE(WIFSTOPPED(status));
829 ASSERT_EQ(SIGSTOP, WSTOPSIG(status));
830
831 ASSERT_EQ(0, kill(crasher_pid, SIGCONT));
832
833 AssertDeath(SIGABRT);
834}
835
Josh Gaocbe70cb2016-10-18 18:17:52 -0700836TEST_F(CrasherTest, backtrace) {
837 std::string result;
838 int intercept_result;
839 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800840
841 StartProcess([]() {
842 abort();
843 });
Narayan Kamatha73df602017-05-24 15:07:25 +0100844 StartIntercept(&output_fd, kDebuggerdNativeBacktrace);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700845
846 std::this_thread::sleep_for(500ms);
847
848 sigval val;
849 val.sival_int = 1;
Josh Gaoa48b41b2019-12-13 14:11:04 -0800850 ASSERT_EQ(0, sigqueue(crasher_pid, BIONIC_SIGNAL_DEBUGGER, val)) << strerror(errno);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700851 FinishIntercept(&intercept_result);
852 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
853 ConsumeFd(std::move(output_fd), &result);
Jaesung Chung58778e12017-06-15 18:20:34 +0900854 ASSERT_BACKTRACE_FRAME(result, "read");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700855
856 int status;
857 ASSERT_EQ(0, waitpid(crasher_pid, &status, WNOHANG | WUNTRACED));
858
859 StartIntercept(&output_fd);
860 FinishCrasher();
861 AssertDeath(SIGABRT);
862 FinishIntercept(&intercept_result);
863 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
864 ConsumeFd(std::move(output_fd), &result);
Andreas Gampe26cbafb2017-06-22 20:14:43 -0700865 ASSERT_BACKTRACE_FRAME(result, "abort");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700866}
Josh Gaofca7ca32017-01-23 12:05:35 -0800867
868TEST_F(CrasherTest, PR_SET_DUMPABLE_0_crash) {
Josh Gao502cfd22017-02-17 01:39:15 -0800869 int intercept_result;
870 unique_fd output_fd;
Josh Gaofca7ca32017-01-23 12:05:35 -0800871 StartProcess([]() {
872 prctl(PR_SET_DUMPABLE, 0);
Josh Gao502cfd22017-02-17 01:39:15 -0800873 abort();
Josh Gaofca7ca32017-01-23 12:05:35 -0800874 });
Josh Gao502cfd22017-02-17 01:39:15 -0800875
876 StartIntercept(&output_fd);
877 FinishCrasher();
878 AssertDeath(SIGABRT);
879 FinishIntercept(&intercept_result);
880
881 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
882
883 std::string result;
884 ConsumeFd(std::move(output_fd), &result);
Andreas Gampe26cbafb2017-06-22 20:14:43 -0700885 ASSERT_BACKTRACE_FRAME(result, "abort");
Josh Gaofca7ca32017-01-23 12:05:35 -0800886}
887
Josh Gao502cfd22017-02-17 01:39:15 -0800888TEST_F(CrasherTest, capabilities) {
889 ASSERT_EQ(0U, getuid()) << "capability test requires root";
890
Josh Gaofca7ca32017-01-23 12:05:35 -0800891 StartProcess([]() {
Josh Gao502cfd22017-02-17 01:39:15 -0800892 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) != 0) {
893 err(1, "failed to set PR_SET_KEEPCAPS");
894 }
895
896 if (setresuid(1, 1, 1) != 0) {
897 err(1, "setresuid failed");
898 }
899
900 __user_cap_header_struct capheader;
901 __user_cap_data_struct capdata[2];
902 memset(&capheader, 0, sizeof(capheader));
903 memset(&capdata, 0, sizeof(capdata));
904
905 capheader.version = _LINUX_CAPABILITY_VERSION_3;
906 capheader.pid = 0;
907
908 // Turn on every third capability.
909 static_assert(CAP_LAST_CAP > 33, "CAP_LAST_CAP <= 32");
910 for (int i = 0; i < CAP_LAST_CAP; i += 3) {
911 capdata[CAP_TO_INDEX(i)].permitted |= CAP_TO_MASK(i);
912 capdata[CAP_TO_INDEX(i)].effective |= CAP_TO_MASK(i);
913 }
914
915 // Make sure CAP_SYS_PTRACE is off.
916 capdata[CAP_TO_INDEX(CAP_SYS_PTRACE)].permitted &= ~(CAP_TO_MASK(CAP_SYS_PTRACE));
917 capdata[CAP_TO_INDEX(CAP_SYS_PTRACE)].effective &= ~(CAP_TO_MASK(CAP_SYS_PTRACE));
918
919 if (capset(&capheader, &capdata[0]) != 0) {
920 err(1, "capset failed");
921 }
922
923 if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_CLEAR_ALL, 0, 0, 0) != 0) {
924 err(1, "failed to drop ambient capabilities");
925 }
926
Josh Gaoa5199a92017-04-03 13:18:34 -0700927 pthread_setname_np(pthread_self(), "thread_name");
Josh Gao502cfd22017-02-17 01:39:15 -0800928 raise(SIGSYS);
Josh Gaofca7ca32017-01-23 12:05:35 -0800929 });
Josh Gao502cfd22017-02-17 01:39:15 -0800930
931 unique_fd output_fd;
932 StartIntercept(&output_fd);
933 FinishCrasher();
934 AssertDeath(SIGSYS);
935
936 std::string result;
937 int intercept_result;
938 FinishIntercept(&intercept_result);
939 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
940 ConsumeFd(std::move(output_fd), &result);
Josh Gaoa5199a92017-04-03 13:18:34 -0700941 ASSERT_MATCH(result, R"(name: thread_name\s+>>> .+debuggerd_test(32|64) <<<)");
Jaesung Chung58778e12017-06-15 18:20:34 +0900942 ASSERT_BACKTRACE_FRAME(result, "tgkill");
Josh Gaofca7ca32017-01-23 12:05:35 -0800943}
Josh Gaoc3c8c022017-02-13 16:36:18 -0800944
Josh Gao2e7b8e22017-05-04 17:12:57 -0700945TEST_F(CrasherTest, fake_pid) {
946 int intercept_result;
947 unique_fd output_fd;
948
949 // Prime the getpid/gettid caches.
950 UNUSED(getpid());
951 UNUSED(gettid());
952
953 std::function<pid_t()> clone_fn = []() {
954 return syscall(__NR_clone, SIGCHLD, nullptr, nullptr, nullptr, nullptr);
955 };
956 StartProcess(
957 []() {
958 ASSERT_NE(getpid(), syscall(__NR_getpid));
959 ASSERT_NE(gettid(), syscall(__NR_gettid));
960 raise(SIGSEGV);
961 },
962 clone_fn);
963
964 StartIntercept(&output_fd);
965 FinishCrasher();
966 AssertDeath(SIGSEGV);
967 FinishIntercept(&intercept_result);
968
969 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
970
971 std::string result;
972 ConsumeFd(std::move(output_fd), &result);
Jaesung Chung58778e12017-06-15 18:20:34 +0900973 ASSERT_BACKTRACE_FRAME(result, "tgkill");
Josh Gao2e7b8e22017-05-04 17:12:57 -0700974}
975
Josh Gaoe04ca272018-01-16 15:38:17 -0800976static const char* const kDebuggerdSeccompPolicy =
977 "/system/etc/seccomp_policy/crash_dump." ABI_STRING ".policy";
978
Josh Gao70adac62018-02-22 11:38:33 -0800979static pid_t seccomp_fork_impl(void (*prejail)()) {
Josh Gao6f9eeec2018-09-12 13:55:47 -0700980 std::string policy;
981 if (!android::base::ReadFileToString(kDebuggerdSeccompPolicy, &policy)) {
982 PLOG(FATAL) << "failed to read policy file";
983 }
984
985 // Allow a bunch of syscalls used by the tests.
986 policy += "\nclone: 1";
987 policy += "\nsigaltstack: 1";
988 policy += "\nnanosleep: 1";
Christopher Ferrisab606682019-09-17 15:31:47 -0700989 policy += "\ngetrlimit: 1";
990 policy += "\nugetrlimit: 1";
Josh Gao6f9eeec2018-09-12 13:55:47 -0700991
992 FILE* tmp_file = tmpfile();
993 if (!tmp_file) {
994 PLOG(FATAL) << "tmpfile failed";
995 }
996
Christopher Ferris172b0a02019-09-18 17:48:30 -0700997 unique_fd tmp_fd(TEMP_FAILURE_RETRY(dup(fileno(tmp_file))));
Josh Gao6f9eeec2018-09-12 13:55:47 -0700998 if (!android::base::WriteStringToFd(policy, tmp_fd.get())) {
999 PLOG(FATAL) << "failed to write policy to tmpfile";
1000 }
1001
1002 if (lseek(tmp_fd.get(), 0, SEEK_SET) != 0) {
1003 PLOG(FATAL) << "failed to seek tmp_fd";
Josh Gaoe04ca272018-01-16 15:38:17 -08001004 }
1005
1006 ScopedMinijail jail{minijail_new()};
1007 if (!jail) {
1008 LOG(FATAL) << "failed to create minijail";
1009 }
1010
1011 minijail_no_new_privs(jail.get());
1012 minijail_log_seccomp_filter_failures(jail.get());
1013 minijail_use_seccomp_filter(jail.get());
Josh Gao6f9eeec2018-09-12 13:55:47 -07001014 minijail_parse_seccomp_filters_from_fd(jail.get(), tmp_fd.release());
Josh Gaoe04ca272018-01-16 15:38:17 -08001015
1016 pid_t result = fork();
1017 if (result == -1) {
1018 return result;
1019 } else if (result != 0) {
1020 return result;
1021 }
1022
1023 // Spawn and detach a thread that spins forever.
1024 std::atomic<bool> thread_ready(false);
1025 std::thread thread([&jail, &thread_ready]() {
1026 minijail_enter(jail.get());
1027 thread_ready = true;
1028 for (;;)
1029 ;
1030 });
1031 thread.detach();
1032
1033 while (!thread_ready) {
1034 continue;
1035 }
1036
Josh Gao70adac62018-02-22 11:38:33 -08001037 if (prejail) {
1038 prejail();
1039 }
1040
Josh Gaoe04ca272018-01-16 15:38:17 -08001041 minijail_enter(jail.get());
1042 return result;
1043}
1044
Josh Gao70adac62018-02-22 11:38:33 -08001045static pid_t seccomp_fork() {
1046 return seccomp_fork_impl(nullptr);
1047}
1048
Josh Gaoe04ca272018-01-16 15:38:17 -08001049TEST_F(CrasherTest, seccomp_crash) {
1050 int intercept_result;
1051 unique_fd output_fd;
1052
1053 StartProcess([]() { abort(); }, &seccomp_fork);
1054
1055 StartIntercept(&output_fd);
1056 FinishCrasher();
1057 AssertDeath(SIGABRT);
1058 FinishIntercept(&intercept_result);
1059 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1060
1061 std::string result;
1062 ConsumeFd(std::move(output_fd), &result);
1063 ASSERT_BACKTRACE_FRAME(result, "abort");
1064}
1065
Josh Gao70adac62018-02-22 11:38:33 -08001066static pid_t seccomp_fork_rlimit() {
1067 return seccomp_fork_impl([]() {
1068 struct rlimit rlim = {
1069 .rlim_cur = 512 * 1024 * 1024,
1070 .rlim_max = 512 * 1024 * 1024,
1071 };
1072
1073 if (setrlimit(RLIMIT_AS, &rlim) != 0) {
1074 raise(SIGINT);
1075 }
1076 });
1077}
1078
1079TEST_F(CrasherTest, seccomp_crash_oom) {
1080 int intercept_result;
1081 unique_fd output_fd;
1082
1083 StartProcess(
1084 []() {
1085 std::vector<void*> vec;
1086 for (int i = 0; i < 512; ++i) {
1087 char* buf = static_cast<char*>(malloc(1024 * 1024));
1088 if (!buf) {
1089 abort();
1090 }
1091 memset(buf, 0xff, 1024 * 1024);
1092 vec.push_back(buf);
1093 }
1094 },
1095 &seccomp_fork_rlimit);
1096
1097 StartIntercept(&output_fd);
1098 FinishCrasher();
1099 AssertDeath(SIGABRT);
1100 FinishIntercept(&intercept_result);
1101 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1102
1103 // We can't actually generate a backtrace, just make sure that the process terminates.
1104}
1105
Josh Gaoe04ca272018-01-16 15:38:17 -08001106__attribute__((noinline)) extern "C" bool raise_debugger_signal(DebuggerdDumpType dump_type) {
1107 siginfo_t siginfo;
1108 siginfo.si_code = SI_QUEUE;
1109 siginfo.si_pid = getpid();
1110 siginfo.si_uid = getuid();
1111
1112 if (dump_type != kDebuggerdNativeBacktrace && dump_type != kDebuggerdTombstone) {
1113 PLOG(FATAL) << "invalid dump type";
1114 }
1115
1116 siginfo.si_value.sival_int = dump_type == kDebuggerdNativeBacktrace;
1117
Josh Gaoa48b41b2019-12-13 14:11:04 -08001118 if (syscall(__NR_rt_tgsigqueueinfo, getpid(), gettid(), BIONIC_SIGNAL_DEBUGGER, &siginfo) != 0) {
Josh Gaoe04ca272018-01-16 15:38:17 -08001119 PLOG(ERROR) << "libdebuggerd_client: failed to send signal to self";
1120 return false;
1121 }
1122
1123 return true;
1124}
1125
1126TEST_F(CrasherTest, seccomp_tombstone) {
1127 int intercept_result;
1128 unique_fd output_fd;
1129
1130 static const auto dump_type = kDebuggerdTombstone;
1131 StartProcess(
1132 []() {
1133 raise_debugger_signal(dump_type);
1134 _exit(0);
1135 },
1136 &seccomp_fork);
1137
1138 StartIntercept(&output_fd, dump_type);
1139 FinishCrasher();
1140 AssertDeath(0);
1141 FinishIntercept(&intercept_result);
1142 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1143
1144 std::string result;
1145 ConsumeFd(std::move(output_fd), &result);
1146 ASSERT_BACKTRACE_FRAME(result, "raise_debugger_signal");
1147}
1148
Josh Gao6f9eeec2018-09-12 13:55:47 -07001149extern "C" void foo() {
1150 LOG(INFO) << "foo";
1151 std::this_thread::sleep_for(1s);
1152}
1153
1154extern "C" void bar() {
1155 LOG(INFO) << "bar";
1156 std::this_thread::sleep_for(1s);
1157}
1158
Josh Gaoe04ca272018-01-16 15:38:17 -08001159TEST_F(CrasherTest, seccomp_backtrace) {
1160 int intercept_result;
1161 unique_fd output_fd;
1162
1163 static const auto dump_type = kDebuggerdNativeBacktrace;
1164 StartProcess(
1165 []() {
Josh Gao6f9eeec2018-09-12 13:55:47 -07001166 std::thread a(foo);
1167 std::thread b(bar);
1168
1169 std::this_thread::sleep_for(100ms);
1170
Josh Gaoe04ca272018-01-16 15:38:17 -08001171 raise_debugger_signal(dump_type);
1172 _exit(0);
1173 },
1174 &seccomp_fork);
1175
1176 StartIntercept(&output_fd, dump_type);
1177 FinishCrasher();
1178 AssertDeath(0);
1179 FinishIntercept(&intercept_result);
1180 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1181
1182 std::string result;
1183 ConsumeFd(std::move(output_fd), &result);
1184 ASSERT_BACKTRACE_FRAME(result, "raise_debugger_signal");
Josh Gao6f9eeec2018-09-12 13:55:47 -07001185 ASSERT_BACKTRACE_FRAME(result, "foo");
1186 ASSERT_BACKTRACE_FRAME(result, "bar");
Josh Gaoe04ca272018-01-16 15:38:17 -08001187}
1188
1189TEST_F(CrasherTest, seccomp_crash_logcat) {
1190 StartProcess([]() { abort(); }, &seccomp_fork);
1191 FinishCrasher();
1192
1193 // Make sure we don't get SIGSYS when trying to dump a crash to logcat.
1194 AssertDeath(SIGABRT);
1195}
1196
Josh Gaofd13bf02017-08-18 15:37:26 -07001197TEST_F(CrasherTest, competing_tracer) {
1198 int intercept_result;
1199 unique_fd output_fd;
1200 StartProcess([]() {
Josh Gao2b2ae0c2017-08-21 14:31:17 -07001201 raise(SIGABRT);
Josh Gaofd13bf02017-08-18 15:37:26 -07001202 });
1203
1204 StartIntercept(&output_fd);
Josh Gaofd13bf02017-08-18 15:37:26 -07001205
1206 ASSERT_EQ(0, ptrace(PTRACE_SEIZE, crasher_pid, 0, 0));
Josh Gao2b2ae0c2017-08-21 14:31:17 -07001207 FinishCrasher();
Josh Gaofd13bf02017-08-18 15:37:26 -07001208
1209 int status;
Christopher Ferris172b0a02019-09-18 17:48:30 -07001210 ASSERT_EQ(crasher_pid, TEMP_FAILURE_RETRY(waitpid(crasher_pid, &status, 0)));
Josh Gaofd13bf02017-08-18 15:37:26 -07001211 ASSERT_TRUE(WIFSTOPPED(status));
1212 ASSERT_EQ(SIGABRT, WSTOPSIG(status));
1213
1214 ASSERT_EQ(0, ptrace(PTRACE_CONT, crasher_pid, 0, SIGABRT));
1215 FinishIntercept(&intercept_result);
1216 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1217
1218 std::string result;
1219 ConsumeFd(std::move(output_fd), &result);
1220 std::string regex = R"(failed to attach to thread \d+, already traced by )";
1221 regex += std::to_string(gettid());
1222 regex += R"( \(.+debuggerd_test)";
1223 ASSERT_MATCH(result, regex.c_str());
1224
Christopher Ferris172b0a02019-09-18 17:48:30 -07001225 ASSERT_EQ(crasher_pid, TEMP_FAILURE_RETRY(waitpid(crasher_pid, &status, 0)));
Josh Gao2b2ae0c2017-08-21 14:31:17 -07001226 ASSERT_TRUE(WIFSTOPPED(status));
1227 ASSERT_EQ(SIGABRT, WSTOPSIG(status));
1228
Josh Gaofd13bf02017-08-18 15:37:26 -07001229 ASSERT_EQ(0, ptrace(PTRACE_DETACH, crasher_pid, 0, SIGABRT));
1230 AssertDeath(SIGABRT);
1231}
1232
Josh Gaobf06a402018-08-27 16:34:01 -07001233TEST_F(CrasherTest, fdsan_warning_abort_message) {
1234 int intercept_result;
1235 unique_fd output_fd;
1236
1237 StartProcess([]() {
1238 android_fdsan_set_error_level(ANDROID_FDSAN_ERROR_LEVEL_WARN_ONCE);
Christopher Ferris172b0a02019-09-18 17:48:30 -07001239 unique_fd fd(TEMP_FAILURE_RETRY(open("/dev/null", O_RDONLY | O_CLOEXEC)));
Josh Gaobf06a402018-08-27 16:34:01 -07001240 if (fd == -1) {
1241 abort();
1242 }
1243 close(fd.get());
1244 _exit(0);
1245 });
1246
1247 StartIntercept(&output_fd);
1248 FinishCrasher();
1249 AssertDeath(0);
1250 FinishIntercept(&intercept_result);
1251 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1252
1253 std::string result;
1254 ConsumeFd(std::move(output_fd), &result);
1255 ASSERT_MATCH(result, "Abort message: 'attempted to close");
1256}
1257
Josh Gaoc3c8c022017-02-13 16:36:18 -08001258TEST(crash_dump, zombie) {
1259 pid_t forkpid = fork();
1260
Josh Gaoc3c8c022017-02-13 16:36:18 -08001261 pid_t rc;
1262 int status;
1263
1264 if (forkpid == 0) {
1265 errno = 0;
1266 rc = waitpid(-1, &status, WNOHANG | __WALL | __WNOTHREAD);
1267 if (rc != -1 || errno != ECHILD) {
1268 errx(2, "first waitpid returned %d (%s), expected failure with ECHILD", rc, strerror(errno));
1269 }
1270
Josh Gaoa48b41b2019-12-13 14:11:04 -08001271 raise(BIONIC_SIGNAL_DEBUGGER);
Josh Gaoc3c8c022017-02-13 16:36:18 -08001272
1273 errno = 0;
Christopher Ferris172b0a02019-09-18 17:48:30 -07001274 rc = TEMP_FAILURE_RETRY(waitpid(-1, &status, __WALL | __WNOTHREAD));
Josh Gaoc3c8c022017-02-13 16:36:18 -08001275 if (rc != -1 || errno != ECHILD) {
1276 errx(2, "second waitpid returned %d (%s), expected failure with ECHILD", rc, strerror(errno));
1277 }
1278 _exit(0);
1279 } else {
Christopher Ferris172b0a02019-09-18 17:48:30 -07001280 rc = TEMP_FAILURE_RETRY(waitpid(forkpid, &status, 0));
Josh Gaoc3c8c022017-02-13 16:36:18 -08001281 ASSERT_EQ(forkpid, rc);
1282 ASSERT_TRUE(WIFEXITED(status));
1283 ASSERT_EQ(0, WEXITSTATUS(status));
1284 }
1285}
Josh Gao352a8452017-03-30 16:46:21 -07001286
1287TEST(tombstoned, no_notify) {
1288 // Do this a few times.
1289 for (int i = 0; i < 3; ++i) {
1290 pid_t pid = 123'456'789 + i;
1291
1292 unique_fd intercept_fd, output_fd;
Narayan Kamathca5e9082017-06-02 15:42:06 +01001293 InterceptStatus status;
1294 tombstoned_intercept(pid, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
1295 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gao352a8452017-03-30 16:46:21 -07001296
1297 {
1298 unique_fd tombstoned_socket, input_fd;
Narayan Kamatha73df602017-05-24 15:07:25 +01001299 ASSERT_TRUE(tombstoned_connect(pid, &tombstoned_socket, &input_fd, kDebuggerdTombstone));
Josh Gao352a8452017-03-30 16:46:21 -07001300 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), &pid, sizeof(pid)));
1301 }
1302
1303 pid_t read_pid;
1304 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), &read_pid, sizeof(read_pid)));
1305 ASSERT_EQ(read_pid, pid);
1306 }
1307}
1308
1309TEST(tombstoned, stress) {
1310 // Spawn threads to simultaneously do a bunch of failing dumps and a bunch of successful dumps.
1311 static constexpr int kDumpCount = 100;
1312
1313 std::atomic<bool> start(false);
1314 std::vector<std::thread> threads;
1315 threads.emplace_back([&start]() {
1316 while (!start) {
1317 continue;
1318 }
1319
1320 // Use a way out of range pid, to avoid stomping on an actual process.
1321 pid_t pid_base = 1'000'000;
1322
1323 for (int dump = 0; dump < kDumpCount; ++dump) {
1324 pid_t pid = pid_base + dump;
1325
1326 unique_fd intercept_fd, output_fd;
Narayan Kamathca5e9082017-06-02 15:42:06 +01001327 InterceptStatus status;
1328 tombstoned_intercept(pid, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
1329 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gao352a8452017-03-30 16:46:21 -07001330
1331 // Pretend to crash, and then immediately close the socket.
1332 unique_fd sockfd(socket_local_client(kTombstonedCrashSocketName,
1333 ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_SEQPACKET));
1334 if (sockfd == -1) {
1335 FAIL() << "failed to connect to tombstoned: " << strerror(errno);
1336 }
1337 TombstonedCrashPacket packet = {};
1338 packet.packet_type = CrashPacketType::kDumpRequest;
1339 packet.packet.dump_request.pid = pid;
1340 if (TEMP_FAILURE_RETRY(write(sockfd, &packet, sizeof(packet))) != sizeof(packet)) {
1341 FAIL() << "failed to write to tombstoned: " << strerror(errno);
1342 }
1343
1344 continue;
1345 }
1346 });
1347
1348 threads.emplace_back([&start]() {
1349 while (!start) {
1350 continue;
1351 }
1352
1353 // Use a way out of range pid, to avoid stomping on an actual process.
1354 pid_t pid_base = 2'000'000;
1355
1356 for (int dump = 0; dump < kDumpCount; ++dump) {
1357 pid_t pid = pid_base + dump;
1358
1359 unique_fd intercept_fd, output_fd;
Narayan Kamathca5e9082017-06-02 15:42:06 +01001360 InterceptStatus status;
1361 tombstoned_intercept(pid, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
1362 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gao352a8452017-03-30 16:46:21 -07001363
1364 {
1365 unique_fd tombstoned_socket, input_fd;
Narayan Kamatha73df602017-05-24 15:07:25 +01001366 ASSERT_TRUE(tombstoned_connect(pid, &tombstoned_socket, &input_fd, kDebuggerdTombstone));
Josh Gao352a8452017-03-30 16:46:21 -07001367 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), &pid, sizeof(pid)));
1368 tombstoned_notify_completion(tombstoned_socket.get());
1369 }
1370
1371 // TODO: Fix the race that requires this sleep.
1372 std::this_thread::sleep_for(50ms);
1373
1374 pid_t read_pid;
1375 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), &read_pid, sizeof(read_pid)));
1376 ASSERT_EQ(read_pid, pid);
1377 }
1378 });
1379
1380 start = true;
1381
1382 for (std::thread& thread : threads) {
1383 thread.join();
1384 }
1385}
Narayan Kamathca5e9082017-06-02 15:42:06 +01001386
1387TEST(tombstoned, java_trace_intercept_smoke) {
1388 // Using a "real" PID is a little dangerous here - if the test fails
1389 // or crashes, we might end up getting a bogus / unreliable stack
1390 // trace.
1391 const pid_t self = getpid();
1392
1393 unique_fd intercept_fd, output_fd;
1394 InterceptStatus status;
1395 tombstoned_intercept(self, &intercept_fd, &output_fd, &status, kDebuggerdJavaBacktrace);
1396 ASSERT_EQ(InterceptStatus::kRegistered, status);
1397
Josh Gao76e1e302021-01-26 15:53:11 -08001398 // First connect to tombstoned requesting a native tombstone. This
Narayan Kamathca5e9082017-06-02 15:42:06 +01001399 // should result in a "regular" FD and not the installed intercept.
1400 const char native[] = "native";
1401 unique_fd tombstoned_socket, input_fd;
Josh Gao76e1e302021-01-26 15:53:11 -08001402 ASSERT_TRUE(tombstoned_connect(self, &tombstoned_socket, &input_fd, kDebuggerdTombstone));
Narayan Kamathca5e9082017-06-02 15:42:06 +01001403 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), native, sizeof(native)));
1404 tombstoned_notify_completion(tombstoned_socket.get());
1405
1406 // Then, connect to tombstoned asking for a java backtrace. This *should*
1407 // trigger the intercept.
1408 const char java[] = "java";
1409 ASSERT_TRUE(tombstoned_connect(self, &tombstoned_socket, &input_fd, kDebuggerdJavaBacktrace));
1410 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), java, sizeof(java)));
1411 tombstoned_notify_completion(tombstoned_socket.get());
1412
1413 char outbuf[sizeof(java)];
1414 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), outbuf, sizeof(outbuf)));
1415 ASSERT_STREQ("java", outbuf);
1416}
1417
1418TEST(tombstoned, multiple_intercepts) {
1419 const pid_t fake_pid = 1'234'567;
1420 unique_fd intercept_fd, output_fd;
1421 InterceptStatus status;
1422 tombstoned_intercept(fake_pid, &intercept_fd, &output_fd, &status, kDebuggerdJavaBacktrace);
1423 ASSERT_EQ(InterceptStatus::kRegistered, status);
1424
1425 unique_fd intercept_fd_2, output_fd_2;
1426 tombstoned_intercept(fake_pid, &intercept_fd_2, &output_fd_2, &status, kDebuggerdNativeBacktrace);
1427 ASSERT_EQ(InterceptStatus::kFailedAlreadyRegistered, status);
1428}
1429
1430TEST(tombstoned, intercept_any) {
1431 const pid_t fake_pid = 1'234'567;
1432
1433 unique_fd intercept_fd, output_fd;
1434 InterceptStatus status;
1435 tombstoned_intercept(fake_pid, &intercept_fd, &output_fd, &status, kDebuggerdNativeBacktrace);
1436 ASSERT_EQ(InterceptStatus::kRegistered, status);
1437
1438 const char any[] = "any";
1439 unique_fd tombstoned_socket, input_fd;
1440 ASSERT_TRUE(tombstoned_connect(fake_pid, &tombstoned_socket, &input_fd, kDebuggerdAnyIntercept));
1441 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), any, sizeof(any)));
1442 tombstoned_notify_completion(tombstoned_socket.get());
1443
1444 char outbuf[sizeof(any)];
1445 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), outbuf, sizeof(outbuf)));
1446 ASSERT_STREQ("any", outbuf);
1447}
Josh Gao2b22ae12018-09-12 14:51:03 -07001448
1449TEST(tombstoned, interceptless_backtrace) {
1450 // Generate 50 backtraces, and then check to see that we haven't created 50 new tombstones.
1451 auto get_tombstone_timestamps = []() -> std::map<int, time_t> {
1452 std::map<int, time_t> result;
1453 for (int i = 0; i < 99; ++i) {
1454 std::string path = android::base::StringPrintf("/data/tombstones/tombstone_%02d", i);
1455 struct stat st;
1456 if (stat(path.c_str(), &st) == 0) {
1457 result[i] = st.st_mtim.tv_sec;
1458 }
1459 }
1460 return result;
1461 };
1462
1463 auto before = get_tombstone_timestamps();
1464 for (int i = 0; i < 50; ++i) {
1465 raise_debugger_signal(kDebuggerdNativeBacktrace);
1466 }
1467 auto after = get_tombstone_timestamps();
1468
1469 int diff = 0;
1470 for (int i = 0; i < 99; ++i) {
1471 if (after.count(i) == 0) {
1472 continue;
1473 }
1474 if (before.count(i) == 0) {
1475 ++diff;
1476 continue;
1477 }
1478 if (before[i] != after[i]) {
1479 ++diff;
1480 }
1481 }
1482
1483 // We can't be sure that nothing's crash looping in the background.
1484 // This should be good enough, though...
1485 ASSERT_LT(diff, 10) << "too many new tombstones; is something crashing in the background?";
1486}
Christopher Ferris481e8372019-07-15 17:13:24 -07001487
1488static __attribute__((__noinline__)) void overflow_stack(void* p) {
1489 void* buf[1];
1490 buf[0] = p;
1491 static volatile void* global = buf;
1492 if (global) {
1493 global = buf;
1494 overflow_stack(&buf);
1495 }
1496}
1497
1498TEST_F(CrasherTest, stack_overflow) {
1499 int intercept_result;
1500 unique_fd output_fd;
1501 StartProcess([]() { overflow_stack(nullptr); });
1502
1503 StartIntercept(&output_fd);
1504 FinishCrasher();
1505 AssertDeath(SIGSEGV);
1506 FinishIntercept(&intercept_result);
1507
1508 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1509
1510 std::string result;
1511 ConsumeFd(std::move(output_fd), &result);
1512 ASSERT_MATCH(result, R"(Cause: stack pointer[^\n]*stack overflow.\n)");
1513}
Josh Gao76e1e302021-01-26 15:53:11 -08001514
Christopher Ferrisfe751c52021-04-16 09:40:40 -07001515static bool CopySharedLibrary(const char* tmp_dir, std::string* tmp_so_name) {
1516 std::string test_lib(testing::internal::GetArgvs()[0]);
1517 auto const value = test_lib.find_last_of('/');
1518 if (value == std::string::npos) {
1519 test_lib = "./";
1520 } else {
1521 test_lib = test_lib.substr(0, value + 1) + "./";
1522 }
1523 test_lib += "libcrash_test.so";
1524
1525 *tmp_so_name = std::string(tmp_dir) + "/libcrash_test.so";
1526 std::string cp_cmd = android::base::StringPrintf("cp %s %s", test_lib.c_str(), tmp_dir);
1527
1528 // Copy the shared so to a tempory directory.
1529 return system(cp_cmd.c_str()) == 0;
1530}
1531
1532TEST_F(CrasherTest, unreadable_elf) {
1533 int intercept_result;
1534 unique_fd output_fd;
1535 StartProcess([]() {
1536 TemporaryDir td;
1537 std::string tmp_so_name;
1538 if (!CopySharedLibrary(td.path, &tmp_so_name)) {
1539 _exit(1);
1540 }
1541 void* handle = dlopen(tmp_so_name.c_str(), RTLD_NOW);
1542 if (handle == nullptr) {
1543 _exit(1);
1544 }
1545 // Delete the original shared library so that we get the warning
1546 // about unreadable elf files.
1547 if (unlink(tmp_so_name.c_str()) == -1) {
1548 _exit(1);
1549 }
1550 void (*crash_func)() = reinterpret_cast<void (*)()>(dlsym(handle, "crash"));
1551 if (crash_func == nullptr) {
1552 _exit(1);
1553 }
1554 crash_func();
1555 });
1556
1557 StartIntercept(&output_fd);
1558 FinishCrasher();
1559 AssertDeath(SIGSEGV);
1560 FinishIntercept(&intercept_result);
1561
1562 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1563
1564 std::string result;
1565 ConsumeFd(std::move(output_fd), &result);
1566 ASSERT_MATCH(result, R"(NOTE: Function names and BuildId information is missing )");
1567}
1568
Josh Gao76e1e302021-01-26 15:53:11 -08001569TEST(tombstoned, proto) {
1570 const pid_t self = getpid();
1571 unique_fd tombstoned_socket, text_fd, proto_fd;
1572 ASSERT_TRUE(
1573 tombstoned_connect(self, &tombstoned_socket, &text_fd, &proto_fd, kDebuggerdTombstoneProto));
1574
1575 tombstoned_notify_completion(tombstoned_socket.get());
1576
1577 ASSERT_NE(-1, text_fd.get());
1578 ASSERT_NE(-1, proto_fd.get());
1579
1580 struct stat text_st;
1581 ASSERT_EQ(0, fstat(text_fd.get(), &text_st));
1582
1583 // Give tombstoned some time to link the files into place.
1584 std::this_thread::sleep_for(100ms);
1585
1586 // Find the tombstone.
Christopher Ferris35da2882021-02-17 15:39:06 -08001587 std::optional<std::string> tombstone_file;
1588 std::unique_ptr<DIR, decltype(&closedir)> dir_h(opendir("/data/tombstones"), closedir);
1589 ASSERT_TRUE(dir_h != nullptr);
1590 std::regex tombstone_re("tombstone_\\d+");
1591 dirent* entry;
1592 while ((entry = readdir(dir_h.get())) != nullptr) {
1593 if (!std::regex_match(entry->d_name, tombstone_re)) {
1594 continue;
1595 }
1596 std::string path = android::base::StringPrintf("/data/tombstones/%s", entry->d_name);
Josh Gao76e1e302021-01-26 15:53:11 -08001597
1598 struct stat st;
1599 if (TEMP_FAILURE_RETRY(stat(path.c_str(), &st)) != 0) {
1600 continue;
1601 }
1602
1603 if (st.st_dev == text_st.st_dev && st.st_ino == text_st.st_ino) {
Christopher Ferris35da2882021-02-17 15:39:06 -08001604 tombstone_file = path;
Josh Gao76e1e302021-01-26 15:53:11 -08001605 break;
1606 }
1607 }
1608
Christopher Ferris35da2882021-02-17 15:39:06 -08001609 ASSERT_TRUE(tombstone_file);
1610 std::string proto_path = tombstone_file.value() + ".pb";
Josh Gao76e1e302021-01-26 15:53:11 -08001611
1612 struct stat proto_fd_st;
1613 struct stat proto_file_st;
1614 ASSERT_EQ(0, fstat(proto_fd.get(), &proto_fd_st));
1615 ASSERT_EQ(0, stat(proto_path.c_str(), &proto_file_st));
1616
1617 ASSERT_EQ(proto_fd_st.st_dev, proto_file_st.st_dev);
1618 ASSERT_EQ(proto_fd_st.st_ino, proto_file_st.st_ino);
1619}
1620
1621TEST(tombstoned, proto_intercept) {
1622 const pid_t self = getpid();
1623 unique_fd intercept_fd, output_fd;
1624 InterceptStatus status;
1625
1626 tombstoned_intercept(self, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
1627 ASSERT_EQ(InterceptStatus::kRegistered, status);
1628
1629 unique_fd tombstoned_socket, text_fd, proto_fd;
1630 ASSERT_TRUE(
1631 tombstoned_connect(self, &tombstoned_socket, &text_fd, &proto_fd, kDebuggerdTombstoneProto));
1632 ASSERT_TRUE(android::base::WriteStringToFd("foo", text_fd.get()));
1633 tombstoned_notify_completion(tombstoned_socket.get());
1634
1635 text_fd.reset();
1636
1637 std::string output;
1638 ASSERT_TRUE(android::base::ReadFdToString(output_fd, &output));
1639 ASSERT_EQ("foo", output);
1640}