blob: 68c9aca71c95ce9e5e87ecba2381e0c6b6dc870a [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
Christopher Ferrise8891452021-08-17 17:34:53 -0700964TEST_F(CrasherTest, abort_message_newline_trimmed) {
965 int intercept_result;
966 unique_fd output_fd;
967 StartProcess([]() {
968 android_set_abort_message("Message with a newline.\n");
969 abort();
970 });
971 StartIntercept(&output_fd);
972 FinishCrasher();
973 AssertDeath(SIGABRT);
974 FinishIntercept(&intercept_result);
975
976 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
977
978 std::string result;
979 ConsumeFd(std::move(output_fd), &result);
980 ASSERT_MATCH(result, R"(Abort message: 'Message with a newline.')");
981}
982
983TEST_F(CrasherTest, abort_message_multiple_newlines_trimmed) {
984 int intercept_result;
985 unique_fd output_fd;
986 StartProcess([]() {
987 android_set_abort_message("Message with multiple newlines.\n\n\n\n\n");
988 abort();
989 });
990 StartIntercept(&output_fd);
991 FinishCrasher();
992 AssertDeath(SIGABRT);
993 FinishIntercept(&intercept_result);
994
995 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
996
997 std::string result;
998 ConsumeFd(std::move(output_fd), &result);
999 ASSERT_MATCH(result, R"(Abort message: 'Message with multiple newlines.')");
1000}
1001
Josh Gaoe06f2a42017-04-27 16:50:38 -07001002TEST_F(CrasherTest, abort_message_backtrace) {
1003 int intercept_result;
1004 unique_fd output_fd;
1005 StartProcess([]() {
1006 android_set_abort_message("not actually aborting");
Josh Gaoa48b41b2019-12-13 14:11:04 -08001007 raise(BIONIC_SIGNAL_DEBUGGER);
Josh Gaoe06f2a42017-04-27 16:50:38 -07001008 exit(0);
1009 });
1010 StartIntercept(&output_fd);
1011 FinishCrasher();
1012 AssertDeath(0);
1013 FinishIntercept(&intercept_result);
1014
1015 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1016
1017 std::string result;
1018 ConsumeFd(std::move(output_fd), &result);
1019 ASSERT_NOT_MATCH(result, R"(Abort message:)");
1020}
1021
Josh Gaocbe70cb2016-10-18 18:17:52 -07001022TEST_F(CrasherTest, intercept_timeout) {
1023 int intercept_result;
1024 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -08001025 StartProcess([]() {
1026 abort();
1027 });
Josh Gaocbe70cb2016-10-18 18:17:52 -07001028 StartIntercept(&output_fd);
1029
1030 // Don't let crasher finish until we timeout.
1031 FinishIntercept(&intercept_result);
1032
1033 ASSERT_NE(1, intercept_result) << "tombstoned reported success? (intercept_result = "
1034 << intercept_result << ")";
1035
1036 FinishCrasher();
1037 AssertDeath(SIGABRT);
1038}
1039
Elliott Hughese4781d52021-03-17 09:15:15 -07001040TEST_F(CrasherTest, wait_for_debugger) {
1041 if (!android::base::SetProperty(kWaitForDebuggerKey, "1")) {
1042 FAIL() << "failed to enable wait_for_debugger";
Josh Gaocbe70cb2016-10-18 18:17:52 -07001043 }
1044 sleep(1);
1045
Josh Gao502cfd22017-02-17 01:39:15 -08001046 StartProcess([]() {
1047 abort();
1048 });
Josh Gaocbe70cb2016-10-18 18:17:52 -07001049 FinishCrasher();
1050
1051 int status;
Christopher Ferris172b0a02019-09-18 17:48:30 -07001052 ASSERT_EQ(crasher_pid, TEMP_FAILURE_RETRY(waitpid(crasher_pid, &status, WUNTRACED)));
Josh Gaocbe70cb2016-10-18 18:17:52 -07001053 ASSERT_TRUE(WIFSTOPPED(status));
1054 ASSERT_EQ(SIGSTOP, WSTOPSIG(status));
1055
1056 ASSERT_EQ(0, kill(crasher_pid, SIGCONT));
1057
1058 AssertDeath(SIGABRT);
1059}
1060
Josh Gaocbe70cb2016-10-18 18:17:52 -07001061TEST_F(CrasherTest, backtrace) {
1062 std::string result;
1063 int intercept_result;
1064 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -08001065
1066 StartProcess([]() {
1067 abort();
1068 });
Narayan Kamatha73df602017-05-24 15:07:25 +01001069 StartIntercept(&output_fd, kDebuggerdNativeBacktrace);
Josh Gaocbe70cb2016-10-18 18:17:52 -07001070
1071 std::this_thread::sleep_for(500ms);
1072
1073 sigval val;
1074 val.sival_int = 1;
Josh Gaoa48b41b2019-12-13 14:11:04 -08001075 ASSERT_EQ(0, sigqueue(crasher_pid, BIONIC_SIGNAL_DEBUGGER, val)) << strerror(errno);
Josh Gaocbe70cb2016-10-18 18:17:52 -07001076 FinishIntercept(&intercept_result);
1077 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1078 ConsumeFd(std::move(output_fd), &result);
Jaesung Chung58778e12017-06-15 18:20:34 +09001079 ASSERT_BACKTRACE_FRAME(result, "read");
Josh Gaocbe70cb2016-10-18 18:17:52 -07001080
1081 int status;
1082 ASSERT_EQ(0, waitpid(crasher_pid, &status, WNOHANG | WUNTRACED));
1083
1084 StartIntercept(&output_fd);
1085 FinishCrasher();
1086 AssertDeath(SIGABRT);
1087 FinishIntercept(&intercept_result);
1088 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1089 ConsumeFd(std::move(output_fd), &result);
Andreas Gampe26cbafb2017-06-22 20:14:43 -07001090 ASSERT_BACKTRACE_FRAME(result, "abort");
Josh Gaocbe70cb2016-10-18 18:17:52 -07001091}
Josh Gaofca7ca32017-01-23 12:05:35 -08001092
1093TEST_F(CrasherTest, PR_SET_DUMPABLE_0_crash) {
Josh Gao502cfd22017-02-17 01:39:15 -08001094 int intercept_result;
1095 unique_fd output_fd;
Josh Gaofca7ca32017-01-23 12:05:35 -08001096 StartProcess([]() {
1097 prctl(PR_SET_DUMPABLE, 0);
Josh Gao502cfd22017-02-17 01:39:15 -08001098 abort();
Josh Gaofca7ca32017-01-23 12:05:35 -08001099 });
Josh Gao502cfd22017-02-17 01:39:15 -08001100
1101 StartIntercept(&output_fd);
1102 FinishCrasher();
1103 AssertDeath(SIGABRT);
1104 FinishIntercept(&intercept_result);
1105
1106 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1107
1108 std::string result;
1109 ConsumeFd(std::move(output_fd), &result);
Andreas Gampe26cbafb2017-06-22 20:14:43 -07001110 ASSERT_BACKTRACE_FRAME(result, "abort");
Josh Gaofca7ca32017-01-23 12:05:35 -08001111}
1112
Josh Gao502cfd22017-02-17 01:39:15 -08001113TEST_F(CrasherTest, capabilities) {
1114 ASSERT_EQ(0U, getuid()) << "capability test requires root";
1115
Josh Gaofca7ca32017-01-23 12:05:35 -08001116 StartProcess([]() {
Josh Gao502cfd22017-02-17 01:39:15 -08001117 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) != 0) {
1118 err(1, "failed to set PR_SET_KEEPCAPS");
1119 }
1120
1121 if (setresuid(1, 1, 1) != 0) {
1122 err(1, "setresuid failed");
1123 }
1124
1125 __user_cap_header_struct capheader;
1126 __user_cap_data_struct capdata[2];
1127 memset(&capheader, 0, sizeof(capheader));
1128 memset(&capdata, 0, sizeof(capdata));
1129
1130 capheader.version = _LINUX_CAPABILITY_VERSION_3;
1131 capheader.pid = 0;
1132
1133 // Turn on every third capability.
1134 static_assert(CAP_LAST_CAP > 33, "CAP_LAST_CAP <= 32");
1135 for (int i = 0; i < CAP_LAST_CAP; i += 3) {
1136 capdata[CAP_TO_INDEX(i)].permitted |= CAP_TO_MASK(i);
1137 capdata[CAP_TO_INDEX(i)].effective |= CAP_TO_MASK(i);
1138 }
1139
1140 // Make sure CAP_SYS_PTRACE is off.
1141 capdata[CAP_TO_INDEX(CAP_SYS_PTRACE)].permitted &= ~(CAP_TO_MASK(CAP_SYS_PTRACE));
1142 capdata[CAP_TO_INDEX(CAP_SYS_PTRACE)].effective &= ~(CAP_TO_MASK(CAP_SYS_PTRACE));
1143
1144 if (capset(&capheader, &capdata[0]) != 0) {
1145 err(1, "capset failed");
1146 }
1147
1148 if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_CLEAR_ALL, 0, 0, 0) != 0) {
1149 err(1, "failed to drop ambient capabilities");
1150 }
1151
Josh Gaoa5199a92017-04-03 13:18:34 -07001152 pthread_setname_np(pthread_self(), "thread_name");
Josh Gao502cfd22017-02-17 01:39:15 -08001153 raise(SIGSYS);
Josh Gaofca7ca32017-01-23 12:05:35 -08001154 });
Josh Gao502cfd22017-02-17 01:39:15 -08001155
1156 unique_fd output_fd;
1157 StartIntercept(&output_fd);
1158 FinishCrasher();
1159 AssertDeath(SIGSYS);
1160
1161 std::string result;
1162 int intercept_result;
1163 FinishIntercept(&intercept_result);
1164 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1165 ConsumeFd(std::move(output_fd), &result);
Josh Gaoa5199a92017-04-03 13:18:34 -07001166 ASSERT_MATCH(result, R"(name: thread_name\s+>>> .+debuggerd_test(32|64) <<<)");
Jaesung Chung58778e12017-06-15 18:20:34 +09001167 ASSERT_BACKTRACE_FRAME(result, "tgkill");
Josh Gaofca7ca32017-01-23 12:05:35 -08001168}
Josh Gaoc3c8c022017-02-13 16:36:18 -08001169
Josh Gao2e7b8e22017-05-04 17:12:57 -07001170TEST_F(CrasherTest, fake_pid) {
1171 int intercept_result;
1172 unique_fd output_fd;
1173
1174 // Prime the getpid/gettid caches.
1175 UNUSED(getpid());
1176 UNUSED(gettid());
1177
1178 std::function<pid_t()> clone_fn = []() {
1179 return syscall(__NR_clone, SIGCHLD, nullptr, nullptr, nullptr, nullptr);
1180 };
1181 StartProcess(
1182 []() {
1183 ASSERT_NE(getpid(), syscall(__NR_getpid));
1184 ASSERT_NE(gettid(), syscall(__NR_gettid));
1185 raise(SIGSEGV);
1186 },
1187 clone_fn);
1188
1189 StartIntercept(&output_fd);
1190 FinishCrasher();
1191 AssertDeath(SIGSEGV);
1192 FinishIntercept(&intercept_result);
1193
1194 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1195
1196 std::string result;
1197 ConsumeFd(std::move(output_fd), &result);
Jaesung Chung58778e12017-06-15 18:20:34 +09001198 ASSERT_BACKTRACE_FRAME(result, "tgkill");
Josh Gao2e7b8e22017-05-04 17:12:57 -07001199}
1200
Josh Gaoe04ca272018-01-16 15:38:17 -08001201static const char* const kDebuggerdSeccompPolicy =
1202 "/system/etc/seccomp_policy/crash_dump." ABI_STRING ".policy";
1203
Josh Gao70adac62018-02-22 11:38:33 -08001204static pid_t seccomp_fork_impl(void (*prejail)()) {
Josh Gao6f9eeec2018-09-12 13:55:47 -07001205 std::string policy;
1206 if (!android::base::ReadFileToString(kDebuggerdSeccompPolicy, &policy)) {
1207 PLOG(FATAL) << "failed to read policy file";
1208 }
1209
1210 // Allow a bunch of syscalls used by the tests.
1211 policy += "\nclone: 1";
1212 policy += "\nsigaltstack: 1";
1213 policy += "\nnanosleep: 1";
Christopher Ferrisab606682019-09-17 15:31:47 -07001214 policy += "\ngetrlimit: 1";
1215 policy += "\nugetrlimit: 1";
Josh Gao6f9eeec2018-09-12 13:55:47 -07001216
1217 FILE* tmp_file = tmpfile();
1218 if (!tmp_file) {
1219 PLOG(FATAL) << "tmpfile failed";
1220 }
1221
Christopher Ferris172b0a02019-09-18 17:48:30 -07001222 unique_fd tmp_fd(TEMP_FAILURE_RETRY(dup(fileno(tmp_file))));
Josh Gao6f9eeec2018-09-12 13:55:47 -07001223 if (!android::base::WriteStringToFd(policy, tmp_fd.get())) {
1224 PLOG(FATAL) << "failed to write policy to tmpfile";
1225 }
1226
1227 if (lseek(tmp_fd.get(), 0, SEEK_SET) != 0) {
1228 PLOG(FATAL) << "failed to seek tmp_fd";
Josh Gaoe04ca272018-01-16 15:38:17 -08001229 }
1230
1231 ScopedMinijail jail{minijail_new()};
1232 if (!jail) {
1233 LOG(FATAL) << "failed to create minijail";
1234 }
1235
1236 minijail_no_new_privs(jail.get());
1237 minijail_log_seccomp_filter_failures(jail.get());
1238 minijail_use_seccomp_filter(jail.get());
Josh Gao6f9eeec2018-09-12 13:55:47 -07001239 minijail_parse_seccomp_filters_from_fd(jail.get(), tmp_fd.release());
Josh Gaoe04ca272018-01-16 15:38:17 -08001240
1241 pid_t result = fork();
1242 if (result == -1) {
1243 return result;
1244 } else if (result != 0) {
1245 return result;
1246 }
1247
1248 // Spawn and detach a thread that spins forever.
1249 std::atomic<bool> thread_ready(false);
1250 std::thread thread([&jail, &thread_ready]() {
1251 minijail_enter(jail.get());
1252 thread_ready = true;
1253 for (;;)
1254 ;
1255 });
1256 thread.detach();
1257
1258 while (!thread_ready) {
1259 continue;
1260 }
1261
Josh Gao70adac62018-02-22 11:38:33 -08001262 if (prejail) {
1263 prejail();
1264 }
1265
Josh Gaoe04ca272018-01-16 15:38:17 -08001266 minijail_enter(jail.get());
1267 return result;
1268}
1269
Josh Gao70adac62018-02-22 11:38:33 -08001270static pid_t seccomp_fork() {
1271 return seccomp_fork_impl(nullptr);
1272}
1273
Josh Gaoe04ca272018-01-16 15:38:17 -08001274TEST_F(CrasherTest, seccomp_crash) {
1275 int intercept_result;
1276 unique_fd output_fd;
1277
1278 StartProcess([]() { abort(); }, &seccomp_fork);
1279
1280 StartIntercept(&output_fd);
1281 FinishCrasher();
1282 AssertDeath(SIGABRT);
1283 FinishIntercept(&intercept_result);
1284 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1285
1286 std::string result;
1287 ConsumeFd(std::move(output_fd), &result);
1288 ASSERT_BACKTRACE_FRAME(result, "abort");
1289}
1290
Josh Gao70adac62018-02-22 11:38:33 -08001291static pid_t seccomp_fork_rlimit() {
1292 return seccomp_fork_impl([]() {
1293 struct rlimit rlim = {
1294 .rlim_cur = 512 * 1024 * 1024,
1295 .rlim_max = 512 * 1024 * 1024,
1296 };
1297
1298 if (setrlimit(RLIMIT_AS, &rlim) != 0) {
1299 raise(SIGINT);
1300 }
1301 });
1302}
1303
1304TEST_F(CrasherTest, seccomp_crash_oom) {
1305 int intercept_result;
1306 unique_fd output_fd;
1307
1308 StartProcess(
1309 []() {
1310 std::vector<void*> vec;
1311 for (int i = 0; i < 512; ++i) {
1312 char* buf = static_cast<char*>(malloc(1024 * 1024));
1313 if (!buf) {
1314 abort();
1315 }
1316 memset(buf, 0xff, 1024 * 1024);
1317 vec.push_back(buf);
1318 }
1319 },
1320 &seccomp_fork_rlimit);
1321
1322 StartIntercept(&output_fd);
1323 FinishCrasher();
1324 AssertDeath(SIGABRT);
1325 FinishIntercept(&intercept_result);
1326 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1327
1328 // We can't actually generate a backtrace, just make sure that the process terminates.
1329}
1330
Josh Gaoe04ca272018-01-16 15:38:17 -08001331__attribute__((noinline)) extern "C" bool raise_debugger_signal(DebuggerdDumpType dump_type) {
1332 siginfo_t siginfo;
1333 siginfo.si_code = SI_QUEUE;
1334 siginfo.si_pid = getpid();
1335 siginfo.si_uid = getuid();
1336
1337 if (dump_type != kDebuggerdNativeBacktrace && dump_type != kDebuggerdTombstone) {
1338 PLOG(FATAL) << "invalid dump type";
1339 }
1340
1341 siginfo.si_value.sival_int = dump_type == kDebuggerdNativeBacktrace;
1342
Josh Gaoa48b41b2019-12-13 14:11:04 -08001343 if (syscall(__NR_rt_tgsigqueueinfo, getpid(), gettid(), BIONIC_SIGNAL_DEBUGGER, &siginfo) != 0) {
Josh Gaoe04ca272018-01-16 15:38:17 -08001344 PLOG(ERROR) << "libdebuggerd_client: failed to send signal to self";
1345 return false;
1346 }
1347
1348 return true;
1349}
1350
1351TEST_F(CrasherTest, seccomp_tombstone) {
1352 int intercept_result;
1353 unique_fd output_fd;
1354
1355 static const auto dump_type = kDebuggerdTombstone;
1356 StartProcess(
1357 []() {
1358 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");
1372}
1373
Josh Gao6f9eeec2018-09-12 13:55:47 -07001374extern "C" void foo() {
1375 LOG(INFO) << "foo";
1376 std::this_thread::sleep_for(1s);
1377}
1378
1379extern "C" void bar() {
1380 LOG(INFO) << "bar";
1381 std::this_thread::sleep_for(1s);
1382}
1383
Josh Gaoe04ca272018-01-16 15:38:17 -08001384TEST_F(CrasherTest, seccomp_backtrace) {
1385 int intercept_result;
1386 unique_fd output_fd;
1387
1388 static const auto dump_type = kDebuggerdNativeBacktrace;
1389 StartProcess(
1390 []() {
Josh Gao6f9eeec2018-09-12 13:55:47 -07001391 std::thread a(foo);
1392 std::thread b(bar);
1393
1394 std::this_thread::sleep_for(100ms);
1395
Josh Gaoe04ca272018-01-16 15:38:17 -08001396 raise_debugger_signal(dump_type);
1397 _exit(0);
1398 },
1399 &seccomp_fork);
1400
1401 StartIntercept(&output_fd, dump_type);
1402 FinishCrasher();
1403 AssertDeath(0);
1404 FinishIntercept(&intercept_result);
1405 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1406
1407 std::string result;
1408 ConsumeFd(std::move(output_fd), &result);
1409 ASSERT_BACKTRACE_FRAME(result, "raise_debugger_signal");
Josh Gao6f9eeec2018-09-12 13:55:47 -07001410 ASSERT_BACKTRACE_FRAME(result, "foo");
1411 ASSERT_BACKTRACE_FRAME(result, "bar");
Josh Gaoe04ca272018-01-16 15:38:17 -08001412}
1413
1414TEST_F(CrasherTest, seccomp_crash_logcat) {
1415 StartProcess([]() { abort(); }, &seccomp_fork);
1416 FinishCrasher();
1417
1418 // Make sure we don't get SIGSYS when trying to dump a crash to logcat.
1419 AssertDeath(SIGABRT);
1420}
1421
Josh Gaofd13bf02017-08-18 15:37:26 -07001422TEST_F(CrasherTest, competing_tracer) {
1423 int intercept_result;
1424 unique_fd output_fd;
1425 StartProcess([]() {
Josh Gao2b2ae0c2017-08-21 14:31:17 -07001426 raise(SIGABRT);
Josh Gaofd13bf02017-08-18 15:37:26 -07001427 });
1428
1429 StartIntercept(&output_fd);
Josh Gaofd13bf02017-08-18 15:37:26 -07001430
1431 ASSERT_EQ(0, ptrace(PTRACE_SEIZE, crasher_pid, 0, 0));
Josh Gao2b2ae0c2017-08-21 14:31:17 -07001432 FinishCrasher();
Josh Gaofd13bf02017-08-18 15:37:26 -07001433
1434 int status;
Christopher Ferris172b0a02019-09-18 17:48:30 -07001435 ASSERT_EQ(crasher_pid, TEMP_FAILURE_RETRY(waitpid(crasher_pid, &status, 0)));
Josh Gaofd13bf02017-08-18 15:37:26 -07001436 ASSERT_TRUE(WIFSTOPPED(status));
1437 ASSERT_EQ(SIGABRT, WSTOPSIG(status));
1438
1439 ASSERT_EQ(0, ptrace(PTRACE_CONT, crasher_pid, 0, SIGABRT));
1440 FinishIntercept(&intercept_result);
1441 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1442
1443 std::string result;
1444 ConsumeFd(std::move(output_fd), &result);
1445 std::string regex = R"(failed to attach to thread \d+, already traced by )";
1446 regex += std::to_string(gettid());
1447 regex += R"( \(.+debuggerd_test)";
1448 ASSERT_MATCH(result, regex.c_str());
1449
Christopher Ferris172b0a02019-09-18 17:48:30 -07001450 ASSERT_EQ(crasher_pid, TEMP_FAILURE_RETRY(waitpid(crasher_pid, &status, 0)));
Josh Gao2b2ae0c2017-08-21 14:31:17 -07001451 ASSERT_TRUE(WIFSTOPPED(status));
1452 ASSERT_EQ(SIGABRT, WSTOPSIG(status));
1453
Josh Gaofd13bf02017-08-18 15:37:26 -07001454 ASSERT_EQ(0, ptrace(PTRACE_DETACH, crasher_pid, 0, SIGABRT));
1455 AssertDeath(SIGABRT);
1456}
1457
Josh Gaobf06a402018-08-27 16:34:01 -07001458TEST_F(CrasherTest, fdsan_warning_abort_message) {
1459 int intercept_result;
1460 unique_fd output_fd;
1461
1462 StartProcess([]() {
1463 android_fdsan_set_error_level(ANDROID_FDSAN_ERROR_LEVEL_WARN_ONCE);
Christopher Ferris172b0a02019-09-18 17:48:30 -07001464 unique_fd fd(TEMP_FAILURE_RETRY(open("/dev/null", O_RDONLY | O_CLOEXEC)));
Josh Gaobf06a402018-08-27 16:34:01 -07001465 if (fd == -1) {
1466 abort();
1467 }
1468 close(fd.get());
1469 _exit(0);
1470 });
1471
1472 StartIntercept(&output_fd);
1473 FinishCrasher();
1474 AssertDeath(0);
1475 FinishIntercept(&intercept_result);
1476 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1477
1478 std::string result;
1479 ConsumeFd(std::move(output_fd), &result);
1480 ASSERT_MATCH(result, "Abort message: 'attempted to close");
1481}
1482
Josh Gaoc3c8c022017-02-13 16:36:18 -08001483TEST(crash_dump, zombie) {
1484 pid_t forkpid = fork();
1485
Josh Gaoc3c8c022017-02-13 16:36:18 -08001486 pid_t rc;
1487 int status;
1488
1489 if (forkpid == 0) {
1490 errno = 0;
1491 rc = waitpid(-1, &status, WNOHANG | __WALL | __WNOTHREAD);
1492 if (rc != -1 || errno != ECHILD) {
1493 errx(2, "first waitpid returned %d (%s), expected failure with ECHILD", rc, strerror(errno));
1494 }
1495
Josh Gaoa48b41b2019-12-13 14:11:04 -08001496 raise(BIONIC_SIGNAL_DEBUGGER);
Josh Gaoc3c8c022017-02-13 16:36:18 -08001497
1498 errno = 0;
Christopher Ferris172b0a02019-09-18 17:48:30 -07001499 rc = TEMP_FAILURE_RETRY(waitpid(-1, &status, __WALL | __WNOTHREAD));
Josh Gaoc3c8c022017-02-13 16:36:18 -08001500 if (rc != -1 || errno != ECHILD) {
1501 errx(2, "second waitpid returned %d (%s), expected failure with ECHILD", rc, strerror(errno));
1502 }
1503 _exit(0);
1504 } else {
Christopher Ferris172b0a02019-09-18 17:48:30 -07001505 rc = TEMP_FAILURE_RETRY(waitpid(forkpid, &status, 0));
Josh Gaoc3c8c022017-02-13 16:36:18 -08001506 ASSERT_EQ(forkpid, rc);
1507 ASSERT_TRUE(WIFEXITED(status));
1508 ASSERT_EQ(0, WEXITSTATUS(status));
1509 }
1510}
Josh Gao352a8452017-03-30 16:46:21 -07001511
1512TEST(tombstoned, no_notify) {
1513 // Do this a few times.
1514 for (int i = 0; i < 3; ++i) {
1515 pid_t pid = 123'456'789 + i;
1516
1517 unique_fd intercept_fd, output_fd;
Narayan Kamathca5e9082017-06-02 15:42:06 +01001518 InterceptStatus status;
1519 tombstoned_intercept(pid, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
1520 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gao352a8452017-03-30 16:46:21 -07001521
1522 {
1523 unique_fd tombstoned_socket, input_fd;
Narayan Kamatha73df602017-05-24 15:07:25 +01001524 ASSERT_TRUE(tombstoned_connect(pid, &tombstoned_socket, &input_fd, kDebuggerdTombstone));
Josh Gao352a8452017-03-30 16:46:21 -07001525 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), &pid, sizeof(pid)));
1526 }
1527
1528 pid_t read_pid;
1529 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), &read_pid, sizeof(read_pid)));
1530 ASSERT_EQ(read_pid, pid);
1531 }
1532}
1533
1534TEST(tombstoned, stress) {
1535 // Spawn threads to simultaneously do a bunch of failing dumps and a bunch of successful dumps.
1536 static constexpr int kDumpCount = 100;
1537
1538 std::atomic<bool> start(false);
1539 std::vector<std::thread> threads;
1540 threads.emplace_back([&start]() {
1541 while (!start) {
1542 continue;
1543 }
1544
1545 // Use a way out of range pid, to avoid stomping on an actual process.
1546 pid_t pid_base = 1'000'000;
1547
1548 for (int dump = 0; dump < kDumpCount; ++dump) {
1549 pid_t pid = pid_base + dump;
1550
1551 unique_fd intercept_fd, output_fd;
Narayan Kamathca5e9082017-06-02 15:42:06 +01001552 InterceptStatus status;
1553 tombstoned_intercept(pid, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
1554 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gao352a8452017-03-30 16:46:21 -07001555
1556 // Pretend to crash, and then immediately close the socket.
1557 unique_fd sockfd(socket_local_client(kTombstonedCrashSocketName,
1558 ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_SEQPACKET));
1559 if (sockfd == -1) {
1560 FAIL() << "failed to connect to tombstoned: " << strerror(errno);
1561 }
1562 TombstonedCrashPacket packet = {};
1563 packet.packet_type = CrashPacketType::kDumpRequest;
1564 packet.packet.dump_request.pid = pid;
1565 if (TEMP_FAILURE_RETRY(write(sockfd, &packet, sizeof(packet))) != sizeof(packet)) {
1566 FAIL() << "failed to write to tombstoned: " << strerror(errno);
1567 }
1568
1569 continue;
1570 }
1571 });
1572
1573 threads.emplace_back([&start]() {
1574 while (!start) {
1575 continue;
1576 }
1577
1578 // Use a way out of range pid, to avoid stomping on an actual process.
1579 pid_t pid_base = 2'000'000;
1580
1581 for (int dump = 0; dump < kDumpCount; ++dump) {
1582 pid_t pid = pid_base + dump;
1583
1584 unique_fd intercept_fd, output_fd;
Narayan Kamathca5e9082017-06-02 15:42:06 +01001585 InterceptStatus status;
1586 tombstoned_intercept(pid, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
1587 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gao352a8452017-03-30 16:46:21 -07001588
1589 {
1590 unique_fd tombstoned_socket, input_fd;
Narayan Kamatha73df602017-05-24 15:07:25 +01001591 ASSERT_TRUE(tombstoned_connect(pid, &tombstoned_socket, &input_fd, kDebuggerdTombstone));
Josh Gao352a8452017-03-30 16:46:21 -07001592 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), &pid, sizeof(pid)));
1593 tombstoned_notify_completion(tombstoned_socket.get());
1594 }
1595
1596 // TODO: Fix the race that requires this sleep.
1597 std::this_thread::sleep_for(50ms);
1598
1599 pid_t read_pid;
1600 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), &read_pid, sizeof(read_pid)));
1601 ASSERT_EQ(read_pid, pid);
1602 }
1603 });
1604
1605 start = true;
1606
1607 for (std::thread& thread : threads) {
1608 thread.join();
1609 }
1610}
Narayan Kamathca5e9082017-06-02 15:42:06 +01001611
1612TEST(tombstoned, java_trace_intercept_smoke) {
1613 // Using a "real" PID is a little dangerous here - if the test fails
1614 // or crashes, we might end up getting a bogus / unreliable stack
1615 // trace.
1616 const pid_t self = getpid();
1617
1618 unique_fd intercept_fd, output_fd;
1619 InterceptStatus status;
1620 tombstoned_intercept(self, &intercept_fd, &output_fd, &status, kDebuggerdJavaBacktrace);
1621 ASSERT_EQ(InterceptStatus::kRegistered, status);
1622
Josh Gao76e1e302021-01-26 15:53:11 -08001623 // First connect to tombstoned requesting a native tombstone. This
Narayan Kamathca5e9082017-06-02 15:42:06 +01001624 // should result in a "regular" FD and not the installed intercept.
1625 const char native[] = "native";
1626 unique_fd tombstoned_socket, input_fd;
Josh Gao76e1e302021-01-26 15:53:11 -08001627 ASSERT_TRUE(tombstoned_connect(self, &tombstoned_socket, &input_fd, kDebuggerdTombstone));
Narayan Kamathca5e9082017-06-02 15:42:06 +01001628 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), native, sizeof(native)));
1629 tombstoned_notify_completion(tombstoned_socket.get());
1630
1631 // Then, connect to tombstoned asking for a java backtrace. This *should*
1632 // trigger the intercept.
1633 const char java[] = "java";
1634 ASSERT_TRUE(tombstoned_connect(self, &tombstoned_socket, &input_fd, kDebuggerdJavaBacktrace));
1635 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), java, sizeof(java)));
1636 tombstoned_notify_completion(tombstoned_socket.get());
1637
1638 char outbuf[sizeof(java)];
1639 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), outbuf, sizeof(outbuf)));
1640 ASSERT_STREQ("java", outbuf);
1641}
1642
1643TEST(tombstoned, multiple_intercepts) {
1644 const pid_t fake_pid = 1'234'567;
1645 unique_fd intercept_fd, output_fd;
1646 InterceptStatus status;
1647 tombstoned_intercept(fake_pid, &intercept_fd, &output_fd, &status, kDebuggerdJavaBacktrace);
1648 ASSERT_EQ(InterceptStatus::kRegistered, status);
1649
1650 unique_fd intercept_fd_2, output_fd_2;
1651 tombstoned_intercept(fake_pid, &intercept_fd_2, &output_fd_2, &status, kDebuggerdNativeBacktrace);
1652 ASSERT_EQ(InterceptStatus::kFailedAlreadyRegistered, status);
1653}
1654
1655TEST(tombstoned, intercept_any) {
1656 const pid_t fake_pid = 1'234'567;
1657
1658 unique_fd intercept_fd, output_fd;
1659 InterceptStatus status;
1660 tombstoned_intercept(fake_pid, &intercept_fd, &output_fd, &status, kDebuggerdNativeBacktrace);
1661 ASSERT_EQ(InterceptStatus::kRegistered, status);
1662
1663 const char any[] = "any";
1664 unique_fd tombstoned_socket, input_fd;
1665 ASSERT_TRUE(tombstoned_connect(fake_pid, &tombstoned_socket, &input_fd, kDebuggerdAnyIntercept));
1666 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), any, sizeof(any)));
1667 tombstoned_notify_completion(tombstoned_socket.get());
1668
1669 char outbuf[sizeof(any)];
1670 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), outbuf, sizeof(outbuf)));
1671 ASSERT_STREQ("any", outbuf);
1672}
Josh Gao2b22ae12018-09-12 14:51:03 -07001673
1674TEST(tombstoned, interceptless_backtrace) {
1675 // Generate 50 backtraces, and then check to see that we haven't created 50 new tombstones.
1676 auto get_tombstone_timestamps = []() -> std::map<int, time_t> {
1677 std::map<int, time_t> result;
1678 for (int i = 0; i < 99; ++i) {
1679 std::string path = android::base::StringPrintf("/data/tombstones/tombstone_%02d", i);
1680 struct stat st;
1681 if (stat(path.c_str(), &st) == 0) {
1682 result[i] = st.st_mtim.tv_sec;
1683 }
1684 }
1685 return result;
1686 };
1687
1688 auto before = get_tombstone_timestamps();
1689 for (int i = 0; i < 50; ++i) {
1690 raise_debugger_signal(kDebuggerdNativeBacktrace);
1691 }
1692 auto after = get_tombstone_timestamps();
1693
1694 int diff = 0;
1695 for (int i = 0; i < 99; ++i) {
1696 if (after.count(i) == 0) {
1697 continue;
1698 }
1699 if (before.count(i) == 0) {
1700 ++diff;
1701 continue;
1702 }
1703 if (before[i] != after[i]) {
1704 ++diff;
1705 }
1706 }
1707
1708 // We can't be sure that nothing's crash looping in the background.
1709 // This should be good enough, though...
1710 ASSERT_LT(diff, 10) << "too many new tombstones; is something crashing in the background?";
1711}
Christopher Ferris481e8372019-07-15 17:13:24 -07001712
1713static __attribute__((__noinline__)) void overflow_stack(void* p) {
1714 void* buf[1];
1715 buf[0] = p;
1716 static volatile void* global = buf;
1717 if (global) {
1718 global = buf;
1719 overflow_stack(&buf);
1720 }
1721}
1722
1723TEST_F(CrasherTest, stack_overflow) {
1724 int intercept_result;
1725 unique_fd output_fd;
1726 StartProcess([]() { overflow_stack(nullptr); });
1727
1728 StartIntercept(&output_fd);
1729 FinishCrasher();
1730 AssertDeath(SIGSEGV);
1731 FinishIntercept(&intercept_result);
1732
1733 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1734
1735 std::string result;
1736 ConsumeFd(std::move(output_fd), &result);
1737 ASSERT_MATCH(result, R"(Cause: stack pointer[^\n]*stack overflow.\n)");
1738}
Josh Gao76e1e302021-01-26 15:53:11 -08001739
Christopher Ferrisfe751c52021-04-16 09:40:40 -07001740static bool CopySharedLibrary(const char* tmp_dir, std::string* tmp_so_name) {
1741 std::string test_lib(testing::internal::GetArgvs()[0]);
1742 auto const value = test_lib.find_last_of('/');
1743 if (value == std::string::npos) {
1744 test_lib = "./";
1745 } else {
1746 test_lib = test_lib.substr(0, value + 1) + "./";
1747 }
1748 test_lib += "libcrash_test.so";
1749
1750 *tmp_so_name = std::string(tmp_dir) + "/libcrash_test.so";
1751 std::string cp_cmd = android::base::StringPrintf("cp %s %s", test_lib.c_str(), tmp_dir);
1752
1753 // Copy the shared so to a tempory directory.
1754 return system(cp_cmd.c_str()) == 0;
1755}
1756
1757TEST_F(CrasherTest, unreadable_elf) {
1758 int intercept_result;
1759 unique_fd output_fd;
1760 StartProcess([]() {
1761 TemporaryDir td;
1762 std::string tmp_so_name;
1763 if (!CopySharedLibrary(td.path, &tmp_so_name)) {
1764 _exit(1);
1765 }
1766 void* handle = dlopen(tmp_so_name.c_str(), RTLD_NOW);
1767 if (handle == nullptr) {
1768 _exit(1);
1769 }
1770 // Delete the original shared library so that we get the warning
1771 // about unreadable elf files.
1772 if (unlink(tmp_so_name.c_str()) == -1) {
1773 _exit(1);
1774 }
1775 void (*crash_func)() = reinterpret_cast<void (*)()>(dlsym(handle, "crash"));
1776 if (crash_func == nullptr) {
1777 _exit(1);
1778 }
1779 crash_func();
1780 });
1781
1782 StartIntercept(&output_fd);
1783 FinishCrasher();
1784 AssertDeath(SIGSEGV);
1785 FinishIntercept(&intercept_result);
1786
1787 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1788
1789 std::string result;
1790 ConsumeFd(std::move(output_fd), &result);
1791 ASSERT_MATCH(result, R"(NOTE: Function names and BuildId information is missing )");
1792}
1793
Josh Gao76e1e302021-01-26 15:53:11 -08001794TEST(tombstoned, proto) {
1795 const pid_t self = getpid();
1796 unique_fd tombstoned_socket, text_fd, proto_fd;
1797 ASSERT_TRUE(
1798 tombstoned_connect(self, &tombstoned_socket, &text_fd, &proto_fd, kDebuggerdTombstoneProto));
1799
1800 tombstoned_notify_completion(tombstoned_socket.get());
1801
1802 ASSERT_NE(-1, text_fd.get());
1803 ASSERT_NE(-1, proto_fd.get());
1804
1805 struct stat text_st;
1806 ASSERT_EQ(0, fstat(text_fd.get(), &text_st));
1807
1808 // Give tombstoned some time to link the files into place.
1809 std::this_thread::sleep_for(100ms);
1810
1811 // Find the tombstone.
Christopher Ferris35da2882021-02-17 15:39:06 -08001812 std::optional<std::string> tombstone_file;
1813 std::unique_ptr<DIR, decltype(&closedir)> dir_h(opendir("/data/tombstones"), closedir);
1814 ASSERT_TRUE(dir_h != nullptr);
1815 std::regex tombstone_re("tombstone_\\d+");
1816 dirent* entry;
1817 while ((entry = readdir(dir_h.get())) != nullptr) {
1818 if (!std::regex_match(entry->d_name, tombstone_re)) {
1819 continue;
1820 }
1821 std::string path = android::base::StringPrintf("/data/tombstones/%s", entry->d_name);
Josh Gao76e1e302021-01-26 15:53:11 -08001822
1823 struct stat st;
1824 if (TEMP_FAILURE_RETRY(stat(path.c_str(), &st)) != 0) {
1825 continue;
1826 }
1827
1828 if (st.st_dev == text_st.st_dev && st.st_ino == text_st.st_ino) {
Christopher Ferris35da2882021-02-17 15:39:06 -08001829 tombstone_file = path;
Josh Gao76e1e302021-01-26 15:53:11 -08001830 break;
1831 }
1832 }
1833
Christopher Ferris35da2882021-02-17 15:39:06 -08001834 ASSERT_TRUE(tombstone_file);
1835 std::string proto_path = tombstone_file.value() + ".pb";
Josh Gao76e1e302021-01-26 15:53:11 -08001836
1837 struct stat proto_fd_st;
1838 struct stat proto_file_st;
1839 ASSERT_EQ(0, fstat(proto_fd.get(), &proto_fd_st));
1840 ASSERT_EQ(0, stat(proto_path.c_str(), &proto_file_st));
1841
1842 ASSERT_EQ(proto_fd_st.st_dev, proto_file_st.st_dev);
1843 ASSERT_EQ(proto_fd_st.st_ino, proto_file_st.st_ino);
1844}
1845
1846TEST(tombstoned, proto_intercept) {
1847 const pid_t self = getpid();
1848 unique_fd intercept_fd, output_fd;
1849 InterceptStatus status;
1850
1851 tombstoned_intercept(self, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
1852 ASSERT_EQ(InterceptStatus::kRegistered, status);
1853
1854 unique_fd tombstoned_socket, text_fd, proto_fd;
1855 ASSERT_TRUE(
1856 tombstoned_connect(self, &tombstoned_socket, &text_fd, &proto_fd, kDebuggerdTombstoneProto));
1857 ASSERT_TRUE(android::base::WriteStringToFd("foo", text_fd.get()));
1858 tombstoned_notify_completion(tombstoned_socket.get());
1859
1860 text_fd.reset();
1861
1862 std::string output;
1863 ASSERT_TRUE(android::base::ReadFdToString(output_fd, &output));
1864 ASSERT_EQ("foo", output);
1865}
Christopher Ferrisa3e9a0b2021-07-29 12:38:07 -07001866
1867// Verify that when an intercept is present for the main thread, and the signal
1868// is received on a different thread, the intercept still works.
1869TEST_F(CrasherTest, intercept_for_main_thread_signal_on_side_thread) {
1870 StartProcess([]() {
1871 std::thread thread([]() {
1872 // Raise the signal on the side thread.
1873 raise_debugger_signal(kDebuggerdNativeBacktrace);
1874 });
1875 thread.join();
1876 _exit(0);
1877 });
1878
1879 unique_fd output_fd;
1880 StartIntercept(&output_fd, kDebuggerdNativeBacktrace);
1881 FinishCrasher();
1882 AssertDeath(0);
1883
1884 int intercept_result;
1885 FinishIntercept(&intercept_result);
1886 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1887
1888 std::string result;
1889 ConsumeFd(std::move(output_fd), &result);
1890 ASSERT_BACKTRACE_FRAME(result, "raise_debugger_signal");
1891}
Christopher Ferris7e4c2a82021-08-20 17:45:09 -07001892
1893static std::string format_pointer(uintptr_t ptr) {
1894#if defined(__LP64__)
1895 return android::base::StringPrintf("%08x'%08x", static_cast<uint32_t>(ptr >> 32),
1896 static_cast<uint32_t>(ptr & 0xffffffff));
1897#else
1898 return android::base::StringPrintf("%08x", static_cast<uint32_t>(ptr & 0xffffffff));
1899#endif
1900}
1901
1902static std::string format_pointer(void* ptr) {
1903 return format_pointer(reinterpret_cast<uintptr_t>(ptr));
1904}
1905
1906static std::string format_full_pointer(uintptr_t ptr) {
1907#if defined(__LP64__)
1908 return android::base::StringPrintf("%016" PRIx64, ptr);
1909#else
1910 return android::base::StringPrintf("%08x", ptr);
1911#endif
1912}
1913
1914static std::string format_full_pointer(void* ptr) {
1915 return format_full_pointer(reinterpret_cast<uintptr_t>(ptr));
1916}
1917
1918__attribute__((__noinline__)) int crash_call(uintptr_t ptr) {
1919 int* crash_ptr = reinterpret_cast<int*>(ptr);
1920 *crash_ptr = 1;
1921 return *crash_ptr;
1922}
1923
1924// Verify that a fault address before the first map is properly handled.
1925TEST_F(CrasherTest, fault_address_before_first_map) {
1926 StartProcess([]() {
1927 ASSERT_EQ(0, crash_call(0x1024));
1928 _exit(0);
1929 });
1930
1931 unique_fd output_fd;
1932 StartIntercept(&output_fd);
1933 FinishCrasher();
1934 AssertDeath(SIGSEGV);
1935
1936 int intercept_result;
1937 FinishIntercept(&intercept_result);
1938 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1939
1940 std::string result;
1941 ConsumeFd(std::move(output_fd), &result);
1942 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\), code 1 \(SEGV_MAPERR\), fault addr 0x1024)");
1943
1944 ASSERT_MATCH(result, R"(\nmemory map \(.*\):\n)");
1945
1946 std::string match_str = android::base::StringPrintf(
1947 R"(memory map .*:\n--->Fault address falls at %s before any mapped regions\n )",
1948 format_pointer(0x1024).c_str());
1949 ASSERT_MATCH(result, match_str);
1950}
1951
1952// Verify that a fault address after the last map is properly handled.
1953TEST_F(CrasherTest, fault_address_after_last_map) {
1954 uintptr_t crash_uptr = untag_address(UINTPTR_MAX - 15);
1955 StartProcess([crash_uptr]() {
1956 ASSERT_EQ(0, crash_call(crash_uptr));
1957 _exit(0);
1958 });
1959
1960 unique_fd output_fd;
1961 StartIntercept(&output_fd);
1962 FinishCrasher();
1963 AssertDeath(SIGSEGV);
1964
1965 int intercept_result;
1966 FinishIntercept(&intercept_result);
1967 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1968
1969 std::string result;
1970 ConsumeFd(std::move(output_fd), &result);
1971
1972 std::string match_str = R"(signal 11 \(SIGSEGV\), code 1 \(SEGV_MAPERR\), fault addr )";
1973 match_str += android::base::StringPrintf("0x%" PRIxPTR, crash_uptr);
1974 ASSERT_MATCH(result, match_str);
1975
1976 ASSERT_MATCH(result, R"(\nmemory map \(.*\): \(fault address prefixed with --->)\n)");
1977
1978 // Assumes that the open files section comes after the map section.
1979 // If that assumption changes, the regex below needs to change.
1980 match_str = android::base::StringPrintf(
1981 R"(\n--->Fault address falls at %s after any mapped regions\n\nopen files:)",
1982 format_pointer(crash_uptr).c_str());
1983 ASSERT_MATCH(result, match_str);
1984}
1985
1986// Verify that a fault address between maps is properly handled.
1987TEST_F(CrasherTest, fault_address_between_maps) {
1988 // Create a map before the fork so it will be present in the child.
1989 void* start_ptr =
1990 mmap(nullptr, 3 * getpagesize(), PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
1991 ASSERT_NE(MAP_FAILED, start_ptr);
1992 // Unmap the page in the middle.
1993 void* middle_ptr =
1994 reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(start_ptr) + getpagesize());
1995 ASSERT_EQ(0, munmap(middle_ptr, getpagesize()));
1996
1997 StartProcess([middle_ptr]() {
1998 ASSERT_EQ(0, crash_call(reinterpret_cast<uintptr_t>(middle_ptr)));
1999 _exit(0);
2000 });
2001
2002 // Unmap the two maps.
2003 ASSERT_EQ(0, munmap(start_ptr, getpagesize()));
2004 void* end_ptr =
2005 reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(start_ptr) + 2 * getpagesize());
2006 ASSERT_EQ(0, munmap(end_ptr, getpagesize()));
2007
2008 unique_fd output_fd;
2009 StartIntercept(&output_fd);
2010 FinishCrasher();
2011 AssertDeath(SIGSEGV);
2012
2013 int intercept_result;
2014 FinishIntercept(&intercept_result);
2015 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
2016
2017 std::string result;
2018 ConsumeFd(std::move(output_fd), &result);
2019
2020 std::string match_str = R"(signal 11 \(SIGSEGV\), code 1 \(SEGV_MAPERR\), fault addr )";
2021 match_str += android::base::StringPrintf("%p", middle_ptr);
2022 ASSERT_MATCH(result, match_str);
2023
2024 ASSERT_MATCH(result, R"(\nmemory map \(.*\): \(fault address prefixed with --->)\n)");
2025
2026 match_str = android::base::StringPrintf(
2027 R"( %s.*\n--->Fault address falls at %s between mapped regions\n %s)",
2028 format_pointer(start_ptr).c_str(), format_pointer(middle_ptr).c_str(),
2029 format_pointer(end_ptr).c_str());
2030 ASSERT_MATCH(result, match_str);
2031}
2032
2033// Verify that a fault address happens in the correct map.
2034TEST_F(CrasherTest, fault_address_in_map) {
2035 // Create a map before the fork so it will be present in the child.
2036 void* ptr = mmap(nullptr, getpagesize(), 0, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
2037 ASSERT_NE(MAP_FAILED, ptr);
2038
2039 StartProcess([ptr]() {
2040 ASSERT_EQ(0, crash_call(reinterpret_cast<uintptr_t>(ptr)));
2041 _exit(0);
2042 });
2043
2044 ASSERT_EQ(0, munmap(ptr, getpagesize()));
2045
2046 unique_fd output_fd;
2047 StartIntercept(&output_fd);
2048 FinishCrasher();
2049 AssertDeath(SIGSEGV);
2050
2051 int intercept_result;
2052 FinishIntercept(&intercept_result);
2053 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
2054
2055 std::string result;
2056 ConsumeFd(std::move(output_fd), &result);
2057
2058 std::string match_str = R"(signal 11 \(SIGSEGV\), code 2 \(SEGV_ACCERR\), fault addr )";
2059 match_str += android::base::StringPrintf("%p", ptr);
2060 ASSERT_MATCH(result, match_str);
2061
2062 ASSERT_MATCH(result, R"(\nmemory map \(.*\): \(fault address prefixed with --->)\n)");
2063
2064 match_str = android::base::StringPrintf(R"(\n--->%s.*\n)", format_pointer(ptr).c_str());
2065 ASSERT_MATCH(result, match_str);
2066}