blob: f24c4fcc6bd3f99de2d94f9d21ee73a8e5eab49d [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>
Mitch Phillips78f06702021-06-01 14:35:43 -070054#include <gmock/gmock.h>
Josh Gaocbe70cb2016-10-18 18:17:52 -070055#include <gtest/gtest.h>
56
Josh Gaoe04ca272018-01-16 15:38:17 -080057#include <libminijail.h>
58#include <scoped_minijail.h>
59
Narayan Kamath2d377cd2017-05-10 10:58:59 +010060#include "debuggerd/handler.h"
Mitch Phillips5ddcea22021-04-19 09:59:17 -070061#include "libdebuggerd/utility.h"
Narayan Kamath2d377cd2017-05-10 10:58:59 +010062#include "protocol.h"
63#include "tombstoned/tombstoned.h"
64#include "util.h"
65
Josh Gaocbe70cb2016-10-18 18:17:52 -070066using namespace std::chrono_literals;
Josh Gao5f87bbd2019-01-09 17:01:49 -080067
68using android::base::SendFileDescriptors;
Josh Gaocbe70cb2016-10-18 18:17:52 -070069using android::base::unique_fd;
Mitch Phillips78f06702021-06-01 14:35:43 -070070using ::testing::HasSubstr;
Josh Gaocbe70cb2016-10-18 18:17:52 -070071
72#if defined(__LP64__)
Josh Gaocbe70cb2016-10-18 18:17:52 -070073#define ARCH_SUFFIX "64"
74#else
Josh Gaocbe70cb2016-10-18 18:17:52 -070075#define ARCH_SUFFIX ""
76#endif
77
Elliott Hughese4781d52021-03-17 09:15:15 -070078constexpr char kWaitForDebuggerKey[] = "debug.debuggerd.wait_for_debugger";
Josh Gaocbe70cb2016-10-18 18:17:52 -070079
80#define TIMEOUT(seconds, expr) \
81 [&]() { \
82 struct sigaction old_sigaction; \
83 struct sigaction new_sigaction = {}; \
84 new_sigaction.sa_handler = [](int) {}; \
85 if (sigaction(SIGALRM, &new_sigaction, &new_sigaction) != 0) { \
86 err(1, "sigaction failed"); \
87 } \
88 alarm(seconds); \
89 auto value = expr; \
90 int saved_errno = errno; \
91 if (sigaction(SIGALRM, &old_sigaction, nullptr) != 0) { \
92 err(1, "sigaction failed"); \
93 } \
94 alarm(0); \
95 errno = saved_errno; \
96 return value; \
97 }()
98
Chih-Hung Hsieh3249b3a2018-05-11 16:01:21 -070099// Backtrace frame dump could contain:
100// #01 pc 0001cded /data/tmp/debuggerd_test32 (raise_debugger_signal+80)
101// or
102// #01 pc 00022a09 /data/tmp/debuggerd_test32 (offset 0x12000) (raise_debugger_signal+80)
Josh Gaoe04ca272018-01-16 15:38:17 -0800103#define ASSERT_BACKTRACE_FRAME(result, frame_name) \
Chih-Hung Hsieh3249b3a2018-05-11 16:01:21 -0700104 ASSERT_MATCH(result, \
105 R"(#\d\d pc [0-9a-f]+\s+ \S+ (\(offset 0x[0-9a-f]+\) )?\()" frame_name R"(\+)");
Jaesung Chung58778e12017-06-15 18:20:34 +0900106
Mitch Phillips7168a212021-03-09 16:53:23 -0800107// Enable GWP-ASan at the start of this process. GWP-ASan is enabled using
108// process sampling, so we need to ensure we force GWP-ASan on.
109__attribute__((constructor)) static void enable_gwp_asan() {
110 bool force = true;
111 android_mallopt(M_INITIALIZE_GWP_ASAN, &force, sizeof(force));
112}
113
Narayan Kamatha73df602017-05-24 15:07:25 +0100114static void tombstoned_intercept(pid_t target_pid, unique_fd* intercept_fd, unique_fd* output_fd,
Narayan Kamathca5e9082017-06-02 15:42:06 +0100115 InterceptStatus* status, DebuggerdDumpType intercept_type) {
Josh Gao460b3362017-03-30 16:40:47 -0700116 intercept_fd->reset(socket_local_client(kTombstonedInterceptSocketName,
117 ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_SEQPACKET));
118 if (intercept_fd->get() == -1) {
119 FAIL() << "failed to contact tombstoned: " << strerror(errno);
120 }
121
Nick Desaulniers67d52aa2019-10-07 23:28:15 -0700122 InterceptRequest req = {
123 .dump_type = intercept_type,
124 .pid = target_pid,
125 };
Josh Gao460b3362017-03-30 16:40:47 -0700126
127 unique_fd output_pipe_write;
128 if (!Pipe(output_fd, &output_pipe_write)) {
129 FAIL() << "failed to create output pipe: " << strerror(errno);
130 }
131
132 std::string pipe_size_str;
133 int pipe_buffer_size;
134 if (!android::base::ReadFileToString("/proc/sys/fs/pipe-max-size", &pipe_size_str)) {
135 FAIL() << "failed to read /proc/sys/fs/pipe-max-size: " << strerror(errno);
136 }
137
138 pipe_size_str = android::base::Trim(pipe_size_str);
139
140 if (!android::base::ParseInt(pipe_size_str.c_str(), &pipe_buffer_size, 0)) {
141 FAIL() << "failed to parse pipe max size";
142 }
143
144 if (fcntl(output_fd->get(), F_SETPIPE_SZ, pipe_buffer_size) != pipe_buffer_size) {
145 FAIL() << "failed to set pipe size: " << strerror(errno);
146 }
147
Josh Gao5675f3c2017-06-01 12:19:53 -0700148 ASSERT_GE(pipe_buffer_size, 1024 * 1024);
149
Josh Gao5f87bbd2019-01-09 17:01:49 -0800150 ssize_t rc = SendFileDescriptors(intercept_fd->get(), &req, sizeof(req), output_pipe_write.get());
151 output_pipe_write.reset();
152 if (rc != sizeof(req)) {
Josh Gao460b3362017-03-30 16:40:47 -0700153 FAIL() << "failed to send output fd to tombstoned: " << strerror(errno);
154 }
155
156 InterceptResponse response;
Josh Gao5f87bbd2019-01-09 17:01:49 -0800157 rc = TEMP_FAILURE_RETRY(read(intercept_fd->get(), &response, sizeof(response)));
Josh Gao460b3362017-03-30 16:40:47 -0700158 if (rc == -1) {
159 FAIL() << "failed to read response from tombstoned: " << strerror(errno);
160 } else if (rc == 0) {
161 FAIL() << "failed to read response from tombstoned (EOF)";
162 } else if (rc != sizeof(response)) {
163 FAIL() << "received packet of unexpected length from tombstoned: expected " << sizeof(response)
164 << ", received " << rc;
165 }
166
Narayan Kamathca5e9082017-06-02 15:42:06 +0100167 *status = response.status;
Josh Gao460b3362017-03-30 16:40:47 -0700168}
169
Josh Gaocbe70cb2016-10-18 18:17:52 -0700170class CrasherTest : public ::testing::Test {
171 public:
172 pid_t crasher_pid = -1;
Elliott Hughese4781d52021-03-17 09:15:15 -0700173 bool previous_wait_for_debugger;
Josh Gaocbe70cb2016-10-18 18:17:52 -0700174 unique_fd crasher_pipe;
175 unique_fd intercept_fd;
176
177 CrasherTest();
178 ~CrasherTest();
179
Narayan Kamatha73df602017-05-24 15:07:25 +0100180 void StartIntercept(unique_fd* output_fd, DebuggerdDumpType intercept_type = kDebuggerdTombstone);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700181
182 // Returns -1 if we fail to read a response from tombstoned, otherwise the received return code.
183 void FinishIntercept(int* result);
184
Josh Gao2e7b8e22017-05-04 17:12:57 -0700185 void StartProcess(std::function<void()> function, std::function<pid_t()> forker = fork);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700186 void StartCrasher(const std::string& crash_type);
187 void FinishCrasher();
188 void AssertDeath(int signo);
Peter Collingbourne10e428d2020-07-17 14:49:31 -0700189
190 static void Trap(void* ptr);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700191};
192
193CrasherTest::CrasherTest() {
Elliott Hughese4781d52021-03-17 09:15:15 -0700194 previous_wait_for_debugger = android::base::GetBoolProperty(kWaitForDebuggerKey, false);
195 android::base::SetProperty(kWaitForDebuggerKey, "0");
196
197 // Clear the old property too, just in case someone's been using it
198 // on this device. (We only document the new name, but we still support
199 // the old name so we don't break anyone's existing setups.)
200 android::base::SetProperty("debug.debuggerd.wait_for_gdb", "0");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700201}
202
203CrasherTest::~CrasherTest() {
204 if (crasher_pid != -1) {
205 kill(crasher_pid, SIGKILL);
206 int status;
Christopher Ferris172b0a02019-09-18 17:48:30 -0700207 TEMP_FAILURE_RETRY(waitpid(crasher_pid, &status, WUNTRACED));
Josh Gaocbe70cb2016-10-18 18:17:52 -0700208 }
209
Elliott Hughese4781d52021-03-17 09:15:15 -0700210 android::base::SetProperty(kWaitForDebuggerKey, previous_wait_for_debugger ? "1" : "0");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700211}
212
Narayan Kamatha73df602017-05-24 15:07:25 +0100213void CrasherTest::StartIntercept(unique_fd* output_fd, DebuggerdDumpType intercept_type) {
Josh Gaocbe70cb2016-10-18 18:17:52 -0700214 if (crasher_pid == -1) {
215 FAIL() << "crasher hasn't been started";
216 }
217
Narayan Kamathca5e9082017-06-02 15:42:06 +0100218 InterceptStatus status;
219 tombstoned_intercept(crasher_pid, &this->intercept_fd, output_fd, &status, intercept_type);
220 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700221}
222
223void CrasherTest::FinishIntercept(int* result) {
224 InterceptResponse response;
225
Christopher Ferris11555f02019-09-20 14:18:55 -0700226 ssize_t rc = TIMEOUT(30, read(intercept_fd.get(), &response, sizeof(response)));
Josh Gaocbe70cb2016-10-18 18:17:52 -0700227 if (rc == -1) {
228 FAIL() << "failed to read response from tombstoned: " << strerror(errno);
229 } else if (rc == 0) {
230 *result = -1;
231 } else if (rc != sizeof(response)) {
232 FAIL() << "received packet of unexpected length from tombstoned: expected " << sizeof(response)
233 << ", received " << rc;
234 } else {
Josh Gao460b3362017-03-30 16:40:47 -0700235 *result = response.status == InterceptStatus::kStarted ? 1 : 0;
Josh Gaocbe70cb2016-10-18 18:17:52 -0700236 }
237}
238
Josh Gao2e7b8e22017-05-04 17:12:57 -0700239void CrasherTest::StartProcess(std::function<void()> function, std::function<pid_t()> forker) {
Josh Gaofca7ca32017-01-23 12:05:35 -0800240 unique_fd read_pipe;
Josh Gaocbe70cb2016-10-18 18:17:52 -0700241 unique_fd crasher_read_pipe;
242 if (!Pipe(&crasher_read_pipe, &crasher_pipe)) {
243 FAIL() << "failed to create pipe: " << strerror(errno);
244 }
245
Josh Gao2e7b8e22017-05-04 17:12:57 -0700246 crasher_pid = forker();
Josh Gaocbe70cb2016-10-18 18:17:52 -0700247 if (crasher_pid == -1) {
248 FAIL() << "fork failed: " << strerror(errno);
249 } else if (crasher_pid == 0) {
Josh Gao502cfd22017-02-17 01:39:15 -0800250 char dummy;
251 crasher_pipe.reset();
252 TEMP_FAILURE_RETRY(read(crasher_read_pipe.get(), &dummy, 1));
Josh Gaofca7ca32017-01-23 12:05:35 -0800253 function();
254 _exit(0);
255 }
256}
257
Josh Gaocbe70cb2016-10-18 18:17:52 -0700258void CrasherTest::FinishCrasher() {
259 if (crasher_pipe == -1) {
260 FAIL() << "crasher pipe uninitialized";
261 }
262
Christopher Ferris172b0a02019-09-18 17:48:30 -0700263 ssize_t rc = TEMP_FAILURE_RETRY(write(crasher_pipe.get(), "\n", 1));
Josh Gaocbe70cb2016-10-18 18:17:52 -0700264 if (rc == -1) {
265 FAIL() << "failed to write to crasher pipe: " << strerror(errno);
266 } else if (rc == 0) {
267 FAIL() << "crasher pipe was closed";
268 }
269}
270
271void CrasherTest::AssertDeath(int signo) {
272 int status;
Christopher Ferris11555f02019-09-20 14:18:55 -0700273 pid_t pid = TIMEOUT(30, waitpid(crasher_pid, &status, 0));
Josh Gaocbe70cb2016-10-18 18:17:52 -0700274 if (pid != crasher_pid) {
Christopher Ferrisafc0ff72019-06-26 15:08:51 -0700275 printf("failed to wait for crasher (expected pid %d, return value %d): %s\n", crasher_pid, pid,
276 strerror(errno));
Josh Gao2b2ae0c2017-08-21 14:31:17 -0700277 sleep(100);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700278 FAIL() << "failed to wait for crasher: " << strerror(errno);
279 }
280
Josh Gaoe06f2a42017-04-27 16:50:38 -0700281 if (signo == 0) {
Christopher Ferris67022562021-04-16 13:30:32 -0700282 ASSERT_TRUE(WIFEXITED(status)) << "Terminated due to unexpected signal " << WTERMSIG(status);
Josh Gaoe06f2a42017-04-27 16:50:38 -0700283 ASSERT_EQ(0, WEXITSTATUS(signo));
284 } else {
285 ASSERT_FALSE(WIFEXITED(status));
286 ASSERT_TRUE(WIFSIGNALED(status)) << "crasher didn't terminate via a signal";
287 ASSERT_EQ(signo, WTERMSIG(status));
Josh Gaocbe70cb2016-10-18 18:17:52 -0700288 }
Josh Gaocbe70cb2016-10-18 18:17:52 -0700289 crasher_pid = -1;
290}
291
292static void ConsumeFd(unique_fd fd, std::string* output) {
293 constexpr size_t read_length = PAGE_SIZE;
294 std::string result;
295
296 while (true) {
297 size_t offset = result.size();
298 result.resize(result.size() + PAGE_SIZE);
299 ssize_t rc = TEMP_FAILURE_RETRY(read(fd.get(), &result[offset], read_length));
300 if (rc == -1) {
301 FAIL() << "read failed: " << strerror(errno);
302 } else if (rc == 0) {
303 result.resize(result.size() - PAGE_SIZE);
304 break;
305 }
306
307 result.resize(result.size() - PAGE_SIZE + rc);
308 }
309
310 *output = std::move(result);
311}
312
Mitch Phillips78f06702021-06-01 14:35:43 -0700313class LogcatCollector {
314 public:
315 LogcatCollector() { system("logcat -c"); }
316
317 void Collect(std::string* output) {
318 FILE* cmd_stdout = popen("logcat -d '*:S DEBUG'", "r");
319 ASSERT_NE(cmd_stdout, nullptr);
320 unique_fd tmp_fd(TEMP_FAILURE_RETRY(dup(fileno(cmd_stdout))));
321 ConsumeFd(std::move(tmp_fd), output);
322 pclose(cmd_stdout);
323 }
324};
325
Josh Gaocbe70cb2016-10-18 18:17:52 -0700326TEST_F(CrasherTest, smoke) {
327 int intercept_result;
328 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800329 StartProcess([]() {
330 *reinterpret_cast<volatile char*>(0xdead) = '1';
331 });
332
Josh Gaocbe70cb2016-10-18 18:17:52 -0700333 StartIntercept(&output_fd);
334 FinishCrasher();
335 AssertDeath(SIGSEGV);
336 FinishIntercept(&intercept_result);
337
338 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
339
340 std::string result;
341 ConsumeFd(std::move(output_fd), &result);
342 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\), code 1 \(SEGV_MAPERR\), fault addr 0xdead)");
Peter Collingbourne864f15d2020-09-14 20:27:36 -0700343
344 if (mte_supported()) {
345 // Test that the default TAGGED_ADDR_CTRL value is set.
Peter Collingbourne939d0742021-02-02 19:00:45 -0800346 ASSERT_MATCH(result, R"(tagged_addr_ctrl: 000000000007fff3)");
Peter Collingbourne864f15d2020-09-14 20:27:36 -0700347 }
Josh Gaocbe70cb2016-10-18 18:17:52 -0700348}
349
Peter Collingbournef03af882020-03-20 18:09:00 -0700350TEST_F(CrasherTest, tagged_fault_addr) {
351#if !defined(__aarch64__)
352 GTEST_SKIP() << "Requires aarch64";
353#endif
354 int intercept_result;
355 unique_fd output_fd;
356 StartProcess([]() {
357 *reinterpret_cast<volatile char*>(0x100000000000dead) = '1';
358 });
359
360 StartIntercept(&output_fd);
361 FinishCrasher();
362 AssertDeath(SIGSEGV);
363 FinishIntercept(&intercept_result);
364
365 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
366
367 std::string result;
368 ConsumeFd(std::move(output_fd), &result);
369
370 // The address can either be tagged (new kernels) or untagged (old kernels).
371 ASSERT_MATCH(
372 result,
373 R"(signal 11 \(SIGSEGV\), code 1 \(SEGV_MAPERR\), fault addr (0x100000000000dead|0xdead))");
374}
375
Peter Collingbourne10e428d2020-07-17 14:49:31 -0700376// Marked as weak to prevent the compiler from removing the malloc in the caller. In theory, the
377// compiler could still clobber the argument register before trapping, but that's unlikely.
378__attribute__((weak)) void CrasherTest::Trap(void* ptr ATTRIBUTE_UNUSED) {
379 __builtin_trap();
380}
381
382TEST_F(CrasherTest, heap_addr_in_register) {
383#if defined(__i386__)
384 GTEST_SKIP() << "architecture does not pass arguments in registers";
385#endif
386 int intercept_result;
387 unique_fd output_fd;
388 StartProcess([]() {
389 // Crash with a heap pointer in the first argument register.
390 Trap(malloc(1));
391 });
392
393 StartIntercept(&output_fd);
394 FinishCrasher();
395 int status;
396 ASSERT_EQ(crasher_pid, TIMEOUT(30, waitpid(crasher_pid, &status, 0)));
397 ASSERT_TRUE(WIFSIGNALED(status)) << "crasher didn't terminate via a signal";
398 // Don't test the signal number because different architectures use different signals for
399 // __builtin_trap().
400 FinishIntercept(&intercept_result);
401
402 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
403
404 std::string result;
405 ConsumeFd(std::move(output_fd), &result);
406
407#if defined(__aarch64__)
Peter Collingbourne0ea08c22021-02-05 14:59:08 -0800408 ASSERT_MATCH(result, "memory near x0 \\(\\[anon:");
Peter Collingbourne10e428d2020-07-17 14:49:31 -0700409#elif defined(__arm__)
Peter Collingbourne0ea08c22021-02-05 14:59:08 -0800410 ASSERT_MATCH(result, "memory near r0 \\(\\[anon:");
Peter Collingbourne10e428d2020-07-17 14:49:31 -0700411#elif defined(__x86_64__)
Peter Collingbourne0ea08c22021-02-05 14:59:08 -0800412 ASSERT_MATCH(result, "memory near rdi \\(\\[anon:");
Peter Collingbourne10e428d2020-07-17 14:49:31 -0700413#else
414 ASSERT_TRUE(false) << "unsupported architecture";
415#endif
416}
417
Peter Collingbournecd278072020-12-21 14:08:38 -0800418#if defined(__aarch64__)
Peter Collingbournef8622522020-04-07 14:07:32 -0700419static void SetTagCheckingLevelSync() {
Elliott Hughes03b283a2021-01-15 11:34:26 -0800420 if (mallopt(M_BIONIC_SET_HEAP_TAGGING_LEVEL, M_HEAP_TAGGING_LEVEL_SYNC) == 0) {
Peter Collingbournef8622522020-04-07 14:07:32 -0700421 abort();
422 }
423}
424#endif
425
Mitch Phillips7168a212021-03-09 16:53:23 -0800426// Number of iterations required to reliably guarantee a GWP-ASan crash.
427// GWP-ASan's sample rate is not truly nondeterministic, it initialises a
428// thread-local counter at 2*SampleRate, and decrements on each malloc(). Once
429// the counter reaches zero, we provide a sampled allocation. Then, double that
430// figure to allow for left/right allocation alignment, as this is done randomly
431// without bias.
432#define GWP_ASAN_ITERATIONS_TO_ENSURE_CRASH (0x20000)
433
434struct GwpAsanTestParameters {
435 size_t alloc_size;
436 bool free_before_access;
437 int access_offset;
438 std::string cause_needle; // Needle to be found in the "Cause: [GWP-ASan]" line.
439};
440
441struct GwpAsanCrasherTest : CrasherTest, testing::WithParamInterface<GwpAsanTestParameters> {};
442
443GwpAsanTestParameters gwp_asan_tests[] = {
444 {/* alloc_size */ 7, /* free_before_access */ true, /* access_offset */ 0, "Use After Free, 0 bytes into a 7-byte allocation"},
445 {/* alloc_size */ 7, /* free_before_access */ true, /* access_offset */ 1, "Use After Free, 1 byte into a 7-byte allocation"},
446 {/* alloc_size */ 7, /* free_before_access */ false, /* access_offset */ 16, "Buffer Overflow, 9 bytes right of a 7-byte allocation"},
447 {/* alloc_size */ 16, /* free_before_access */ false, /* access_offset */ -1, "Buffer Underflow, 1 byte left of a 16-byte allocation"},
448};
449
450INSTANTIATE_TEST_SUITE_P(GwpAsanTests, GwpAsanCrasherTest, testing::ValuesIn(gwp_asan_tests));
451
452TEST_P(GwpAsanCrasherTest, gwp_asan_uaf) {
453 if (mte_supported()) {
454 // Skip this test on MTE hardware, as MTE will reliably catch these errors
455 // instead of GWP-ASan.
456 GTEST_SKIP() << "Skipped on MTE.";
457 }
458
459 GwpAsanTestParameters params = GetParam();
Mitch Phillips78f06702021-06-01 14:35:43 -0700460 LogcatCollector logcat_collector;
Mitch Phillips7168a212021-03-09 16:53:23 -0800461
462 int intercept_result;
463 unique_fd output_fd;
464 StartProcess([&params]() {
465 for (unsigned i = 0; i < GWP_ASAN_ITERATIONS_TO_ENSURE_CRASH; ++i) {
466 volatile char* p = reinterpret_cast<volatile char*>(malloc(params.alloc_size));
467 if (params.free_before_access) free(static_cast<void*>(const_cast<char*>(p)));
468 p[params.access_offset] = 42;
469 if (!params.free_before_access) free(static_cast<void*>(const_cast<char*>(p)));
470 }
471 });
472
473 StartIntercept(&output_fd);
474 FinishCrasher();
475 AssertDeath(SIGSEGV);
476 FinishIntercept(&intercept_result);
477
478 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
479
Mitch Phillips78f06702021-06-01 14:35:43 -0700480 std::vector<std::string> log_sources(2);
481 ConsumeFd(std::move(output_fd), &log_sources[0]);
482 logcat_collector.Collect(&log_sources[1]);
Mitch Phillips7168a212021-03-09 16:53:23 -0800483
Mitch Phillips78f06702021-06-01 14:35:43 -0700484 for (const auto& result : log_sources) {
485 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\), code 2 \(SEGV_ACCERR\))");
486 ASSERT_MATCH(result, R"(Cause: \[GWP-ASan\]: )" + params.cause_needle);
487 if (params.free_before_access) {
488 ASSERT_MATCH(result, R"(deallocated by thread .*\n.*#00 pc)");
489 }
490 ASSERT_MATCH(result, R"((^|\s)allocated by thread .*\n.*#00 pc)");
Mitch Phillips7168a212021-03-09 16:53:23 -0800491 }
Mitch Phillips7168a212021-03-09 16:53:23 -0800492}
493
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800494struct SizeParamCrasherTest : CrasherTest, testing::WithParamInterface<size_t> {};
495
Peter Collingbourneaa544792021-05-13 13:53:37 -0700496INSTANTIATE_TEST_SUITE_P(Sizes, SizeParamCrasherTest, testing::Values(0, 16, 131072));
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800497
498TEST_P(SizeParamCrasherTest, mte_uaf) {
Peter Collingbournecd278072020-12-21 14:08:38 -0800499#if defined(__aarch64__)
Peter Collingbournef8622522020-04-07 14:07:32 -0700500 if (!mte_supported()) {
501 GTEST_SKIP() << "Requires MTE";
502 }
503
Peter Collingbourneaa544792021-05-13 13:53:37 -0700504 // Any UAF on a zero-sized allocation will be out-of-bounds so it won't be reported.
505 if (GetParam() == 0) {
506 return;
507 }
508
Mitch Phillips78f06702021-06-01 14:35:43 -0700509 LogcatCollector logcat_collector;
510
Peter Collingbournef8622522020-04-07 14:07:32 -0700511 int intercept_result;
512 unique_fd output_fd;
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800513 StartProcess([&]() {
Peter Collingbournef8622522020-04-07 14:07:32 -0700514 SetTagCheckingLevelSync();
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800515 volatile int* p = (volatile int*)malloc(GetParam());
Peter Collingbournef8622522020-04-07 14:07:32 -0700516 free((void *)p);
517 p[0] = 42;
518 });
519
520 StartIntercept(&output_fd);
521 FinishCrasher();
522 AssertDeath(SIGSEGV);
523 FinishIntercept(&intercept_result);
524
525 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
526
Mitch Phillips78f06702021-06-01 14:35:43 -0700527 std::vector<std::string> log_sources(2);
528 ConsumeFd(std::move(output_fd), &log_sources[0]);
529 logcat_collector.Collect(&log_sources[1]);
Mitch Phillips5ddcea22021-04-19 09:59:17 -0700530 // Tag dump only available in the tombstone, not logcat.
531 ASSERT_MATCH(log_sources[0], "Memory tags around the fault address");
Peter Collingbournef8622522020-04-07 14:07:32 -0700532
Mitch Phillips78f06702021-06-01 14:35:43 -0700533 for (const auto& result : log_sources) {
534 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\))");
535 ASSERT_MATCH(result, R"(Cause: \[MTE\]: Use After Free, 0 bytes into a )" +
536 std::to_string(GetParam()) + R"(-byte allocation)");
537 ASSERT_MATCH(result, R"(deallocated by thread .*?\n.*#00 pc)");
538 ASSERT_MATCH(result, R"((^|\s)allocated by thread .*?\n.*#00 pc)");
539 }
Peter Collingbournef8622522020-04-07 14:07:32 -0700540#else
Peter Collingbournecd278072020-12-21 14:08:38 -0800541 GTEST_SKIP() << "Requires aarch64";
Peter Collingbournef8622522020-04-07 14:07:32 -0700542#endif
543}
544
Peter Collingbournedc476342021-05-12 15:56:43 -0700545TEST_P(SizeParamCrasherTest, mte_oob_uaf) {
546#if defined(__aarch64__)
547 if (!mte_supported()) {
548 GTEST_SKIP() << "Requires MTE";
549 }
550
551 int intercept_result;
552 unique_fd output_fd;
553 StartProcess([&]() {
554 SetTagCheckingLevelSync();
555 volatile int* p = (volatile int*)malloc(GetParam());
556 free((void *)p);
557 p[-1] = 42;
558 });
559
560 StartIntercept(&output_fd);
561 FinishCrasher();
562 AssertDeath(SIGSEGV);
563 FinishIntercept(&intercept_result);
564
565 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
566
567 std::string result;
568 ConsumeFd(std::move(output_fd), &result);
569
570 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\))");
571 ASSERT_NOT_MATCH(result, R"(Cause: \[MTE\]: Use After Free, 4 bytes left)");
572#else
573 GTEST_SKIP() << "Requires aarch64";
574#endif
575}
576
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800577TEST_P(SizeParamCrasherTest, mte_overflow) {
Peter Collingbournecd278072020-12-21 14:08:38 -0800578#if defined(__aarch64__)
Peter Collingbournef8622522020-04-07 14:07:32 -0700579 if (!mte_supported()) {
580 GTEST_SKIP() << "Requires MTE";
581 }
582
Mitch Phillips78f06702021-06-01 14:35:43 -0700583 LogcatCollector logcat_collector;
Peter Collingbournef8622522020-04-07 14:07:32 -0700584 int intercept_result;
585 unique_fd output_fd;
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800586 StartProcess([&]() {
Peter Collingbournef8622522020-04-07 14:07:32 -0700587 SetTagCheckingLevelSync();
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800588 volatile char* p = (volatile char*)malloc(GetParam());
589 p[GetParam()] = 42;
Peter Collingbournef8622522020-04-07 14:07:32 -0700590 });
591
592 StartIntercept(&output_fd);
593 FinishCrasher();
594 AssertDeath(SIGSEGV);
595 FinishIntercept(&intercept_result);
596
597 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
598
Mitch Phillips78f06702021-06-01 14:35:43 -0700599 std::vector<std::string> log_sources(2);
600 ConsumeFd(std::move(output_fd), &log_sources[0]);
601 logcat_collector.Collect(&log_sources[1]);
Peter Collingbournef8622522020-04-07 14:07:32 -0700602
Mitch Phillips5ddcea22021-04-19 09:59:17 -0700603 // Tag dump only in tombstone, not logcat, and tagging is not used for
604 // overflow protection in the scudo secondary (guard pages are used instead).
605 if (GetParam() < 0x10000) {
606 ASSERT_MATCH(log_sources[0], "Memory tags around the fault address");
607 }
608
Mitch Phillips78f06702021-06-01 14:35:43 -0700609 for (const auto& result : log_sources) {
610 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\))");
611 ASSERT_MATCH(result, R"(Cause: \[MTE\]: Buffer Overflow, 0 bytes right of a )" +
612 std::to_string(GetParam()) + R"(-byte allocation)");
613 ASSERT_MATCH(result, R"((^|\s)allocated by thread .*?\n.*#00 pc)");
614 }
Peter Collingbournef8622522020-04-07 14:07:32 -0700615#else
Peter Collingbournecd278072020-12-21 14:08:38 -0800616 GTEST_SKIP() << "Requires aarch64";
Peter Collingbournef8622522020-04-07 14:07:32 -0700617#endif
618}
619
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800620TEST_P(SizeParamCrasherTest, mte_underflow) {
Peter Collingbournecd278072020-12-21 14:08:38 -0800621#if defined(__aarch64__)
Peter Collingbournef8622522020-04-07 14:07:32 -0700622 if (!mte_supported()) {
623 GTEST_SKIP() << "Requires MTE";
624 }
625
626 int intercept_result;
627 unique_fd output_fd;
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800628 StartProcess([&]() {
Peter Collingbournef8622522020-04-07 14:07:32 -0700629 SetTagCheckingLevelSync();
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800630 volatile int* p = (volatile int*)malloc(GetParam());
Peter Collingbournef8622522020-04-07 14:07:32 -0700631 p[-1] = 42;
632 });
633
634 StartIntercept(&output_fd);
635 FinishCrasher();
636 AssertDeath(SIGSEGV);
637 FinishIntercept(&intercept_result);
638
639 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
640
641 std::string result;
642 ConsumeFd(std::move(output_fd), &result);
643
644 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\), code 9 \(SEGV_MTESERR\))");
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800645 ASSERT_MATCH(result, R"(Cause: \[MTE\]: Buffer Underflow, 4 bytes left of a )" +
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800646 std::to_string(GetParam()) + R"(-byte allocation)");
Mitch Phillips78f06702021-06-01 14:35:43 -0700647 ASSERT_MATCH(result, R"((^|\s)allocated by thread .*
Peter Collingbournebbe69052020-05-08 10:11:19 -0700648 #00 pc)");
Mitch Phillips5ddcea22021-04-19 09:59:17 -0700649 ASSERT_MATCH(result, "Memory tags around the fault address");
Peter Collingbournef8622522020-04-07 14:07:32 -0700650#else
Peter Collingbournecd278072020-12-21 14:08:38 -0800651 GTEST_SKIP() << "Requires aarch64";
Peter Collingbournef8622522020-04-07 14:07:32 -0700652#endif
653}
654
655TEST_F(CrasherTest, mte_multiple_causes) {
Peter Collingbournecd278072020-12-21 14:08:38 -0800656#if defined(__aarch64__)
Peter Collingbournef8622522020-04-07 14:07:32 -0700657 if (!mte_supported()) {
658 GTEST_SKIP() << "Requires MTE";
659 }
660
Mitch Phillips78f06702021-06-01 14:35:43 -0700661 LogcatCollector logcat_collector;
662
Peter Collingbournef8622522020-04-07 14:07:32 -0700663 int intercept_result;
664 unique_fd output_fd;
665 StartProcess([]() {
666 SetTagCheckingLevelSync();
667
668 // Make two allocations with the same tag and close to one another. Check for both properties
669 // with a bounds check -- this relies on the fact that only if the allocations have the same tag
670 // would they be measured as closer than 128 bytes to each other. Otherwise they would be about
671 // (some non-zero value << 56) apart.
672 //
673 // The out-of-bounds access will be considered either an overflow of one or an underflow of the
674 // other.
675 std::set<uintptr_t> allocs;
676 for (int i = 0; i != 4096; ++i) {
677 uintptr_t alloc = reinterpret_cast<uintptr_t>(malloc(16));
678 auto it = allocs.insert(alloc).first;
679 if (it != allocs.begin() && *std::prev(it) + 128 > alloc) {
680 *reinterpret_cast<int*>(*std::prev(it) + 16) = 42;
681 }
682 if (std::next(it) != allocs.end() && alloc + 128 > *std::next(it)) {
683 *reinterpret_cast<int*>(alloc + 16) = 42;
684 }
685 }
686 });
687
688 StartIntercept(&output_fd);
689 FinishCrasher();
690 AssertDeath(SIGSEGV);
691 FinishIntercept(&intercept_result);
692
693 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
694
Mitch Phillips78f06702021-06-01 14:35:43 -0700695 std::vector<std::string> log_sources(2);
696 ConsumeFd(std::move(output_fd), &log_sources[0]);
697 logcat_collector.Collect(&log_sources[1]);
Peter Collingbournef8622522020-04-07 14:07:32 -0700698
Mitch Phillips5ddcea22021-04-19 09:59:17 -0700699 // Tag dump only in the tombstone, not logcat.
700 ASSERT_MATCH(log_sources[0], "Memory tags around the fault address");
701
Mitch Phillips78f06702021-06-01 14:35:43 -0700702 for (const auto& result : log_sources) {
703 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\))");
704 ASSERT_THAT(result, HasSubstr("Note: multiple potential causes for this crash were detected, "
705 "listing them in decreasing order of probability."));
706 // Adjacent untracked allocations may cause us to see the wrong underflow here (or only
707 // overflows), so we can't match explicitly for an underflow message.
708 ASSERT_MATCH(result,
709 R"(Cause: \[MTE\]: Buffer Overflow, 0 bytes right of a 16-byte allocation)");
710 // Ensure there's at least two allocation traces (one for each cause).
711 ASSERT_MATCH(
712 result,
713 R"((^|\s)allocated by thread .*?\n.*#00 pc(.|\n)*?(^|\s)allocated by thread .*?\n.*#00 pc)");
714 }
Peter Collingbournef8622522020-04-07 14:07:32 -0700715#else
Peter Collingbournecd278072020-12-21 14:08:38 -0800716 GTEST_SKIP() << "Requires aarch64";
Peter Collingbournef8622522020-04-07 14:07:32 -0700717#endif
718}
719
Peter Collingbournecd278072020-12-21 14:08:38 -0800720#if defined(__aarch64__)
Peter Collingbournefe8997a2020-07-20 15:08:52 -0700721static uintptr_t CreateTagMapping() {
Mitch Phillips5ddcea22021-04-19 09:59:17 -0700722 // Some of the MTE tag dump tests assert that there is an inaccessible page to the left and right
723 // of the PROT_MTE page, so map three pages and set the two guard pages to PROT_NONE.
724 size_t page_size = getpagesize();
725 void* mapping = mmap(nullptr, page_size * 3, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
726 uintptr_t mapping_uptr = reinterpret_cast<uintptr_t>(mapping);
727 if (mapping == MAP_FAILED) {
Peter Collingbournefe8997a2020-07-20 15:08:52 -0700728 return 0;
729 }
Mitch Phillips5ddcea22021-04-19 09:59:17 -0700730 mprotect(reinterpret_cast<void*>(mapping_uptr + page_size), page_size,
731 PROT_READ | PROT_WRITE | PROT_MTE);
732 // Stripe the mapping, where even granules get tag '1', and odd granules get tag '0'.
733 for (uintptr_t offset = 0; offset < page_size; offset += 2 * kTagGranuleSize) {
734 uintptr_t tagged_addr = mapping_uptr + page_size + offset + (1ULL << 56);
735 __asm__ __volatile__(".arch_extension mte; stg %0, [%0]" : : "r"(tagged_addr) : "memory");
736 }
737 return mapping_uptr + page_size;
Peter Collingbournefe8997a2020-07-20 15:08:52 -0700738}
739#endif
740
Mitch Phillips5ddcea22021-04-19 09:59:17 -0700741TEST_F(CrasherTest, mte_register_tag_dump) {
Peter Collingbournecd278072020-12-21 14:08:38 -0800742#if defined(__aarch64__)
Peter Collingbournefe8997a2020-07-20 15:08:52 -0700743 if (!mte_supported()) {
744 GTEST_SKIP() << "Requires MTE";
745 }
746
747 int intercept_result;
748 unique_fd output_fd;
749 StartProcess([&]() {
750 SetTagCheckingLevelSync();
751 Trap(reinterpret_cast<void *>(CreateTagMapping()));
752 });
753
754 StartIntercept(&output_fd);
755 FinishCrasher();
756 AssertDeath(SIGTRAP);
757 FinishIntercept(&intercept_result);
758
759 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
760
761 std::string result;
762 ConsumeFd(std::move(output_fd), &result);
763
764 ASSERT_MATCH(result, R"(memory near x0:
765.*
766.*
767 01.............0 0000000000000000 0000000000000000 ................
768 00.............0)");
769#else
Peter Collingbournecd278072020-12-21 14:08:38 -0800770 GTEST_SKIP() << "Requires aarch64";
Peter Collingbournefe8997a2020-07-20 15:08:52 -0700771#endif
772}
773
Mitch Phillips5ddcea22021-04-19 09:59:17 -0700774TEST_F(CrasherTest, mte_fault_tag_dump_front_truncated) {
775#if defined(__aarch64__)
776 if (!mte_supported()) {
777 GTEST_SKIP() << "Requires MTE";
778 }
779
780 int intercept_result;
781 unique_fd output_fd;
782 StartProcess([&]() {
783 SetTagCheckingLevelSync();
784 volatile char* p = reinterpret_cast<char*>(CreateTagMapping());
785 p[0] = 0; // Untagged pointer, tagged memory.
786 });
787
788 StartIntercept(&output_fd);
789 FinishCrasher();
790 AssertDeath(SIGSEGV);
791 FinishIntercept(&intercept_result);
792
793 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
794
795 std::string result;
796 ConsumeFd(std::move(output_fd), &result);
797
798 ASSERT_MATCH(result, R"(Memory tags around the fault address.*
799\s*=>0x[0-9a-f]+000:\[1\] 0 1 0)");
800#else
801 GTEST_SKIP() << "Requires aarch64";
802#endif
803}
804
805TEST_F(CrasherTest, mte_fault_tag_dump) {
806#if defined(__aarch64__)
807 if (!mte_supported()) {
808 GTEST_SKIP() << "Requires MTE";
809 }
810
811 int intercept_result;
812 unique_fd output_fd;
813 StartProcess([&]() {
814 SetTagCheckingLevelSync();
815 volatile char* p = reinterpret_cast<char*>(CreateTagMapping());
816 p[320] = 0; // Untagged pointer, tagged memory.
817 });
818
819 StartIntercept(&output_fd);
820 FinishCrasher();
821 AssertDeath(SIGSEGV);
822 FinishIntercept(&intercept_result);
823
824 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
825
826 std::string result;
827 ConsumeFd(std::move(output_fd), &result);
828
829 ASSERT_MATCH(result, R"(Memory tags around the fault address.*
830\s*0x[0-9a-f]+: 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0
831\s*=>0x[0-9a-f]+: 1 0 1 0 \[1\] 0 1 0 1 0 1 0 1 0 1 0
832\s*0x[0-9a-f]+: 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0
833)");
834#else
835 GTEST_SKIP() << "Requires aarch64";
836#endif
837}
838
839TEST_F(CrasherTest, mte_fault_tag_dump_rear_truncated) {
840#if defined(__aarch64__)
841 if (!mte_supported()) {
842 GTEST_SKIP() << "Requires MTE";
843 }
844
845 int intercept_result;
846 unique_fd output_fd;
847 StartProcess([&]() {
848 SetTagCheckingLevelSync();
849 size_t page_size = getpagesize();
850 volatile char* p = reinterpret_cast<char*>(CreateTagMapping());
851 p[page_size - kTagGranuleSize * 2] = 0; // Untagged pointer, tagged memory.
852 });
853
854 StartIntercept(&output_fd);
855 FinishCrasher();
856 AssertDeath(SIGSEGV);
857 FinishIntercept(&intercept_result);
858
859 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
860
861 std::string result;
862 ConsumeFd(std::move(output_fd), &result);
863
864 ASSERT_MATCH(result, R"(Memory tags around the fault address)");
865 ASSERT_MATCH(result,
866 R"(\s*0x[0-9a-f]+: 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0
867\s*=>0x[0-9a-f]+: 1 0 1 0 1 0 1 0 1 0 1 0 1 0 \[1\] 0
868
869)"); // Ensure truncation happened and there's a newline after the tag fault.
870#else
871 GTEST_SKIP() << "Requires aarch64";
872#endif
873}
874
Josh Gaocdea7502017-11-01 15:00:40 -0700875TEST_F(CrasherTest, LD_PRELOAD) {
876 int intercept_result;
877 unique_fd output_fd;
878 StartProcess([]() {
879 setenv("LD_PRELOAD", "nonexistent.so", 1);
880 *reinterpret_cast<volatile char*>(0xdead) = '1';
881 });
882
883 StartIntercept(&output_fd);
884 FinishCrasher();
885 AssertDeath(SIGSEGV);
886 FinishIntercept(&intercept_result);
887
888 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
889
890 std::string result;
891 ConsumeFd(std::move(output_fd), &result);
892 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\), code 1 \(SEGV_MAPERR\), fault addr 0xdead)");
893}
894
Josh Gaocbe70cb2016-10-18 18:17:52 -0700895TEST_F(CrasherTest, abort) {
896 int intercept_result;
897 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800898 StartProcess([]() {
899 abort();
900 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700901 StartIntercept(&output_fd);
902 FinishCrasher();
903 AssertDeath(SIGABRT);
904 FinishIntercept(&intercept_result);
905
906 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
907
908 std::string result;
909 ConsumeFd(std::move(output_fd), &result);
Andreas Gampe26cbafb2017-06-22 20:14:43 -0700910 ASSERT_BACKTRACE_FRAME(result, "abort");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700911}
912
913TEST_F(CrasherTest, signal) {
914 int intercept_result;
915 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800916 StartProcess([]() {
Josh Gao2b2ae0c2017-08-21 14:31:17 -0700917 while (true) {
918 sleep(1);
919 }
Josh Gao502cfd22017-02-17 01:39:15 -0800920 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700921 StartIntercept(&output_fd);
Josh Gao2b2ae0c2017-08-21 14:31:17 -0700922 FinishCrasher();
Josh Gaocbe70cb2016-10-18 18:17:52 -0700923 ASSERT_EQ(0, kill(crasher_pid, SIGSEGV));
924
925 AssertDeath(SIGSEGV);
926 FinishIntercept(&intercept_result);
927
928 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
929
930 std::string result;
931 ConsumeFd(std::move(output_fd), &result);
Elliott Hughes89722702018-05-02 10:47:00 -0700932 ASSERT_MATCH(
933 result,
934 R"(signal 11 \(SIGSEGV\), code 0 \(SI_USER from pid \d+, uid \d+\), fault addr --------)");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700935 ASSERT_MATCH(result, R"(backtrace:)");
936}
937
938TEST_F(CrasherTest, abort_message) {
939 int intercept_result;
940 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800941 StartProcess([]() {
Josh Gao1cc7bd82018-02-13 13:16:17 -0800942 // Arrived at experimentally;
943 // logd truncates at 4062.
944 // strlen("Abort message: ''") is 17.
945 // That's 4045, but we also want a NUL.
946 char buf[4045 + 1];
947 memset(buf, 'x', sizeof(buf));
948 buf[sizeof(buf) - 1] = '\0';
949 android_set_abort_message(buf);
Josh Gao502cfd22017-02-17 01:39:15 -0800950 abort();
951 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700952 StartIntercept(&output_fd);
953 FinishCrasher();
954 AssertDeath(SIGABRT);
955 FinishIntercept(&intercept_result);
956
957 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
958
959 std::string result;
960 ConsumeFd(std::move(output_fd), &result);
Josh Gao1cc7bd82018-02-13 13:16:17 -0800961 ASSERT_MATCH(result, R"(Abort message: 'x{4045}')");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700962}
963
Josh Gaoe06f2a42017-04-27 16:50:38 -0700964TEST_F(CrasherTest, abort_message_backtrace) {
965 int intercept_result;
966 unique_fd output_fd;
967 StartProcess([]() {
968 android_set_abort_message("not actually aborting");
Josh Gaoa48b41b2019-12-13 14:11:04 -0800969 raise(BIONIC_SIGNAL_DEBUGGER);
Josh Gaoe06f2a42017-04-27 16:50:38 -0700970 exit(0);
971 });
972 StartIntercept(&output_fd);
973 FinishCrasher();
974 AssertDeath(0);
975 FinishIntercept(&intercept_result);
976
977 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
978
979 std::string result;
980 ConsumeFd(std::move(output_fd), &result);
981 ASSERT_NOT_MATCH(result, R"(Abort message:)");
982}
983
Josh Gaocbe70cb2016-10-18 18:17:52 -0700984TEST_F(CrasherTest, intercept_timeout) {
985 int intercept_result;
986 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800987 StartProcess([]() {
988 abort();
989 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700990 StartIntercept(&output_fd);
991
992 // Don't let crasher finish until we timeout.
993 FinishIntercept(&intercept_result);
994
995 ASSERT_NE(1, intercept_result) << "tombstoned reported success? (intercept_result = "
996 << intercept_result << ")";
997
998 FinishCrasher();
999 AssertDeath(SIGABRT);
1000}
1001
Elliott Hughese4781d52021-03-17 09:15:15 -07001002TEST_F(CrasherTest, wait_for_debugger) {
1003 if (!android::base::SetProperty(kWaitForDebuggerKey, "1")) {
1004 FAIL() << "failed to enable wait_for_debugger";
Josh Gaocbe70cb2016-10-18 18:17:52 -07001005 }
1006 sleep(1);
1007
Josh Gao502cfd22017-02-17 01:39:15 -08001008 StartProcess([]() {
1009 abort();
1010 });
Josh Gaocbe70cb2016-10-18 18:17:52 -07001011 FinishCrasher();
1012
1013 int status;
Christopher Ferris172b0a02019-09-18 17:48:30 -07001014 ASSERT_EQ(crasher_pid, TEMP_FAILURE_RETRY(waitpid(crasher_pid, &status, WUNTRACED)));
Josh Gaocbe70cb2016-10-18 18:17:52 -07001015 ASSERT_TRUE(WIFSTOPPED(status));
1016 ASSERT_EQ(SIGSTOP, WSTOPSIG(status));
1017
1018 ASSERT_EQ(0, kill(crasher_pid, SIGCONT));
1019
1020 AssertDeath(SIGABRT);
1021}
1022
Josh Gaocbe70cb2016-10-18 18:17:52 -07001023TEST_F(CrasherTest, backtrace) {
1024 std::string result;
1025 int intercept_result;
1026 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -08001027
1028 StartProcess([]() {
1029 abort();
1030 });
Narayan Kamatha73df602017-05-24 15:07:25 +01001031 StartIntercept(&output_fd, kDebuggerdNativeBacktrace);
Josh Gaocbe70cb2016-10-18 18:17:52 -07001032
1033 std::this_thread::sleep_for(500ms);
1034
1035 sigval val;
1036 val.sival_int = 1;
Josh Gaoa48b41b2019-12-13 14:11:04 -08001037 ASSERT_EQ(0, sigqueue(crasher_pid, BIONIC_SIGNAL_DEBUGGER, val)) << strerror(errno);
Josh Gaocbe70cb2016-10-18 18:17:52 -07001038 FinishIntercept(&intercept_result);
1039 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1040 ConsumeFd(std::move(output_fd), &result);
Jaesung Chung58778e12017-06-15 18:20:34 +09001041 ASSERT_BACKTRACE_FRAME(result, "read");
Josh Gaocbe70cb2016-10-18 18:17:52 -07001042
1043 int status;
1044 ASSERT_EQ(0, waitpid(crasher_pid, &status, WNOHANG | WUNTRACED));
1045
1046 StartIntercept(&output_fd);
1047 FinishCrasher();
1048 AssertDeath(SIGABRT);
1049 FinishIntercept(&intercept_result);
1050 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1051 ConsumeFd(std::move(output_fd), &result);
Andreas Gampe26cbafb2017-06-22 20:14:43 -07001052 ASSERT_BACKTRACE_FRAME(result, "abort");
Josh Gaocbe70cb2016-10-18 18:17:52 -07001053}
Josh Gaofca7ca32017-01-23 12:05:35 -08001054
1055TEST_F(CrasherTest, PR_SET_DUMPABLE_0_crash) {
Josh Gao502cfd22017-02-17 01:39:15 -08001056 int intercept_result;
1057 unique_fd output_fd;
Josh Gaofca7ca32017-01-23 12:05:35 -08001058 StartProcess([]() {
1059 prctl(PR_SET_DUMPABLE, 0);
Josh Gao502cfd22017-02-17 01:39:15 -08001060 abort();
Josh Gaofca7ca32017-01-23 12:05:35 -08001061 });
Josh Gao502cfd22017-02-17 01:39:15 -08001062
1063 StartIntercept(&output_fd);
1064 FinishCrasher();
1065 AssertDeath(SIGABRT);
1066 FinishIntercept(&intercept_result);
1067
1068 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1069
1070 std::string result;
1071 ConsumeFd(std::move(output_fd), &result);
Andreas Gampe26cbafb2017-06-22 20:14:43 -07001072 ASSERT_BACKTRACE_FRAME(result, "abort");
Josh Gaofca7ca32017-01-23 12:05:35 -08001073}
1074
Josh Gao502cfd22017-02-17 01:39:15 -08001075TEST_F(CrasherTest, capabilities) {
1076 ASSERT_EQ(0U, getuid()) << "capability test requires root";
1077
Josh Gaofca7ca32017-01-23 12:05:35 -08001078 StartProcess([]() {
Josh Gao502cfd22017-02-17 01:39:15 -08001079 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) != 0) {
1080 err(1, "failed to set PR_SET_KEEPCAPS");
1081 }
1082
1083 if (setresuid(1, 1, 1) != 0) {
1084 err(1, "setresuid failed");
1085 }
1086
1087 __user_cap_header_struct capheader;
1088 __user_cap_data_struct capdata[2];
1089 memset(&capheader, 0, sizeof(capheader));
1090 memset(&capdata, 0, sizeof(capdata));
1091
1092 capheader.version = _LINUX_CAPABILITY_VERSION_3;
1093 capheader.pid = 0;
1094
1095 // Turn on every third capability.
1096 static_assert(CAP_LAST_CAP > 33, "CAP_LAST_CAP <= 32");
1097 for (int i = 0; i < CAP_LAST_CAP; i += 3) {
1098 capdata[CAP_TO_INDEX(i)].permitted |= CAP_TO_MASK(i);
1099 capdata[CAP_TO_INDEX(i)].effective |= CAP_TO_MASK(i);
1100 }
1101
1102 // Make sure CAP_SYS_PTRACE is off.
1103 capdata[CAP_TO_INDEX(CAP_SYS_PTRACE)].permitted &= ~(CAP_TO_MASK(CAP_SYS_PTRACE));
1104 capdata[CAP_TO_INDEX(CAP_SYS_PTRACE)].effective &= ~(CAP_TO_MASK(CAP_SYS_PTRACE));
1105
1106 if (capset(&capheader, &capdata[0]) != 0) {
1107 err(1, "capset failed");
1108 }
1109
1110 if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_CLEAR_ALL, 0, 0, 0) != 0) {
1111 err(1, "failed to drop ambient capabilities");
1112 }
1113
Josh Gaoa5199a92017-04-03 13:18:34 -07001114 pthread_setname_np(pthread_self(), "thread_name");
Josh Gao502cfd22017-02-17 01:39:15 -08001115 raise(SIGSYS);
Josh Gaofca7ca32017-01-23 12:05:35 -08001116 });
Josh Gao502cfd22017-02-17 01:39:15 -08001117
1118 unique_fd output_fd;
1119 StartIntercept(&output_fd);
1120 FinishCrasher();
1121 AssertDeath(SIGSYS);
1122
1123 std::string result;
1124 int intercept_result;
1125 FinishIntercept(&intercept_result);
1126 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1127 ConsumeFd(std::move(output_fd), &result);
Josh Gaoa5199a92017-04-03 13:18:34 -07001128 ASSERT_MATCH(result, R"(name: thread_name\s+>>> .+debuggerd_test(32|64) <<<)");
Jaesung Chung58778e12017-06-15 18:20:34 +09001129 ASSERT_BACKTRACE_FRAME(result, "tgkill");
Josh Gaofca7ca32017-01-23 12:05:35 -08001130}
Josh Gaoc3c8c022017-02-13 16:36:18 -08001131
Josh Gao2e7b8e22017-05-04 17:12:57 -07001132TEST_F(CrasherTest, fake_pid) {
1133 int intercept_result;
1134 unique_fd output_fd;
1135
1136 // Prime the getpid/gettid caches.
1137 UNUSED(getpid());
1138 UNUSED(gettid());
1139
1140 std::function<pid_t()> clone_fn = []() {
1141 return syscall(__NR_clone, SIGCHLD, nullptr, nullptr, nullptr, nullptr);
1142 };
1143 StartProcess(
1144 []() {
1145 ASSERT_NE(getpid(), syscall(__NR_getpid));
1146 ASSERT_NE(gettid(), syscall(__NR_gettid));
1147 raise(SIGSEGV);
1148 },
1149 clone_fn);
1150
1151 StartIntercept(&output_fd);
1152 FinishCrasher();
1153 AssertDeath(SIGSEGV);
1154 FinishIntercept(&intercept_result);
1155
1156 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1157
1158 std::string result;
1159 ConsumeFd(std::move(output_fd), &result);
Jaesung Chung58778e12017-06-15 18:20:34 +09001160 ASSERT_BACKTRACE_FRAME(result, "tgkill");
Josh Gao2e7b8e22017-05-04 17:12:57 -07001161}
1162
Josh Gaoe04ca272018-01-16 15:38:17 -08001163static const char* const kDebuggerdSeccompPolicy =
1164 "/system/etc/seccomp_policy/crash_dump." ABI_STRING ".policy";
1165
Josh Gao70adac62018-02-22 11:38:33 -08001166static pid_t seccomp_fork_impl(void (*prejail)()) {
Josh Gao6f9eeec2018-09-12 13:55:47 -07001167 std::string policy;
1168 if (!android::base::ReadFileToString(kDebuggerdSeccompPolicy, &policy)) {
1169 PLOG(FATAL) << "failed to read policy file";
1170 }
1171
1172 // Allow a bunch of syscalls used by the tests.
1173 policy += "\nclone: 1";
1174 policy += "\nsigaltstack: 1";
1175 policy += "\nnanosleep: 1";
Christopher Ferrisab606682019-09-17 15:31:47 -07001176 policy += "\ngetrlimit: 1";
1177 policy += "\nugetrlimit: 1";
Josh Gao6f9eeec2018-09-12 13:55:47 -07001178
1179 FILE* tmp_file = tmpfile();
1180 if (!tmp_file) {
1181 PLOG(FATAL) << "tmpfile failed";
1182 }
1183
Christopher Ferris172b0a02019-09-18 17:48:30 -07001184 unique_fd tmp_fd(TEMP_FAILURE_RETRY(dup(fileno(tmp_file))));
Josh Gao6f9eeec2018-09-12 13:55:47 -07001185 if (!android::base::WriteStringToFd(policy, tmp_fd.get())) {
1186 PLOG(FATAL) << "failed to write policy to tmpfile";
1187 }
1188
1189 if (lseek(tmp_fd.get(), 0, SEEK_SET) != 0) {
1190 PLOG(FATAL) << "failed to seek tmp_fd";
Josh Gaoe04ca272018-01-16 15:38:17 -08001191 }
1192
1193 ScopedMinijail jail{minijail_new()};
1194 if (!jail) {
1195 LOG(FATAL) << "failed to create minijail";
1196 }
1197
1198 minijail_no_new_privs(jail.get());
1199 minijail_log_seccomp_filter_failures(jail.get());
1200 minijail_use_seccomp_filter(jail.get());
Josh Gao6f9eeec2018-09-12 13:55:47 -07001201 minijail_parse_seccomp_filters_from_fd(jail.get(), tmp_fd.release());
Josh Gaoe04ca272018-01-16 15:38:17 -08001202
1203 pid_t result = fork();
1204 if (result == -1) {
1205 return result;
1206 } else if (result != 0) {
1207 return result;
1208 }
1209
1210 // Spawn and detach a thread that spins forever.
1211 std::atomic<bool> thread_ready(false);
1212 std::thread thread([&jail, &thread_ready]() {
1213 minijail_enter(jail.get());
1214 thread_ready = true;
1215 for (;;)
1216 ;
1217 });
1218 thread.detach();
1219
1220 while (!thread_ready) {
1221 continue;
1222 }
1223
Josh Gao70adac62018-02-22 11:38:33 -08001224 if (prejail) {
1225 prejail();
1226 }
1227
Josh Gaoe04ca272018-01-16 15:38:17 -08001228 minijail_enter(jail.get());
1229 return result;
1230}
1231
Josh Gao70adac62018-02-22 11:38:33 -08001232static pid_t seccomp_fork() {
1233 return seccomp_fork_impl(nullptr);
1234}
1235
Josh Gaoe04ca272018-01-16 15:38:17 -08001236TEST_F(CrasherTest, seccomp_crash) {
1237 int intercept_result;
1238 unique_fd output_fd;
1239
1240 StartProcess([]() { abort(); }, &seccomp_fork);
1241
1242 StartIntercept(&output_fd);
1243 FinishCrasher();
1244 AssertDeath(SIGABRT);
1245 FinishIntercept(&intercept_result);
1246 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1247
1248 std::string result;
1249 ConsumeFd(std::move(output_fd), &result);
1250 ASSERT_BACKTRACE_FRAME(result, "abort");
1251}
1252
Josh Gao70adac62018-02-22 11:38:33 -08001253static pid_t seccomp_fork_rlimit() {
1254 return seccomp_fork_impl([]() {
1255 struct rlimit rlim = {
1256 .rlim_cur = 512 * 1024 * 1024,
1257 .rlim_max = 512 * 1024 * 1024,
1258 };
1259
1260 if (setrlimit(RLIMIT_AS, &rlim) != 0) {
1261 raise(SIGINT);
1262 }
1263 });
1264}
1265
1266TEST_F(CrasherTest, seccomp_crash_oom) {
1267 int intercept_result;
1268 unique_fd output_fd;
1269
1270 StartProcess(
1271 []() {
1272 std::vector<void*> vec;
1273 for (int i = 0; i < 512; ++i) {
1274 char* buf = static_cast<char*>(malloc(1024 * 1024));
1275 if (!buf) {
1276 abort();
1277 }
1278 memset(buf, 0xff, 1024 * 1024);
1279 vec.push_back(buf);
1280 }
1281 },
1282 &seccomp_fork_rlimit);
1283
1284 StartIntercept(&output_fd);
1285 FinishCrasher();
1286 AssertDeath(SIGABRT);
1287 FinishIntercept(&intercept_result);
1288 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1289
1290 // We can't actually generate a backtrace, just make sure that the process terminates.
1291}
1292
Josh Gaoe04ca272018-01-16 15:38:17 -08001293__attribute__((noinline)) extern "C" bool raise_debugger_signal(DebuggerdDumpType dump_type) {
1294 siginfo_t siginfo;
1295 siginfo.si_code = SI_QUEUE;
1296 siginfo.si_pid = getpid();
1297 siginfo.si_uid = getuid();
1298
1299 if (dump_type != kDebuggerdNativeBacktrace && dump_type != kDebuggerdTombstone) {
1300 PLOG(FATAL) << "invalid dump type";
1301 }
1302
1303 siginfo.si_value.sival_int = dump_type == kDebuggerdNativeBacktrace;
1304
Josh Gaoa48b41b2019-12-13 14:11:04 -08001305 if (syscall(__NR_rt_tgsigqueueinfo, getpid(), gettid(), BIONIC_SIGNAL_DEBUGGER, &siginfo) != 0) {
Josh Gaoe04ca272018-01-16 15:38:17 -08001306 PLOG(ERROR) << "libdebuggerd_client: failed to send signal to self";
1307 return false;
1308 }
1309
1310 return true;
1311}
1312
1313TEST_F(CrasherTest, seccomp_tombstone) {
1314 int intercept_result;
1315 unique_fd output_fd;
1316
1317 static const auto dump_type = kDebuggerdTombstone;
1318 StartProcess(
1319 []() {
1320 raise_debugger_signal(dump_type);
1321 _exit(0);
1322 },
1323 &seccomp_fork);
1324
1325 StartIntercept(&output_fd, dump_type);
1326 FinishCrasher();
1327 AssertDeath(0);
1328 FinishIntercept(&intercept_result);
1329 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1330
1331 std::string result;
1332 ConsumeFd(std::move(output_fd), &result);
1333 ASSERT_BACKTRACE_FRAME(result, "raise_debugger_signal");
1334}
1335
Josh Gao6f9eeec2018-09-12 13:55:47 -07001336extern "C" void foo() {
1337 LOG(INFO) << "foo";
1338 std::this_thread::sleep_for(1s);
1339}
1340
1341extern "C" void bar() {
1342 LOG(INFO) << "bar";
1343 std::this_thread::sleep_for(1s);
1344}
1345
Josh Gaoe04ca272018-01-16 15:38:17 -08001346TEST_F(CrasherTest, seccomp_backtrace) {
1347 int intercept_result;
1348 unique_fd output_fd;
1349
1350 static const auto dump_type = kDebuggerdNativeBacktrace;
1351 StartProcess(
1352 []() {
Josh Gao6f9eeec2018-09-12 13:55:47 -07001353 std::thread a(foo);
1354 std::thread b(bar);
1355
1356 std::this_thread::sleep_for(100ms);
1357
Josh Gaoe04ca272018-01-16 15:38:17 -08001358 raise_debugger_signal(dump_type);
1359 _exit(0);
1360 },
1361 &seccomp_fork);
1362
1363 StartIntercept(&output_fd, dump_type);
1364 FinishCrasher();
1365 AssertDeath(0);
1366 FinishIntercept(&intercept_result);
1367 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1368
1369 std::string result;
1370 ConsumeFd(std::move(output_fd), &result);
1371 ASSERT_BACKTRACE_FRAME(result, "raise_debugger_signal");
Josh Gao6f9eeec2018-09-12 13:55:47 -07001372 ASSERT_BACKTRACE_FRAME(result, "foo");
1373 ASSERT_BACKTRACE_FRAME(result, "bar");
Josh Gaoe04ca272018-01-16 15:38:17 -08001374}
1375
1376TEST_F(CrasherTest, seccomp_crash_logcat) {
1377 StartProcess([]() { abort(); }, &seccomp_fork);
1378 FinishCrasher();
1379
1380 // Make sure we don't get SIGSYS when trying to dump a crash to logcat.
1381 AssertDeath(SIGABRT);
1382}
1383
Josh Gaofd13bf02017-08-18 15:37:26 -07001384TEST_F(CrasherTest, competing_tracer) {
1385 int intercept_result;
1386 unique_fd output_fd;
1387 StartProcess([]() {
Josh Gao2b2ae0c2017-08-21 14:31:17 -07001388 raise(SIGABRT);
Josh Gaofd13bf02017-08-18 15:37:26 -07001389 });
1390
1391 StartIntercept(&output_fd);
Josh Gaofd13bf02017-08-18 15:37:26 -07001392
1393 ASSERT_EQ(0, ptrace(PTRACE_SEIZE, crasher_pid, 0, 0));
Josh Gao2b2ae0c2017-08-21 14:31:17 -07001394 FinishCrasher();
Josh Gaofd13bf02017-08-18 15:37:26 -07001395
1396 int status;
Christopher Ferris172b0a02019-09-18 17:48:30 -07001397 ASSERT_EQ(crasher_pid, TEMP_FAILURE_RETRY(waitpid(crasher_pid, &status, 0)));
Josh Gaofd13bf02017-08-18 15:37:26 -07001398 ASSERT_TRUE(WIFSTOPPED(status));
1399 ASSERT_EQ(SIGABRT, WSTOPSIG(status));
1400
1401 ASSERT_EQ(0, ptrace(PTRACE_CONT, crasher_pid, 0, SIGABRT));
1402 FinishIntercept(&intercept_result);
1403 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1404
1405 std::string result;
1406 ConsumeFd(std::move(output_fd), &result);
1407 std::string regex = R"(failed to attach to thread \d+, already traced by )";
1408 regex += std::to_string(gettid());
1409 regex += R"( \(.+debuggerd_test)";
1410 ASSERT_MATCH(result, regex.c_str());
1411
Christopher Ferris172b0a02019-09-18 17:48:30 -07001412 ASSERT_EQ(crasher_pid, TEMP_FAILURE_RETRY(waitpid(crasher_pid, &status, 0)));
Josh Gao2b2ae0c2017-08-21 14:31:17 -07001413 ASSERT_TRUE(WIFSTOPPED(status));
1414 ASSERT_EQ(SIGABRT, WSTOPSIG(status));
1415
Josh Gaofd13bf02017-08-18 15:37:26 -07001416 ASSERT_EQ(0, ptrace(PTRACE_DETACH, crasher_pid, 0, SIGABRT));
1417 AssertDeath(SIGABRT);
1418}
1419
Josh Gaobf06a402018-08-27 16:34:01 -07001420TEST_F(CrasherTest, fdsan_warning_abort_message) {
1421 int intercept_result;
1422 unique_fd output_fd;
1423
1424 StartProcess([]() {
1425 android_fdsan_set_error_level(ANDROID_FDSAN_ERROR_LEVEL_WARN_ONCE);
Christopher Ferris172b0a02019-09-18 17:48:30 -07001426 unique_fd fd(TEMP_FAILURE_RETRY(open("/dev/null", O_RDONLY | O_CLOEXEC)));
Josh Gaobf06a402018-08-27 16:34:01 -07001427 if (fd == -1) {
1428 abort();
1429 }
1430 close(fd.get());
1431 _exit(0);
1432 });
1433
1434 StartIntercept(&output_fd);
1435 FinishCrasher();
1436 AssertDeath(0);
1437 FinishIntercept(&intercept_result);
1438 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1439
1440 std::string result;
1441 ConsumeFd(std::move(output_fd), &result);
1442 ASSERT_MATCH(result, "Abort message: 'attempted to close");
1443}
1444
Josh Gaoc3c8c022017-02-13 16:36:18 -08001445TEST(crash_dump, zombie) {
1446 pid_t forkpid = fork();
1447
Josh Gaoc3c8c022017-02-13 16:36:18 -08001448 pid_t rc;
1449 int status;
1450
1451 if (forkpid == 0) {
1452 errno = 0;
1453 rc = waitpid(-1, &status, WNOHANG | __WALL | __WNOTHREAD);
1454 if (rc != -1 || errno != ECHILD) {
1455 errx(2, "first waitpid returned %d (%s), expected failure with ECHILD", rc, strerror(errno));
1456 }
1457
Josh Gaoa48b41b2019-12-13 14:11:04 -08001458 raise(BIONIC_SIGNAL_DEBUGGER);
Josh Gaoc3c8c022017-02-13 16:36:18 -08001459
1460 errno = 0;
Christopher Ferris172b0a02019-09-18 17:48:30 -07001461 rc = TEMP_FAILURE_RETRY(waitpid(-1, &status, __WALL | __WNOTHREAD));
Josh Gaoc3c8c022017-02-13 16:36:18 -08001462 if (rc != -1 || errno != ECHILD) {
1463 errx(2, "second waitpid returned %d (%s), expected failure with ECHILD", rc, strerror(errno));
1464 }
1465 _exit(0);
1466 } else {
Christopher Ferris172b0a02019-09-18 17:48:30 -07001467 rc = TEMP_FAILURE_RETRY(waitpid(forkpid, &status, 0));
Josh Gaoc3c8c022017-02-13 16:36:18 -08001468 ASSERT_EQ(forkpid, rc);
1469 ASSERT_TRUE(WIFEXITED(status));
1470 ASSERT_EQ(0, WEXITSTATUS(status));
1471 }
1472}
Josh Gao352a8452017-03-30 16:46:21 -07001473
1474TEST(tombstoned, no_notify) {
1475 // Do this a few times.
1476 for (int i = 0; i < 3; ++i) {
1477 pid_t pid = 123'456'789 + i;
1478
1479 unique_fd intercept_fd, output_fd;
Narayan Kamathca5e9082017-06-02 15:42:06 +01001480 InterceptStatus status;
1481 tombstoned_intercept(pid, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
1482 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gao352a8452017-03-30 16:46:21 -07001483
1484 {
1485 unique_fd tombstoned_socket, input_fd;
Narayan Kamatha73df602017-05-24 15:07:25 +01001486 ASSERT_TRUE(tombstoned_connect(pid, &tombstoned_socket, &input_fd, kDebuggerdTombstone));
Josh Gao352a8452017-03-30 16:46:21 -07001487 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), &pid, sizeof(pid)));
1488 }
1489
1490 pid_t read_pid;
1491 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), &read_pid, sizeof(read_pid)));
1492 ASSERT_EQ(read_pid, pid);
1493 }
1494}
1495
1496TEST(tombstoned, stress) {
1497 // Spawn threads to simultaneously do a bunch of failing dumps and a bunch of successful dumps.
1498 static constexpr int kDumpCount = 100;
1499
1500 std::atomic<bool> start(false);
1501 std::vector<std::thread> threads;
1502 threads.emplace_back([&start]() {
1503 while (!start) {
1504 continue;
1505 }
1506
1507 // Use a way out of range pid, to avoid stomping on an actual process.
1508 pid_t pid_base = 1'000'000;
1509
1510 for (int dump = 0; dump < kDumpCount; ++dump) {
1511 pid_t pid = pid_base + dump;
1512
1513 unique_fd intercept_fd, output_fd;
Narayan Kamathca5e9082017-06-02 15:42:06 +01001514 InterceptStatus status;
1515 tombstoned_intercept(pid, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
1516 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gao352a8452017-03-30 16:46:21 -07001517
1518 // Pretend to crash, and then immediately close the socket.
1519 unique_fd sockfd(socket_local_client(kTombstonedCrashSocketName,
1520 ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_SEQPACKET));
1521 if (sockfd == -1) {
1522 FAIL() << "failed to connect to tombstoned: " << strerror(errno);
1523 }
1524 TombstonedCrashPacket packet = {};
1525 packet.packet_type = CrashPacketType::kDumpRequest;
1526 packet.packet.dump_request.pid = pid;
1527 if (TEMP_FAILURE_RETRY(write(sockfd, &packet, sizeof(packet))) != sizeof(packet)) {
1528 FAIL() << "failed to write to tombstoned: " << strerror(errno);
1529 }
1530
1531 continue;
1532 }
1533 });
1534
1535 threads.emplace_back([&start]() {
1536 while (!start) {
1537 continue;
1538 }
1539
1540 // Use a way out of range pid, to avoid stomping on an actual process.
1541 pid_t pid_base = 2'000'000;
1542
1543 for (int dump = 0; dump < kDumpCount; ++dump) {
1544 pid_t pid = pid_base + dump;
1545
1546 unique_fd intercept_fd, output_fd;
Narayan Kamathca5e9082017-06-02 15:42:06 +01001547 InterceptStatus status;
1548 tombstoned_intercept(pid, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
1549 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gao352a8452017-03-30 16:46:21 -07001550
1551 {
1552 unique_fd tombstoned_socket, input_fd;
Narayan Kamatha73df602017-05-24 15:07:25 +01001553 ASSERT_TRUE(tombstoned_connect(pid, &tombstoned_socket, &input_fd, kDebuggerdTombstone));
Josh Gao352a8452017-03-30 16:46:21 -07001554 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), &pid, sizeof(pid)));
1555 tombstoned_notify_completion(tombstoned_socket.get());
1556 }
1557
1558 // TODO: Fix the race that requires this sleep.
1559 std::this_thread::sleep_for(50ms);
1560
1561 pid_t read_pid;
1562 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), &read_pid, sizeof(read_pid)));
1563 ASSERT_EQ(read_pid, pid);
1564 }
1565 });
1566
1567 start = true;
1568
1569 for (std::thread& thread : threads) {
1570 thread.join();
1571 }
1572}
Narayan Kamathca5e9082017-06-02 15:42:06 +01001573
1574TEST(tombstoned, java_trace_intercept_smoke) {
1575 // Using a "real" PID is a little dangerous here - if the test fails
1576 // or crashes, we might end up getting a bogus / unreliable stack
1577 // trace.
1578 const pid_t self = getpid();
1579
1580 unique_fd intercept_fd, output_fd;
1581 InterceptStatus status;
1582 tombstoned_intercept(self, &intercept_fd, &output_fd, &status, kDebuggerdJavaBacktrace);
1583 ASSERT_EQ(InterceptStatus::kRegistered, status);
1584
Josh Gao76e1e302021-01-26 15:53:11 -08001585 // First connect to tombstoned requesting a native tombstone. This
Narayan Kamathca5e9082017-06-02 15:42:06 +01001586 // should result in a "regular" FD and not the installed intercept.
1587 const char native[] = "native";
1588 unique_fd tombstoned_socket, input_fd;
Josh Gao76e1e302021-01-26 15:53:11 -08001589 ASSERT_TRUE(tombstoned_connect(self, &tombstoned_socket, &input_fd, kDebuggerdTombstone));
Narayan Kamathca5e9082017-06-02 15:42:06 +01001590 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), native, sizeof(native)));
1591 tombstoned_notify_completion(tombstoned_socket.get());
1592
1593 // Then, connect to tombstoned asking for a java backtrace. This *should*
1594 // trigger the intercept.
1595 const char java[] = "java";
1596 ASSERT_TRUE(tombstoned_connect(self, &tombstoned_socket, &input_fd, kDebuggerdJavaBacktrace));
1597 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), java, sizeof(java)));
1598 tombstoned_notify_completion(tombstoned_socket.get());
1599
1600 char outbuf[sizeof(java)];
1601 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), outbuf, sizeof(outbuf)));
1602 ASSERT_STREQ("java", outbuf);
1603}
1604
1605TEST(tombstoned, multiple_intercepts) {
1606 const pid_t fake_pid = 1'234'567;
1607 unique_fd intercept_fd, output_fd;
1608 InterceptStatus status;
1609 tombstoned_intercept(fake_pid, &intercept_fd, &output_fd, &status, kDebuggerdJavaBacktrace);
1610 ASSERT_EQ(InterceptStatus::kRegistered, status);
1611
1612 unique_fd intercept_fd_2, output_fd_2;
1613 tombstoned_intercept(fake_pid, &intercept_fd_2, &output_fd_2, &status, kDebuggerdNativeBacktrace);
1614 ASSERT_EQ(InterceptStatus::kFailedAlreadyRegistered, status);
1615}
1616
1617TEST(tombstoned, intercept_any) {
1618 const pid_t fake_pid = 1'234'567;
1619
1620 unique_fd intercept_fd, output_fd;
1621 InterceptStatus status;
1622 tombstoned_intercept(fake_pid, &intercept_fd, &output_fd, &status, kDebuggerdNativeBacktrace);
1623 ASSERT_EQ(InterceptStatus::kRegistered, status);
1624
1625 const char any[] = "any";
1626 unique_fd tombstoned_socket, input_fd;
1627 ASSERT_TRUE(tombstoned_connect(fake_pid, &tombstoned_socket, &input_fd, kDebuggerdAnyIntercept));
1628 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), any, sizeof(any)));
1629 tombstoned_notify_completion(tombstoned_socket.get());
1630
1631 char outbuf[sizeof(any)];
1632 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), outbuf, sizeof(outbuf)));
1633 ASSERT_STREQ("any", outbuf);
1634}
Josh Gao2b22ae12018-09-12 14:51:03 -07001635
1636TEST(tombstoned, interceptless_backtrace) {
1637 // Generate 50 backtraces, and then check to see that we haven't created 50 new tombstones.
1638 auto get_tombstone_timestamps = []() -> std::map<int, time_t> {
1639 std::map<int, time_t> result;
1640 for (int i = 0; i < 99; ++i) {
1641 std::string path = android::base::StringPrintf("/data/tombstones/tombstone_%02d", i);
1642 struct stat st;
1643 if (stat(path.c_str(), &st) == 0) {
1644 result[i] = st.st_mtim.tv_sec;
1645 }
1646 }
1647 return result;
1648 };
1649
1650 auto before = get_tombstone_timestamps();
1651 for (int i = 0; i < 50; ++i) {
1652 raise_debugger_signal(kDebuggerdNativeBacktrace);
1653 }
1654 auto after = get_tombstone_timestamps();
1655
1656 int diff = 0;
1657 for (int i = 0; i < 99; ++i) {
1658 if (after.count(i) == 0) {
1659 continue;
1660 }
1661 if (before.count(i) == 0) {
1662 ++diff;
1663 continue;
1664 }
1665 if (before[i] != after[i]) {
1666 ++diff;
1667 }
1668 }
1669
1670 // We can't be sure that nothing's crash looping in the background.
1671 // This should be good enough, though...
1672 ASSERT_LT(diff, 10) << "too many new tombstones; is something crashing in the background?";
1673}
Christopher Ferris481e8372019-07-15 17:13:24 -07001674
1675static __attribute__((__noinline__)) void overflow_stack(void* p) {
1676 void* buf[1];
1677 buf[0] = p;
1678 static volatile void* global = buf;
1679 if (global) {
1680 global = buf;
1681 overflow_stack(&buf);
1682 }
1683}
1684
1685TEST_F(CrasherTest, stack_overflow) {
1686 int intercept_result;
1687 unique_fd output_fd;
1688 StartProcess([]() { overflow_stack(nullptr); });
1689
1690 StartIntercept(&output_fd);
1691 FinishCrasher();
1692 AssertDeath(SIGSEGV);
1693 FinishIntercept(&intercept_result);
1694
1695 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1696
1697 std::string result;
1698 ConsumeFd(std::move(output_fd), &result);
1699 ASSERT_MATCH(result, R"(Cause: stack pointer[^\n]*stack overflow.\n)");
1700}
Josh Gao76e1e302021-01-26 15:53:11 -08001701
Christopher Ferrisfe751c52021-04-16 09:40:40 -07001702static bool CopySharedLibrary(const char* tmp_dir, std::string* tmp_so_name) {
1703 std::string test_lib(testing::internal::GetArgvs()[0]);
1704 auto const value = test_lib.find_last_of('/');
1705 if (value == std::string::npos) {
1706 test_lib = "./";
1707 } else {
1708 test_lib = test_lib.substr(0, value + 1) + "./";
1709 }
1710 test_lib += "libcrash_test.so";
1711
1712 *tmp_so_name = std::string(tmp_dir) + "/libcrash_test.so";
1713 std::string cp_cmd = android::base::StringPrintf("cp %s %s", test_lib.c_str(), tmp_dir);
1714
1715 // Copy the shared so to a tempory directory.
1716 return system(cp_cmd.c_str()) == 0;
1717}
1718
1719TEST_F(CrasherTest, unreadable_elf) {
1720 int intercept_result;
1721 unique_fd output_fd;
1722 StartProcess([]() {
1723 TemporaryDir td;
1724 std::string tmp_so_name;
1725 if (!CopySharedLibrary(td.path, &tmp_so_name)) {
1726 _exit(1);
1727 }
1728 void* handle = dlopen(tmp_so_name.c_str(), RTLD_NOW);
1729 if (handle == nullptr) {
1730 _exit(1);
1731 }
1732 // Delete the original shared library so that we get the warning
1733 // about unreadable elf files.
1734 if (unlink(tmp_so_name.c_str()) == -1) {
1735 _exit(1);
1736 }
1737 void (*crash_func)() = reinterpret_cast<void (*)()>(dlsym(handle, "crash"));
1738 if (crash_func == nullptr) {
1739 _exit(1);
1740 }
1741 crash_func();
1742 });
1743
1744 StartIntercept(&output_fd);
1745 FinishCrasher();
1746 AssertDeath(SIGSEGV);
1747 FinishIntercept(&intercept_result);
1748
1749 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1750
1751 std::string result;
1752 ConsumeFd(std::move(output_fd), &result);
1753 ASSERT_MATCH(result, R"(NOTE: Function names and BuildId information is missing )");
1754}
1755
Josh Gao76e1e302021-01-26 15:53:11 -08001756TEST(tombstoned, proto) {
1757 const pid_t self = getpid();
1758 unique_fd tombstoned_socket, text_fd, proto_fd;
1759 ASSERT_TRUE(
1760 tombstoned_connect(self, &tombstoned_socket, &text_fd, &proto_fd, kDebuggerdTombstoneProto));
1761
1762 tombstoned_notify_completion(tombstoned_socket.get());
1763
1764 ASSERT_NE(-1, text_fd.get());
1765 ASSERT_NE(-1, proto_fd.get());
1766
1767 struct stat text_st;
1768 ASSERT_EQ(0, fstat(text_fd.get(), &text_st));
1769
1770 // Give tombstoned some time to link the files into place.
1771 std::this_thread::sleep_for(100ms);
1772
1773 // Find the tombstone.
Christopher Ferris35da2882021-02-17 15:39:06 -08001774 std::optional<std::string> tombstone_file;
1775 std::unique_ptr<DIR, decltype(&closedir)> dir_h(opendir("/data/tombstones"), closedir);
1776 ASSERT_TRUE(dir_h != nullptr);
1777 std::regex tombstone_re("tombstone_\\d+");
1778 dirent* entry;
1779 while ((entry = readdir(dir_h.get())) != nullptr) {
1780 if (!std::regex_match(entry->d_name, tombstone_re)) {
1781 continue;
1782 }
1783 std::string path = android::base::StringPrintf("/data/tombstones/%s", entry->d_name);
Josh Gao76e1e302021-01-26 15:53:11 -08001784
1785 struct stat st;
1786 if (TEMP_FAILURE_RETRY(stat(path.c_str(), &st)) != 0) {
1787 continue;
1788 }
1789
1790 if (st.st_dev == text_st.st_dev && st.st_ino == text_st.st_ino) {
Christopher Ferris35da2882021-02-17 15:39:06 -08001791 tombstone_file = path;
Josh Gao76e1e302021-01-26 15:53:11 -08001792 break;
1793 }
1794 }
1795
Christopher Ferris35da2882021-02-17 15:39:06 -08001796 ASSERT_TRUE(tombstone_file);
1797 std::string proto_path = tombstone_file.value() + ".pb";
Josh Gao76e1e302021-01-26 15:53:11 -08001798
1799 struct stat proto_fd_st;
1800 struct stat proto_file_st;
1801 ASSERT_EQ(0, fstat(proto_fd.get(), &proto_fd_st));
1802 ASSERT_EQ(0, stat(proto_path.c_str(), &proto_file_st));
1803
1804 ASSERT_EQ(proto_fd_st.st_dev, proto_file_st.st_dev);
1805 ASSERT_EQ(proto_fd_st.st_ino, proto_file_st.st_ino);
1806}
1807
1808TEST(tombstoned, proto_intercept) {
1809 const pid_t self = getpid();
1810 unique_fd intercept_fd, output_fd;
1811 InterceptStatus status;
1812
1813 tombstoned_intercept(self, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
1814 ASSERT_EQ(InterceptStatus::kRegistered, status);
1815
1816 unique_fd tombstoned_socket, text_fd, proto_fd;
1817 ASSERT_TRUE(
1818 tombstoned_connect(self, &tombstoned_socket, &text_fd, &proto_fd, kDebuggerdTombstoneProto));
1819 ASSERT_TRUE(android::base::WriteStringToFd("foo", text_fd.get()));
1820 tombstoned_notify_completion(tombstoned_socket.get());
1821
1822 text_fd.reset();
1823
1824 std::string output;
1825 ASSERT_TRUE(android::base::ReadFdToString(output_fd, &output));
1826 ASSERT_EQ("foo", output);
1827}
Christopher Ferrisa3e9a0b2021-07-29 12:38:07 -07001828
1829// Verify that when an intercept is present for the main thread, and the signal
1830// is received on a different thread, the intercept still works.
1831TEST_F(CrasherTest, intercept_for_main_thread_signal_on_side_thread) {
1832 StartProcess([]() {
1833 std::thread thread([]() {
1834 // Raise the signal on the side thread.
1835 raise_debugger_signal(kDebuggerdNativeBacktrace);
1836 });
1837 thread.join();
1838 _exit(0);
1839 });
1840
1841 unique_fd output_fd;
1842 StartIntercept(&output_fd, kDebuggerdNativeBacktrace);
1843 FinishCrasher();
1844 AssertDeath(0);
1845
1846 int intercept_result;
1847 FinishIntercept(&intercept_result);
1848 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1849
1850 std::string result;
1851 ConsumeFd(std::move(output_fd), &result);
1852 ASSERT_BACKTRACE_FRAME(result, "raise_debugger_signal");
1853}