blob: 46342831ca1688c66dd64a3553b6155c95626000 [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
Peter Collingbourneaa544792021-05-13 13:53:37 -0700478INSTANTIATE_TEST_SUITE_P(Sizes, SizeParamCrasherTest, testing::Values(0, 16, 131072));
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800479
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
Peter Collingbourneaa544792021-05-13 13:53:37 -0700486 // Any UAF on a zero-sized allocation will be out-of-bounds so it won't be reported.
487 if (GetParam() == 0) {
488 return;
489 }
490
Peter Collingbournef8622522020-04-07 14:07:32 -0700491 int intercept_result;
492 unique_fd output_fd;
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800493 StartProcess([&]() {
Peter Collingbournef8622522020-04-07 14:07:32 -0700494 SetTagCheckingLevelSync();
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800495 volatile int* p = (volatile int*)malloc(GetParam());
Peter Collingbournef8622522020-04-07 14:07:32 -0700496 free((void *)p);
497 p[0] = 42;
498 });
499
500 StartIntercept(&output_fd);
501 FinishCrasher();
502 AssertDeath(SIGSEGV);
503 FinishIntercept(&intercept_result);
504
505 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
506
507 std::string result;
508 ConsumeFd(std::move(output_fd), &result);
509
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800510 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\))");
511 ASSERT_MATCH(result, R"(Cause: \[MTE\]: Use After Free, 0 bytes into a )" +
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800512 std::to_string(GetParam()) + R"(-byte allocation)");
Peter Collingbournebbe69052020-05-08 10:11:19 -0700513 ASSERT_MATCH(result, R"(deallocated by thread .*
514 #00 pc)");
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800515 ASSERT_MATCH(result, R"(allocated by thread .*
516 #00 pc)");
Peter Collingbournef8622522020-04-07 14:07:32 -0700517#else
Peter Collingbournecd278072020-12-21 14:08:38 -0800518 GTEST_SKIP() << "Requires aarch64";
Peter Collingbournef8622522020-04-07 14:07:32 -0700519#endif
520}
521
Peter Collingbournedc476342021-05-12 15:56:43 -0700522TEST_P(SizeParamCrasherTest, mte_oob_uaf) {
523#if defined(__aarch64__)
524 if (!mte_supported()) {
525 GTEST_SKIP() << "Requires MTE";
526 }
527
528 int intercept_result;
529 unique_fd output_fd;
530 StartProcess([&]() {
531 SetTagCheckingLevelSync();
532 volatile int* p = (volatile int*)malloc(GetParam());
533 free((void *)p);
534 p[-1] = 42;
535 });
536
537 StartIntercept(&output_fd);
538 FinishCrasher();
539 AssertDeath(SIGSEGV);
540 FinishIntercept(&intercept_result);
541
542 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
543
544 std::string result;
545 ConsumeFd(std::move(output_fd), &result);
546
547 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\))");
548 ASSERT_NOT_MATCH(result, R"(Cause: \[MTE\]: Use After Free, 4 bytes left)");
549#else
550 GTEST_SKIP() << "Requires aarch64";
551#endif
552}
553
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800554TEST_P(SizeParamCrasherTest, mte_overflow) {
Peter Collingbournecd278072020-12-21 14:08:38 -0800555#if defined(__aarch64__)
Peter Collingbournef8622522020-04-07 14:07:32 -0700556 if (!mte_supported()) {
557 GTEST_SKIP() << "Requires MTE";
558 }
559
560 int intercept_result;
561 unique_fd output_fd;
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800562 StartProcess([&]() {
Peter Collingbournef8622522020-04-07 14:07:32 -0700563 SetTagCheckingLevelSync();
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800564 volatile char* p = (volatile char*)malloc(GetParam());
565 p[GetParam()] = 42;
Peter Collingbournef8622522020-04-07 14:07:32 -0700566 });
567
568 StartIntercept(&output_fd);
569 FinishCrasher();
570 AssertDeath(SIGSEGV);
571 FinishIntercept(&intercept_result);
572
573 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
574
575 std::string result;
576 ConsumeFd(std::move(output_fd), &result);
577
578 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\))");
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800579 ASSERT_MATCH(result, R"(Cause: \[MTE\]: Buffer Overflow, 0 bytes right of a )" +
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800580 std::to_string(GetParam()) + R"(-byte allocation)");
581 ASSERT_MATCH(result, R"(allocated by thread .*
Peter Collingbournebbe69052020-05-08 10:11:19 -0700582 #00 pc)");
Peter Collingbournef8622522020-04-07 14:07:32 -0700583#else
Peter Collingbournecd278072020-12-21 14:08:38 -0800584 GTEST_SKIP() << "Requires aarch64";
Peter Collingbournef8622522020-04-07 14:07:32 -0700585#endif
586}
587
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800588TEST_P(SizeParamCrasherTest, mte_underflow) {
Peter Collingbournecd278072020-12-21 14:08:38 -0800589#if defined(__aarch64__)
Peter Collingbournef8622522020-04-07 14:07:32 -0700590 if (!mte_supported()) {
591 GTEST_SKIP() << "Requires MTE";
592 }
593
594 int intercept_result;
595 unique_fd output_fd;
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800596 StartProcess([&]() {
Peter Collingbournef8622522020-04-07 14:07:32 -0700597 SetTagCheckingLevelSync();
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800598 volatile int* p = (volatile int*)malloc(GetParam());
Peter Collingbournef8622522020-04-07 14:07:32 -0700599 p[-1] = 42;
600 });
601
602 StartIntercept(&output_fd);
603 FinishCrasher();
604 AssertDeath(SIGSEGV);
605 FinishIntercept(&intercept_result);
606
607 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
608
609 std::string result;
610 ConsumeFd(std::move(output_fd), &result);
611
612 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\), code 9 \(SEGV_MTESERR\))");
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800613 ASSERT_MATCH(result, R"(Cause: \[MTE\]: Buffer Underflow, 4 bytes left of a )" +
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800614 std::to_string(GetParam()) + R"(-byte allocation)");
615 ASSERT_MATCH(result, R"(allocated by thread .*
Peter Collingbournebbe69052020-05-08 10:11:19 -0700616 #00 pc)");
Peter Collingbournef8622522020-04-07 14:07:32 -0700617#else
Peter Collingbournecd278072020-12-21 14:08:38 -0800618 GTEST_SKIP() << "Requires aarch64";
Peter Collingbournef8622522020-04-07 14:07:32 -0700619#endif
620}
621
622TEST_F(CrasherTest, mte_multiple_causes) {
Peter Collingbournecd278072020-12-21 14:08:38 -0800623#if defined(__aarch64__)
Peter Collingbournef8622522020-04-07 14:07:32 -0700624 if (!mte_supported()) {
625 GTEST_SKIP() << "Requires MTE";
626 }
627
628 int intercept_result;
629 unique_fd output_fd;
630 StartProcess([]() {
631 SetTagCheckingLevelSync();
632
633 // Make two allocations with the same tag and close to one another. Check for both properties
634 // with a bounds check -- this relies on the fact that only if the allocations have the same tag
635 // would they be measured as closer than 128 bytes to each other. Otherwise they would be about
636 // (some non-zero value << 56) apart.
637 //
638 // The out-of-bounds access will be considered either an overflow of one or an underflow of the
639 // other.
640 std::set<uintptr_t> allocs;
641 for (int i = 0; i != 4096; ++i) {
642 uintptr_t alloc = reinterpret_cast<uintptr_t>(malloc(16));
643 auto it = allocs.insert(alloc).first;
644 if (it != allocs.begin() && *std::prev(it) + 128 > alloc) {
645 *reinterpret_cast<int*>(*std::prev(it) + 16) = 42;
646 }
647 if (std::next(it) != allocs.end() && alloc + 128 > *std::next(it)) {
648 *reinterpret_cast<int*>(alloc + 16) = 42;
649 }
650 }
651 });
652
653 StartIntercept(&output_fd);
654 FinishCrasher();
655 AssertDeath(SIGSEGV);
656 FinishIntercept(&intercept_result);
657
658 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
659
660 std::string result;
661 ConsumeFd(std::move(output_fd), &result);
662
663 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\))");
664 ASSERT_MATCH(
665 result,
666 R"(Note: multiple potential causes for this crash were detected, listing them in decreasing order of probability.)");
667
668 // Adjacent untracked allocations may cause us to see the wrong underflow here (or only
669 // overflows), so we can't match explicitly for an underflow message.
670 ASSERT_MATCH(result, R"(Cause: \[MTE\]: Buffer Overflow, 0 bytes right of a 16-byte allocation)");
671#else
Peter Collingbournecd278072020-12-21 14:08:38 -0800672 GTEST_SKIP() << "Requires aarch64";
Peter Collingbournef8622522020-04-07 14:07:32 -0700673#endif
674}
675
Peter Collingbournecd278072020-12-21 14:08:38 -0800676#if defined(__aarch64__)
Peter Collingbournefe8997a2020-07-20 15:08:52 -0700677static uintptr_t CreateTagMapping() {
678 uintptr_t mapping =
679 reinterpret_cast<uintptr_t>(mmap(nullptr, getpagesize(), PROT_READ | PROT_WRITE | PROT_MTE,
680 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0));
681 if (reinterpret_cast<void*>(mapping) == MAP_FAILED) {
682 return 0;
683 }
684 __asm__ __volatile__(".arch_extension mte; stg %0, [%0]"
685 :
686 : "r"(mapping + (1ULL << 56))
687 : "memory");
688 return mapping;
689}
690#endif
691
692TEST_F(CrasherTest, mte_tag_dump) {
Peter Collingbournecd278072020-12-21 14:08:38 -0800693#if defined(__aarch64__)
Peter Collingbournefe8997a2020-07-20 15:08:52 -0700694 if (!mte_supported()) {
695 GTEST_SKIP() << "Requires MTE";
696 }
697
698 int intercept_result;
699 unique_fd output_fd;
700 StartProcess([&]() {
701 SetTagCheckingLevelSync();
702 Trap(reinterpret_cast<void *>(CreateTagMapping()));
703 });
704
705 StartIntercept(&output_fd);
706 FinishCrasher();
707 AssertDeath(SIGTRAP);
708 FinishIntercept(&intercept_result);
709
710 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
711
712 std::string result;
713 ConsumeFd(std::move(output_fd), &result);
714
715 ASSERT_MATCH(result, R"(memory near x0:
716.*
717.*
718 01.............0 0000000000000000 0000000000000000 ................
719 00.............0)");
720#else
Peter Collingbournecd278072020-12-21 14:08:38 -0800721 GTEST_SKIP() << "Requires aarch64";
Peter Collingbournefe8997a2020-07-20 15:08:52 -0700722#endif
723}
724
Josh Gaocdea7502017-11-01 15:00:40 -0700725TEST_F(CrasherTest, LD_PRELOAD) {
726 int intercept_result;
727 unique_fd output_fd;
728 StartProcess([]() {
729 setenv("LD_PRELOAD", "nonexistent.so", 1);
730 *reinterpret_cast<volatile char*>(0xdead) = '1';
731 });
732
733 StartIntercept(&output_fd);
734 FinishCrasher();
735 AssertDeath(SIGSEGV);
736 FinishIntercept(&intercept_result);
737
738 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
739
740 std::string result;
741 ConsumeFd(std::move(output_fd), &result);
742 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\), code 1 \(SEGV_MAPERR\), fault addr 0xdead)");
743}
744
Josh Gaocbe70cb2016-10-18 18:17:52 -0700745TEST_F(CrasherTest, abort) {
746 int intercept_result;
747 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800748 StartProcess([]() {
749 abort();
750 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700751 StartIntercept(&output_fd);
752 FinishCrasher();
753 AssertDeath(SIGABRT);
754 FinishIntercept(&intercept_result);
755
756 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
757
758 std::string result;
759 ConsumeFd(std::move(output_fd), &result);
Andreas Gampe26cbafb2017-06-22 20:14:43 -0700760 ASSERT_BACKTRACE_FRAME(result, "abort");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700761}
762
763TEST_F(CrasherTest, signal) {
764 int intercept_result;
765 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800766 StartProcess([]() {
Josh Gao2b2ae0c2017-08-21 14:31:17 -0700767 while (true) {
768 sleep(1);
769 }
Josh Gao502cfd22017-02-17 01:39:15 -0800770 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700771 StartIntercept(&output_fd);
Josh Gao2b2ae0c2017-08-21 14:31:17 -0700772 FinishCrasher();
Josh Gaocbe70cb2016-10-18 18:17:52 -0700773 ASSERT_EQ(0, kill(crasher_pid, SIGSEGV));
774
775 AssertDeath(SIGSEGV);
776 FinishIntercept(&intercept_result);
777
778 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
779
780 std::string result;
781 ConsumeFd(std::move(output_fd), &result);
Elliott Hughes89722702018-05-02 10:47:00 -0700782 ASSERT_MATCH(
783 result,
784 R"(signal 11 \(SIGSEGV\), code 0 \(SI_USER from pid \d+, uid \d+\), fault addr --------)");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700785 ASSERT_MATCH(result, R"(backtrace:)");
786}
787
788TEST_F(CrasherTest, abort_message) {
789 int intercept_result;
790 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800791 StartProcess([]() {
Josh Gao1cc7bd82018-02-13 13:16:17 -0800792 // Arrived at experimentally;
793 // logd truncates at 4062.
794 // strlen("Abort message: ''") is 17.
795 // That's 4045, but we also want a NUL.
796 char buf[4045 + 1];
797 memset(buf, 'x', sizeof(buf));
798 buf[sizeof(buf) - 1] = '\0';
799 android_set_abort_message(buf);
Josh Gao502cfd22017-02-17 01:39:15 -0800800 abort();
801 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700802 StartIntercept(&output_fd);
803 FinishCrasher();
804 AssertDeath(SIGABRT);
805 FinishIntercept(&intercept_result);
806
807 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
808
809 std::string result;
810 ConsumeFd(std::move(output_fd), &result);
Josh Gao1cc7bd82018-02-13 13:16:17 -0800811 ASSERT_MATCH(result, R"(Abort message: 'x{4045}')");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700812}
813
Josh Gaoe06f2a42017-04-27 16:50:38 -0700814TEST_F(CrasherTest, abort_message_backtrace) {
815 int intercept_result;
816 unique_fd output_fd;
817 StartProcess([]() {
818 android_set_abort_message("not actually aborting");
Josh Gaoa48b41b2019-12-13 14:11:04 -0800819 raise(BIONIC_SIGNAL_DEBUGGER);
Josh Gaoe06f2a42017-04-27 16:50:38 -0700820 exit(0);
821 });
822 StartIntercept(&output_fd);
823 FinishCrasher();
824 AssertDeath(0);
825 FinishIntercept(&intercept_result);
826
827 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
828
829 std::string result;
830 ConsumeFd(std::move(output_fd), &result);
831 ASSERT_NOT_MATCH(result, R"(Abort message:)");
832}
833
Josh Gaocbe70cb2016-10-18 18:17:52 -0700834TEST_F(CrasherTest, intercept_timeout) {
835 int intercept_result;
836 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800837 StartProcess([]() {
838 abort();
839 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700840 StartIntercept(&output_fd);
841
842 // Don't let crasher finish until we timeout.
843 FinishIntercept(&intercept_result);
844
845 ASSERT_NE(1, intercept_result) << "tombstoned reported success? (intercept_result = "
846 << intercept_result << ")";
847
848 FinishCrasher();
849 AssertDeath(SIGABRT);
850}
851
Elliott Hughese4781d52021-03-17 09:15:15 -0700852TEST_F(CrasherTest, wait_for_debugger) {
853 if (!android::base::SetProperty(kWaitForDebuggerKey, "1")) {
854 FAIL() << "failed to enable wait_for_debugger";
Josh Gaocbe70cb2016-10-18 18:17:52 -0700855 }
856 sleep(1);
857
Josh Gao502cfd22017-02-17 01:39:15 -0800858 StartProcess([]() {
859 abort();
860 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700861 FinishCrasher();
862
863 int status;
Christopher Ferris172b0a02019-09-18 17:48:30 -0700864 ASSERT_EQ(crasher_pid, TEMP_FAILURE_RETRY(waitpid(crasher_pid, &status, WUNTRACED)));
Josh Gaocbe70cb2016-10-18 18:17:52 -0700865 ASSERT_TRUE(WIFSTOPPED(status));
866 ASSERT_EQ(SIGSTOP, WSTOPSIG(status));
867
868 ASSERT_EQ(0, kill(crasher_pid, SIGCONT));
869
870 AssertDeath(SIGABRT);
871}
872
Josh Gaocbe70cb2016-10-18 18:17:52 -0700873TEST_F(CrasherTest, backtrace) {
874 std::string result;
875 int intercept_result;
876 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800877
878 StartProcess([]() {
879 abort();
880 });
Narayan Kamatha73df602017-05-24 15:07:25 +0100881 StartIntercept(&output_fd, kDebuggerdNativeBacktrace);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700882
883 std::this_thread::sleep_for(500ms);
884
885 sigval val;
886 val.sival_int = 1;
Josh Gaoa48b41b2019-12-13 14:11:04 -0800887 ASSERT_EQ(0, sigqueue(crasher_pid, BIONIC_SIGNAL_DEBUGGER, val)) << strerror(errno);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700888 FinishIntercept(&intercept_result);
889 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
890 ConsumeFd(std::move(output_fd), &result);
Jaesung Chung58778e12017-06-15 18:20:34 +0900891 ASSERT_BACKTRACE_FRAME(result, "read");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700892
893 int status;
894 ASSERT_EQ(0, waitpid(crasher_pid, &status, WNOHANG | WUNTRACED));
895
896 StartIntercept(&output_fd);
897 FinishCrasher();
898 AssertDeath(SIGABRT);
899 FinishIntercept(&intercept_result);
900 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
901 ConsumeFd(std::move(output_fd), &result);
Andreas Gampe26cbafb2017-06-22 20:14:43 -0700902 ASSERT_BACKTRACE_FRAME(result, "abort");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700903}
Josh Gaofca7ca32017-01-23 12:05:35 -0800904
905TEST_F(CrasherTest, PR_SET_DUMPABLE_0_crash) {
Josh Gao502cfd22017-02-17 01:39:15 -0800906 int intercept_result;
907 unique_fd output_fd;
Josh Gaofca7ca32017-01-23 12:05:35 -0800908 StartProcess([]() {
909 prctl(PR_SET_DUMPABLE, 0);
Josh Gao502cfd22017-02-17 01:39:15 -0800910 abort();
Josh Gaofca7ca32017-01-23 12:05:35 -0800911 });
Josh Gao502cfd22017-02-17 01:39:15 -0800912
913 StartIntercept(&output_fd);
914 FinishCrasher();
915 AssertDeath(SIGABRT);
916 FinishIntercept(&intercept_result);
917
918 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
919
920 std::string result;
921 ConsumeFd(std::move(output_fd), &result);
Andreas Gampe26cbafb2017-06-22 20:14:43 -0700922 ASSERT_BACKTRACE_FRAME(result, "abort");
Josh Gaofca7ca32017-01-23 12:05:35 -0800923}
924
Josh Gao502cfd22017-02-17 01:39:15 -0800925TEST_F(CrasherTest, capabilities) {
926 ASSERT_EQ(0U, getuid()) << "capability test requires root";
927
Josh Gaofca7ca32017-01-23 12:05:35 -0800928 StartProcess([]() {
Josh Gao502cfd22017-02-17 01:39:15 -0800929 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) != 0) {
930 err(1, "failed to set PR_SET_KEEPCAPS");
931 }
932
933 if (setresuid(1, 1, 1) != 0) {
934 err(1, "setresuid failed");
935 }
936
937 __user_cap_header_struct capheader;
938 __user_cap_data_struct capdata[2];
939 memset(&capheader, 0, sizeof(capheader));
940 memset(&capdata, 0, sizeof(capdata));
941
942 capheader.version = _LINUX_CAPABILITY_VERSION_3;
943 capheader.pid = 0;
944
945 // Turn on every third capability.
946 static_assert(CAP_LAST_CAP > 33, "CAP_LAST_CAP <= 32");
947 for (int i = 0; i < CAP_LAST_CAP; i += 3) {
948 capdata[CAP_TO_INDEX(i)].permitted |= CAP_TO_MASK(i);
949 capdata[CAP_TO_INDEX(i)].effective |= CAP_TO_MASK(i);
950 }
951
952 // Make sure CAP_SYS_PTRACE is off.
953 capdata[CAP_TO_INDEX(CAP_SYS_PTRACE)].permitted &= ~(CAP_TO_MASK(CAP_SYS_PTRACE));
954 capdata[CAP_TO_INDEX(CAP_SYS_PTRACE)].effective &= ~(CAP_TO_MASK(CAP_SYS_PTRACE));
955
956 if (capset(&capheader, &capdata[0]) != 0) {
957 err(1, "capset failed");
958 }
959
960 if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_CLEAR_ALL, 0, 0, 0) != 0) {
961 err(1, "failed to drop ambient capabilities");
962 }
963
Josh Gaoa5199a92017-04-03 13:18:34 -0700964 pthread_setname_np(pthread_self(), "thread_name");
Josh Gao502cfd22017-02-17 01:39:15 -0800965 raise(SIGSYS);
Josh Gaofca7ca32017-01-23 12:05:35 -0800966 });
Josh Gao502cfd22017-02-17 01:39:15 -0800967
968 unique_fd output_fd;
969 StartIntercept(&output_fd);
970 FinishCrasher();
971 AssertDeath(SIGSYS);
972
973 std::string result;
974 int intercept_result;
975 FinishIntercept(&intercept_result);
976 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
977 ConsumeFd(std::move(output_fd), &result);
Josh Gaoa5199a92017-04-03 13:18:34 -0700978 ASSERT_MATCH(result, R"(name: thread_name\s+>>> .+debuggerd_test(32|64) <<<)");
Jaesung Chung58778e12017-06-15 18:20:34 +0900979 ASSERT_BACKTRACE_FRAME(result, "tgkill");
Josh Gaofca7ca32017-01-23 12:05:35 -0800980}
Josh Gaoc3c8c022017-02-13 16:36:18 -0800981
Josh Gao2e7b8e22017-05-04 17:12:57 -0700982TEST_F(CrasherTest, fake_pid) {
983 int intercept_result;
984 unique_fd output_fd;
985
986 // Prime the getpid/gettid caches.
987 UNUSED(getpid());
988 UNUSED(gettid());
989
990 std::function<pid_t()> clone_fn = []() {
991 return syscall(__NR_clone, SIGCHLD, nullptr, nullptr, nullptr, nullptr);
992 };
993 StartProcess(
994 []() {
995 ASSERT_NE(getpid(), syscall(__NR_getpid));
996 ASSERT_NE(gettid(), syscall(__NR_gettid));
997 raise(SIGSEGV);
998 },
999 clone_fn);
1000
1001 StartIntercept(&output_fd);
1002 FinishCrasher();
1003 AssertDeath(SIGSEGV);
1004 FinishIntercept(&intercept_result);
1005
1006 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1007
1008 std::string result;
1009 ConsumeFd(std::move(output_fd), &result);
Jaesung Chung58778e12017-06-15 18:20:34 +09001010 ASSERT_BACKTRACE_FRAME(result, "tgkill");
Josh Gao2e7b8e22017-05-04 17:12:57 -07001011}
1012
Josh Gaoe04ca272018-01-16 15:38:17 -08001013static const char* const kDebuggerdSeccompPolicy =
1014 "/system/etc/seccomp_policy/crash_dump." ABI_STRING ".policy";
1015
Josh Gao70adac62018-02-22 11:38:33 -08001016static pid_t seccomp_fork_impl(void (*prejail)()) {
Josh Gao6f9eeec2018-09-12 13:55:47 -07001017 std::string policy;
1018 if (!android::base::ReadFileToString(kDebuggerdSeccompPolicy, &policy)) {
1019 PLOG(FATAL) << "failed to read policy file";
1020 }
1021
1022 // Allow a bunch of syscalls used by the tests.
1023 policy += "\nclone: 1";
1024 policy += "\nsigaltstack: 1";
1025 policy += "\nnanosleep: 1";
Christopher Ferrisab606682019-09-17 15:31:47 -07001026 policy += "\ngetrlimit: 1";
1027 policy += "\nugetrlimit: 1";
Josh Gao6f9eeec2018-09-12 13:55:47 -07001028
1029 FILE* tmp_file = tmpfile();
1030 if (!tmp_file) {
1031 PLOG(FATAL) << "tmpfile failed";
1032 }
1033
Christopher Ferris172b0a02019-09-18 17:48:30 -07001034 unique_fd tmp_fd(TEMP_FAILURE_RETRY(dup(fileno(tmp_file))));
Josh Gao6f9eeec2018-09-12 13:55:47 -07001035 if (!android::base::WriteStringToFd(policy, tmp_fd.get())) {
1036 PLOG(FATAL) << "failed to write policy to tmpfile";
1037 }
1038
1039 if (lseek(tmp_fd.get(), 0, SEEK_SET) != 0) {
1040 PLOG(FATAL) << "failed to seek tmp_fd";
Josh Gaoe04ca272018-01-16 15:38:17 -08001041 }
1042
1043 ScopedMinijail jail{minijail_new()};
1044 if (!jail) {
1045 LOG(FATAL) << "failed to create minijail";
1046 }
1047
1048 minijail_no_new_privs(jail.get());
1049 minijail_log_seccomp_filter_failures(jail.get());
1050 minijail_use_seccomp_filter(jail.get());
Josh Gao6f9eeec2018-09-12 13:55:47 -07001051 minijail_parse_seccomp_filters_from_fd(jail.get(), tmp_fd.release());
Josh Gaoe04ca272018-01-16 15:38:17 -08001052
1053 pid_t result = fork();
1054 if (result == -1) {
1055 return result;
1056 } else if (result != 0) {
1057 return result;
1058 }
1059
1060 // Spawn and detach a thread that spins forever.
1061 std::atomic<bool> thread_ready(false);
1062 std::thread thread([&jail, &thread_ready]() {
1063 minijail_enter(jail.get());
1064 thread_ready = true;
1065 for (;;)
1066 ;
1067 });
1068 thread.detach();
1069
1070 while (!thread_ready) {
1071 continue;
1072 }
1073
Josh Gao70adac62018-02-22 11:38:33 -08001074 if (prejail) {
1075 prejail();
1076 }
1077
Josh Gaoe04ca272018-01-16 15:38:17 -08001078 minijail_enter(jail.get());
1079 return result;
1080}
1081
Josh Gao70adac62018-02-22 11:38:33 -08001082static pid_t seccomp_fork() {
1083 return seccomp_fork_impl(nullptr);
1084}
1085
Josh Gaoe04ca272018-01-16 15:38:17 -08001086TEST_F(CrasherTest, seccomp_crash) {
1087 int intercept_result;
1088 unique_fd output_fd;
1089
1090 StartProcess([]() { abort(); }, &seccomp_fork);
1091
1092 StartIntercept(&output_fd);
1093 FinishCrasher();
1094 AssertDeath(SIGABRT);
1095 FinishIntercept(&intercept_result);
1096 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1097
1098 std::string result;
1099 ConsumeFd(std::move(output_fd), &result);
1100 ASSERT_BACKTRACE_FRAME(result, "abort");
1101}
1102
Josh Gao70adac62018-02-22 11:38:33 -08001103static pid_t seccomp_fork_rlimit() {
1104 return seccomp_fork_impl([]() {
1105 struct rlimit rlim = {
1106 .rlim_cur = 512 * 1024 * 1024,
1107 .rlim_max = 512 * 1024 * 1024,
1108 };
1109
1110 if (setrlimit(RLIMIT_AS, &rlim) != 0) {
1111 raise(SIGINT);
1112 }
1113 });
1114}
1115
1116TEST_F(CrasherTest, seccomp_crash_oom) {
1117 int intercept_result;
1118 unique_fd output_fd;
1119
1120 StartProcess(
1121 []() {
1122 std::vector<void*> vec;
1123 for (int i = 0; i < 512; ++i) {
1124 char* buf = static_cast<char*>(malloc(1024 * 1024));
1125 if (!buf) {
1126 abort();
1127 }
1128 memset(buf, 0xff, 1024 * 1024);
1129 vec.push_back(buf);
1130 }
1131 },
1132 &seccomp_fork_rlimit);
1133
1134 StartIntercept(&output_fd);
1135 FinishCrasher();
1136 AssertDeath(SIGABRT);
1137 FinishIntercept(&intercept_result);
1138 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1139
1140 // We can't actually generate a backtrace, just make sure that the process terminates.
1141}
1142
Josh Gaoe04ca272018-01-16 15:38:17 -08001143__attribute__((noinline)) extern "C" bool raise_debugger_signal(DebuggerdDumpType dump_type) {
1144 siginfo_t siginfo;
1145 siginfo.si_code = SI_QUEUE;
1146 siginfo.si_pid = getpid();
1147 siginfo.si_uid = getuid();
1148
1149 if (dump_type != kDebuggerdNativeBacktrace && dump_type != kDebuggerdTombstone) {
1150 PLOG(FATAL) << "invalid dump type";
1151 }
1152
1153 siginfo.si_value.sival_int = dump_type == kDebuggerdNativeBacktrace;
1154
Josh Gaoa48b41b2019-12-13 14:11:04 -08001155 if (syscall(__NR_rt_tgsigqueueinfo, getpid(), gettid(), BIONIC_SIGNAL_DEBUGGER, &siginfo) != 0) {
Josh Gaoe04ca272018-01-16 15:38:17 -08001156 PLOG(ERROR) << "libdebuggerd_client: failed to send signal to self";
1157 return false;
1158 }
1159
1160 return true;
1161}
1162
1163TEST_F(CrasherTest, seccomp_tombstone) {
1164 int intercept_result;
1165 unique_fd output_fd;
1166
1167 static const auto dump_type = kDebuggerdTombstone;
1168 StartProcess(
1169 []() {
1170 raise_debugger_signal(dump_type);
1171 _exit(0);
1172 },
1173 &seccomp_fork);
1174
1175 StartIntercept(&output_fd, dump_type);
1176 FinishCrasher();
1177 AssertDeath(0);
1178 FinishIntercept(&intercept_result);
1179 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1180
1181 std::string result;
1182 ConsumeFd(std::move(output_fd), &result);
1183 ASSERT_BACKTRACE_FRAME(result, "raise_debugger_signal");
1184}
1185
Josh Gao6f9eeec2018-09-12 13:55:47 -07001186extern "C" void foo() {
1187 LOG(INFO) << "foo";
1188 std::this_thread::sleep_for(1s);
1189}
1190
1191extern "C" void bar() {
1192 LOG(INFO) << "bar";
1193 std::this_thread::sleep_for(1s);
1194}
1195
Josh Gaoe04ca272018-01-16 15:38:17 -08001196TEST_F(CrasherTest, seccomp_backtrace) {
1197 int intercept_result;
1198 unique_fd output_fd;
1199
1200 static const auto dump_type = kDebuggerdNativeBacktrace;
1201 StartProcess(
1202 []() {
Josh Gao6f9eeec2018-09-12 13:55:47 -07001203 std::thread a(foo);
1204 std::thread b(bar);
1205
1206 std::this_thread::sleep_for(100ms);
1207
Josh Gaoe04ca272018-01-16 15:38:17 -08001208 raise_debugger_signal(dump_type);
1209 _exit(0);
1210 },
1211 &seccomp_fork);
1212
1213 StartIntercept(&output_fd, dump_type);
1214 FinishCrasher();
1215 AssertDeath(0);
1216 FinishIntercept(&intercept_result);
1217 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1218
1219 std::string result;
1220 ConsumeFd(std::move(output_fd), &result);
1221 ASSERT_BACKTRACE_FRAME(result, "raise_debugger_signal");
Josh Gao6f9eeec2018-09-12 13:55:47 -07001222 ASSERT_BACKTRACE_FRAME(result, "foo");
1223 ASSERT_BACKTRACE_FRAME(result, "bar");
Josh Gaoe04ca272018-01-16 15:38:17 -08001224}
1225
1226TEST_F(CrasherTest, seccomp_crash_logcat) {
1227 StartProcess([]() { abort(); }, &seccomp_fork);
1228 FinishCrasher();
1229
1230 // Make sure we don't get SIGSYS when trying to dump a crash to logcat.
1231 AssertDeath(SIGABRT);
1232}
1233
Josh Gaofd13bf02017-08-18 15:37:26 -07001234TEST_F(CrasherTest, competing_tracer) {
1235 int intercept_result;
1236 unique_fd output_fd;
1237 StartProcess([]() {
Josh Gao2b2ae0c2017-08-21 14:31:17 -07001238 raise(SIGABRT);
Josh Gaofd13bf02017-08-18 15:37:26 -07001239 });
1240
1241 StartIntercept(&output_fd);
Josh Gaofd13bf02017-08-18 15:37:26 -07001242
1243 ASSERT_EQ(0, ptrace(PTRACE_SEIZE, crasher_pid, 0, 0));
Josh Gao2b2ae0c2017-08-21 14:31:17 -07001244 FinishCrasher();
Josh Gaofd13bf02017-08-18 15:37:26 -07001245
1246 int status;
Christopher Ferris172b0a02019-09-18 17:48:30 -07001247 ASSERT_EQ(crasher_pid, TEMP_FAILURE_RETRY(waitpid(crasher_pid, &status, 0)));
Josh Gaofd13bf02017-08-18 15:37:26 -07001248 ASSERT_TRUE(WIFSTOPPED(status));
1249 ASSERT_EQ(SIGABRT, WSTOPSIG(status));
1250
1251 ASSERT_EQ(0, ptrace(PTRACE_CONT, crasher_pid, 0, SIGABRT));
1252 FinishIntercept(&intercept_result);
1253 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1254
1255 std::string result;
1256 ConsumeFd(std::move(output_fd), &result);
1257 std::string regex = R"(failed to attach to thread \d+, already traced by )";
1258 regex += std::to_string(gettid());
1259 regex += R"( \(.+debuggerd_test)";
1260 ASSERT_MATCH(result, regex.c_str());
1261
Christopher Ferris172b0a02019-09-18 17:48:30 -07001262 ASSERT_EQ(crasher_pid, TEMP_FAILURE_RETRY(waitpid(crasher_pid, &status, 0)));
Josh Gao2b2ae0c2017-08-21 14:31:17 -07001263 ASSERT_TRUE(WIFSTOPPED(status));
1264 ASSERT_EQ(SIGABRT, WSTOPSIG(status));
1265
Josh Gaofd13bf02017-08-18 15:37:26 -07001266 ASSERT_EQ(0, ptrace(PTRACE_DETACH, crasher_pid, 0, SIGABRT));
1267 AssertDeath(SIGABRT);
1268}
1269
Josh Gaobf06a402018-08-27 16:34:01 -07001270TEST_F(CrasherTest, fdsan_warning_abort_message) {
1271 int intercept_result;
1272 unique_fd output_fd;
1273
1274 StartProcess([]() {
1275 android_fdsan_set_error_level(ANDROID_FDSAN_ERROR_LEVEL_WARN_ONCE);
Christopher Ferris172b0a02019-09-18 17:48:30 -07001276 unique_fd fd(TEMP_FAILURE_RETRY(open("/dev/null", O_RDONLY | O_CLOEXEC)));
Josh Gaobf06a402018-08-27 16:34:01 -07001277 if (fd == -1) {
1278 abort();
1279 }
1280 close(fd.get());
1281 _exit(0);
1282 });
1283
1284 StartIntercept(&output_fd);
1285 FinishCrasher();
1286 AssertDeath(0);
1287 FinishIntercept(&intercept_result);
1288 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1289
1290 std::string result;
1291 ConsumeFd(std::move(output_fd), &result);
1292 ASSERT_MATCH(result, "Abort message: 'attempted to close");
1293}
1294
Josh Gaoc3c8c022017-02-13 16:36:18 -08001295TEST(crash_dump, zombie) {
1296 pid_t forkpid = fork();
1297
Josh Gaoc3c8c022017-02-13 16:36:18 -08001298 pid_t rc;
1299 int status;
1300
1301 if (forkpid == 0) {
1302 errno = 0;
1303 rc = waitpid(-1, &status, WNOHANG | __WALL | __WNOTHREAD);
1304 if (rc != -1 || errno != ECHILD) {
1305 errx(2, "first waitpid returned %d (%s), expected failure with ECHILD", rc, strerror(errno));
1306 }
1307
Josh Gaoa48b41b2019-12-13 14:11:04 -08001308 raise(BIONIC_SIGNAL_DEBUGGER);
Josh Gaoc3c8c022017-02-13 16:36:18 -08001309
1310 errno = 0;
Christopher Ferris172b0a02019-09-18 17:48:30 -07001311 rc = TEMP_FAILURE_RETRY(waitpid(-1, &status, __WALL | __WNOTHREAD));
Josh Gaoc3c8c022017-02-13 16:36:18 -08001312 if (rc != -1 || errno != ECHILD) {
1313 errx(2, "second waitpid returned %d (%s), expected failure with ECHILD", rc, strerror(errno));
1314 }
1315 _exit(0);
1316 } else {
Christopher Ferris172b0a02019-09-18 17:48:30 -07001317 rc = TEMP_FAILURE_RETRY(waitpid(forkpid, &status, 0));
Josh Gaoc3c8c022017-02-13 16:36:18 -08001318 ASSERT_EQ(forkpid, rc);
1319 ASSERT_TRUE(WIFEXITED(status));
1320 ASSERT_EQ(0, WEXITSTATUS(status));
1321 }
1322}
Josh Gao352a8452017-03-30 16:46:21 -07001323
1324TEST(tombstoned, no_notify) {
1325 // Do this a few times.
1326 for (int i = 0; i < 3; ++i) {
1327 pid_t pid = 123'456'789 + i;
1328
1329 unique_fd intercept_fd, output_fd;
Narayan Kamathca5e9082017-06-02 15:42:06 +01001330 InterceptStatus status;
1331 tombstoned_intercept(pid, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
1332 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gao352a8452017-03-30 16:46:21 -07001333
1334 {
1335 unique_fd tombstoned_socket, input_fd;
Narayan Kamatha73df602017-05-24 15:07:25 +01001336 ASSERT_TRUE(tombstoned_connect(pid, &tombstoned_socket, &input_fd, kDebuggerdTombstone));
Josh Gao352a8452017-03-30 16:46:21 -07001337 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), &pid, sizeof(pid)));
1338 }
1339
1340 pid_t read_pid;
1341 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), &read_pid, sizeof(read_pid)));
1342 ASSERT_EQ(read_pid, pid);
1343 }
1344}
1345
1346TEST(tombstoned, stress) {
1347 // Spawn threads to simultaneously do a bunch of failing dumps and a bunch of successful dumps.
1348 static constexpr int kDumpCount = 100;
1349
1350 std::atomic<bool> start(false);
1351 std::vector<std::thread> threads;
1352 threads.emplace_back([&start]() {
1353 while (!start) {
1354 continue;
1355 }
1356
1357 // Use a way out of range pid, to avoid stomping on an actual process.
1358 pid_t pid_base = 1'000'000;
1359
1360 for (int dump = 0; dump < kDumpCount; ++dump) {
1361 pid_t pid = pid_base + dump;
1362
1363 unique_fd intercept_fd, output_fd;
Narayan Kamathca5e9082017-06-02 15:42:06 +01001364 InterceptStatus status;
1365 tombstoned_intercept(pid, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
1366 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gao352a8452017-03-30 16:46:21 -07001367
1368 // Pretend to crash, and then immediately close the socket.
1369 unique_fd sockfd(socket_local_client(kTombstonedCrashSocketName,
1370 ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_SEQPACKET));
1371 if (sockfd == -1) {
1372 FAIL() << "failed to connect to tombstoned: " << strerror(errno);
1373 }
1374 TombstonedCrashPacket packet = {};
1375 packet.packet_type = CrashPacketType::kDumpRequest;
1376 packet.packet.dump_request.pid = pid;
1377 if (TEMP_FAILURE_RETRY(write(sockfd, &packet, sizeof(packet))) != sizeof(packet)) {
1378 FAIL() << "failed to write to tombstoned: " << strerror(errno);
1379 }
1380
1381 continue;
1382 }
1383 });
1384
1385 threads.emplace_back([&start]() {
1386 while (!start) {
1387 continue;
1388 }
1389
1390 // Use a way out of range pid, to avoid stomping on an actual process.
1391 pid_t pid_base = 2'000'000;
1392
1393 for (int dump = 0; dump < kDumpCount; ++dump) {
1394 pid_t pid = pid_base + dump;
1395
1396 unique_fd intercept_fd, output_fd;
Narayan Kamathca5e9082017-06-02 15:42:06 +01001397 InterceptStatus status;
1398 tombstoned_intercept(pid, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
1399 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gao352a8452017-03-30 16:46:21 -07001400
1401 {
1402 unique_fd tombstoned_socket, input_fd;
Narayan Kamatha73df602017-05-24 15:07:25 +01001403 ASSERT_TRUE(tombstoned_connect(pid, &tombstoned_socket, &input_fd, kDebuggerdTombstone));
Josh Gao352a8452017-03-30 16:46:21 -07001404 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), &pid, sizeof(pid)));
1405 tombstoned_notify_completion(tombstoned_socket.get());
1406 }
1407
1408 // TODO: Fix the race that requires this sleep.
1409 std::this_thread::sleep_for(50ms);
1410
1411 pid_t read_pid;
1412 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), &read_pid, sizeof(read_pid)));
1413 ASSERT_EQ(read_pid, pid);
1414 }
1415 });
1416
1417 start = true;
1418
1419 for (std::thread& thread : threads) {
1420 thread.join();
1421 }
1422}
Narayan Kamathca5e9082017-06-02 15:42:06 +01001423
1424TEST(tombstoned, java_trace_intercept_smoke) {
1425 // Using a "real" PID is a little dangerous here - if the test fails
1426 // or crashes, we might end up getting a bogus / unreliable stack
1427 // trace.
1428 const pid_t self = getpid();
1429
1430 unique_fd intercept_fd, output_fd;
1431 InterceptStatus status;
1432 tombstoned_intercept(self, &intercept_fd, &output_fd, &status, kDebuggerdJavaBacktrace);
1433 ASSERT_EQ(InterceptStatus::kRegistered, status);
1434
Josh Gao76e1e302021-01-26 15:53:11 -08001435 // First connect to tombstoned requesting a native tombstone. This
Narayan Kamathca5e9082017-06-02 15:42:06 +01001436 // should result in a "regular" FD and not the installed intercept.
1437 const char native[] = "native";
1438 unique_fd tombstoned_socket, input_fd;
Josh Gao76e1e302021-01-26 15:53:11 -08001439 ASSERT_TRUE(tombstoned_connect(self, &tombstoned_socket, &input_fd, kDebuggerdTombstone));
Narayan Kamathca5e9082017-06-02 15:42:06 +01001440 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), native, sizeof(native)));
1441 tombstoned_notify_completion(tombstoned_socket.get());
1442
1443 // Then, connect to tombstoned asking for a java backtrace. This *should*
1444 // trigger the intercept.
1445 const char java[] = "java";
1446 ASSERT_TRUE(tombstoned_connect(self, &tombstoned_socket, &input_fd, kDebuggerdJavaBacktrace));
1447 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), java, sizeof(java)));
1448 tombstoned_notify_completion(tombstoned_socket.get());
1449
1450 char outbuf[sizeof(java)];
1451 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), outbuf, sizeof(outbuf)));
1452 ASSERT_STREQ("java", outbuf);
1453}
1454
1455TEST(tombstoned, multiple_intercepts) {
1456 const pid_t fake_pid = 1'234'567;
1457 unique_fd intercept_fd, output_fd;
1458 InterceptStatus status;
1459 tombstoned_intercept(fake_pid, &intercept_fd, &output_fd, &status, kDebuggerdJavaBacktrace);
1460 ASSERT_EQ(InterceptStatus::kRegistered, status);
1461
1462 unique_fd intercept_fd_2, output_fd_2;
1463 tombstoned_intercept(fake_pid, &intercept_fd_2, &output_fd_2, &status, kDebuggerdNativeBacktrace);
1464 ASSERT_EQ(InterceptStatus::kFailedAlreadyRegistered, status);
1465}
1466
1467TEST(tombstoned, intercept_any) {
1468 const pid_t fake_pid = 1'234'567;
1469
1470 unique_fd intercept_fd, output_fd;
1471 InterceptStatus status;
1472 tombstoned_intercept(fake_pid, &intercept_fd, &output_fd, &status, kDebuggerdNativeBacktrace);
1473 ASSERT_EQ(InterceptStatus::kRegistered, status);
1474
1475 const char any[] = "any";
1476 unique_fd tombstoned_socket, input_fd;
1477 ASSERT_TRUE(tombstoned_connect(fake_pid, &tombstoned_socket, &input_fd, kDebuggerdAnyIntercept));
1478 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), any, sizeof(any)));
1479 tombstoned_notify_completion(tombstoned_socket.get());
1480
1481 char outbuf[sizeof(any)];
1482 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), outbuf, sizeof(outbuf)));
1483 ASSERT_STREQ("any", outbuf);
1484}
Josh Gao2b22ae12018-09-12 14:51:03 -07001485
1486TEST(tombstoned, interceptless_backtrace) {
1487 // Generate 50 backtraces, and then check to see that we haven't created 50 new tombstones.
1488 auto get_tombstone_timestamps = []() -> std::map<int, time_t> {
1489 std::map<int, time_t> result;
1490 for (int i = 0; i < 99; ++i) {
1491 std::string path = android::base::StringPrintf("/data/tombstones/tombstone_%02d", i);
1492 struct stat st;
1493 if (stat(path.c_str(), &st) == 0) {
1494 result[i] = st.st_mtim.tv_sec;
1495 }
1496 }
1497 return result;
1498 };
1499
1500 auto before = get_tombstone_timestamps();
1501 for (int i = 0; i < 50; ++i) {
1502 raise_debugger_signal(kDebuggerdNativeBacktrace);
1503 }
1504 auto after = get_tombstone_timestamps();
1505
1506 int diff = 0;
1507 for (int i = 0; i < 99; ++i) {
1508 if (after.count(i) == 0) {
1509 continue;
1510 }
1511 if (before.count(i) == 0) {
1512 ++diff;
1513 continue;
1514 }
1515 if (before[i] != after[i]) {
1516 ++diff;
1517 }
1518 }
1519
1520 // We can't be sure that nothing's crash looping in the background.
1521 // This should be good enough, though...
1522 ASSERT_LT(diff, 10) << "too many new tombstones; is something crashing in the background?";
1523}
Christopher Ferris481e8372019-07-15 17:13:24 -07001524
1525static __attribute__((__noinline__)) void overflow_stack(void* p) {
1526 void* buf[1];
1527 buf[0] = p;
1528 static volatile void* global = buf;
1529 if (global) {
1530 global = buf;
1531 overflow_stack(&buf);
1532 }
1533}
1534
1535TEST_F(CrasherTest, stack_overflow) {
1536 int intercept_result;
1537 unique_fd output_fd;
1538 StartProcess([]() { overflow_stack(nullptr); });
1539
1540 StartIntercept(&output_fd);
1541 FinishCrasher();
1542 AssertDeath(SIGSEGV);
1543 FinishIntercept(&intercept_result);
1544
1545 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1546
1547 std::string result;
1548 ConsumeFd(std::move(output_fd), &result);
1549 ASSERT_MATCH(result, R"(Cause: stack pointer[^\n]*stack overflow.\n)");
1550}
Josh Gao76e1e302021-01-26 15:53:11 -08001551
Christopher Ferrisfe751c52021-04-16 09:40:40 -07001552static bool CopySharedLibrary(const char* tmp_dir, std::string* tmp_so_name) {
1553 std::string test_lib(testing::internal::GetArgvs()[0]);
1554 auto const value = test_lib.find_last_of('/');
1555 if (value == std::string::npos) {
1556 test_lib = "./";
1557 } else {
1558 test_lib = test_lib.substr(0, value + 1) + "./";
1559 }
1560 test_lib += "libcrash_test.so";
1561
1562 *tmp_so_name = std::string(tmp_dir) + "/libcrash_test.so";
1563 std::string cp_cmd = android::base::StringPrintf("cp %s %s", test_lib.c_str(), tmp_dir);
1564
1565 // Copy the shared so to a tempory directory.
1566 return system(cp_cmd.c_str()) == 0;
1567}
1568
1569TEST_F(CrasherTest, unreadable_elf) {
1570 int intercept_result;
1571 unique_fd output_fd;
1572 StartProcess([]() {
1573 TemporaryDir td;
1574 std::string tmp_so_name;
1575 if (!CopySharedLibrary(td.path, &tmp_so_name)) {
1576 _exit(1);
1577 }
1578 void* handle = dlopen(tmp_so_name.c_str(), RTLD_NOW);
1579 if (handle == nullptr) {
1580 _exit(1);
1581 }
1582 // Delete the original shared library so that we get the warning
1583 // about unreadable elf files.
1584 if (unlink(tmp_so_name.c_str()) == -1) {
1585 _exit(1);
1586 }
1587 void (*crash_func)() = reinterpret_cast<void (*)()>(dlsym(handle, "crash"));
1588 if (crash_func == nullptr) {
1589 _exit(1);
1590 }
1591 crash_func();
1592 });
1593
1594 StartIntercept(&output_fd);
1595 FinishCrasher();
1596 AssertDeath(SIGSEGV);
1597 FinishIntercept(&intercept_result);
1598
1599 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1600
1601 std::string result;
1602 ConsumeFd(std::move(output_fd), &result);
1603 ASSERT_MATCH(result, R"(NOTE: Function names and BuildId information is missing )");
1604}
1605
Josh Gao76e1e302021-01-26 15:53:11 -08001606TEST(tombstoned, proto) {
1607 const pid_t self = getpid();
1608 unique_fd tombstoned_socket, text_fd, proto_fd;
1609 ASSERT_TRUE(
1610 tombstoned_connect(self, &tombstoned_socket, &text_fd, &proto_fd, kDebuggerdTombstoneProto));
1611
1612 tombstoned_notify_completion(tombstoned_socket.get());
1613
1614 ASSERT_NE(-1, text_fd.get());
1615 ASSERT_NE(-1, proto_fd.get());
1616
1617 struct stat text_st;
1618 ASSERT_EQ(0, fstat(text_fd.get(), &text_st));
1619
1620 // Give tombstoned some time to link the files into place.
1621 std::this_thread::sleep_for(100ms);
1622
1623 // Find the tombstone.
Christopher Ferris35da2882021-02-17 15:39:06 -08001624 std::optional<std::string> tombstone_file;
1625 std::unique_ptr<DIR, decltype(&closedir)> dir_h(opendir("/data/tombstones"), closedir);
1626 ASSERT_TRUE(dir_h != nullptr);
1627 std::regex tombstone_re("tombstone_\\d+");
1628 dirent* entry;
1629 while ((entry = readdir(dir_h.get())) != nullptr) {
1630 if (!std::regex_match(entry->d_name, tombstone_re)) {
1631 continue;
1632 }
1633 std::string path = android::base::StringPrintf("/data/tombstones/%s", entry->d_name);
Josh Gao76e1e302021-01-26 15:53:11 -08001634
1635 struct stat st;
1636 if (TEMP_FAILURE_RETRY(stat(path.c_str(), &st)) != 0) {
1637 continue;
1638 }
1639
1640 if (st.st_dev == text_st.st_dev && st.st_ino == text_st.st_ino) {
Christopher Ferris35da2882021-02-17 15:39:06 -08001641 tombstone_file = path;
Josh Gao76e1e302021-01-26 15:53:11 -08001642 break;
1643 }
1644 }
1645
Christopher Ferris35da2882021-02-17 15:39:06 -08001646 ASSERT_TRUE(tombstone_file);
1647 std::string proto_path = tombstone_file.value() + ".pb";
Josh Gao76e1e302021-01-26 15:53:11 -08001648
1649 struct stat proto_fd_st;
1650 struct stat proto_file_st;
1651 ASSERT_EQ(0, fstat(proto_fd.get(), &proto_fd_st));
1652 ASSERT_EQ(0, stat(proto_path.c_str(), &proto_file_st));
1653
1654 ASSERT_EQ(proto_fd_st.st_dev, proto_file_st.st_dev);
1655 ASSERT_EQ(proto_fd_st.st_ino, proto_file_st.st_ino);
1656}
1657
1658TEST(tombstoned, proto_intercept) {
1659 const pid_t self = getpid();
1660 unique_fd intercept_fd, output_fd;
1661 InterceptStatus status;
1662
1663 tombstoned_intercept(self, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
1664 ASSERT_EQ(InterceptStatus::kRegistered, status);
1665
1666 unique_fd tombstoned_socket, text_fd, proto_fd;
1667 ASSERT_TRUE(
1668 tombstoned_connect(self, &tombstoned_socket, &text_fd, &proto_fd, kDebuggerdTombstoneProto));
1669 ASSERT_TRUE(android::base::WriteStringToFd("foo", text_fd.get()));
1670 tombstoned_notify_completion(tombstoned_socket.get());
1671
1672 text_fd.reset();
1673
1674 std::string output;
1675 ASSERT_TRUE(android::base::ReadFdToString(output_fd, &output));
1676 ASSERT_EQ("foo", output);
1677}