blob: 24804d0466eb663d0ea80844fbe682660cbaca9c [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"
61#include "protocol.h"
62#include "tombstoned/tombstoned.h"
63#include "util.h"
64
Josh Gaocbe70cb2016-10-18 18:17:52 -070065using namespace std::chrono_literals;
Josh Gao5f87bbd2019-01-09 17:01:49 -080066
67using android::base::SendFileDescriptors;
Josh Gaocbe70cb2016-10-18 18:17:52 -070068using android::base::unique_fd;
Mitch Phillips78f06702021-06-01 14:35:43 -070069using ::testing::HasSubstr;
Josh Gaocbe70cb2016-10-18 18:17:52 -070070
71#if defined(__LP64__)
Josh Gaocbe70cb2016-10-18 18:17:52 -070072#define ARCH_SUFFIX "64"
73#else
Josh Gaocbe70cb2016-10-18 18:17:52 -070074#define ARCH_SUFFIX ""
75#endif
76
Elliott Hughese4781d52021-03-17 09:15:15 -070077constexpr char kWaitForDebuggerKey[] = "debug.debuggerd.wait_for_debugger";
Josh Gaocbe70cb2016-10-18 18:17:52 -070078
79#define TIMEOUT(seconds, expr) \
80 [&]() { \
81 struct sigaction old_sigaction; \
82 struct sigaction new_sigaction = {}; \
83 new_sigaction.sa_handler = [](int) {}; \
84 if (sigaction(SIGALRM, &new_sigaction, &new_sigaction) != 0) { \
85 err(1, "sigaction failed"); \
86 } \
87 alarm(seconds); \
88 auto value = expr; \
89 int saved_errno = errno; \
90 if (sigaction(SIGALRM, &old_sigaction, nullptr) != 0) { \
91 err(1, "sigaction failed"); \
92 } \
93 alarm(0); \
94 errno = saved_errno; \
95 return value; \
96 }()
97
Chih-Hung Hsieh3249b3a2018-05-11 16:01:21 -070098// Backtrace frame dump could contain:
99// #01 pc 0001cded /data/tmp/debuggerd_test32 (raise_debugger_signal+80)
100// or
101// #01 pc 00022a09 /data/tmp/debuggerd_test32 (offset 0x12000) (raise_debugger_signal+80)
Josh Gaoe04ca272018-01-16 15:38:17 -0800102#define ASSERT_BACKTRACE_FRAME(result, frame_name) \
Chih-Hung Hsieh3249b3a2018-05-11 16:01:21 -0700103 ASSERT_MATCH(result, \
104 R"(#\d\d pc [0-9a-f]+\s+ \S+ (\(offset 0x[0-9a-f]+\) )?\()" frame_name R"(\+)");
Jaesung Chung58778e12017-06-15 18:20:34 +0900105
Mitch Phillips7168a212021-03-09 16:53:23 -0800106// Enable GWP-ASan at the start of this process. GWP-ASan is enabled using
107// process sampling, so we need to ensure we force GWP-ASan on.
108__attribute__((constructor)) static void enable_gwp_asan() {
109 bool force = true;
110 android_mallopt(M_INITIALIZE_GWP_ASAN, &force, sizeof(force));
111}
112
Narayan Kamatha73df602017-05-24 15:07:25 +0100113static void tombstoned_intercept(pid_t target_pid, unique_fd* intercept_fd, unique_fd* output_fd,
Narayan Kamathca5e9082017-06-02 15:42:06 +0100114 InterceptStatus* status, DebuggerdDumpType intercept_type) {
Josh Gao460b3362017-03-30 16:40:47 -0700115 intercept_fd->reset(socket_local_client(kTombstonedInterceptSocketName,
116 ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_SEQPACKET));
117 if (intercept_fd->get() == -1) {
118 FAIL() << "failed to contact tombstoned: " << strerror(errno);
119 }
120
Nick Desaulniers67d52aa2019-10-07 23:28:15 -0700121 InterceptRequest req = {
122 .dump_type = intercept_type,
123 .pid = target_pid,
124 };
Josh Gao460b3362017-03-30 16:40:47 -0700125
126 unique_fd output_pipe_write;
127 if (!Pipe(output_fd, &output_pipe_write)) {
128 FAIL() << "failed to create output pipe: " << strerror(errno);
129 }
130
131 std::string pipe_size_str;
132 int pipe_buffer_size;
133 if (!android::base::ReadFileToString("/proc/sys/fs/pipe-max-size", &pipe_size_str)) {
134 FAIL() << "failed to read /proc/sys/fs/pipe-max-size: " << strerror(errno);
135 }
136
137 pipe_size_str = android::base::Trim(pipe_size_str);
138
139 if (!android::base::ParseInt(pipe_size_str.c_str(), &pipe_buffer_size, 0)) {
140 FAIL() << "failed to parse pipe max size";
141 }
142
143 if (fcntl(output_fd->get(), F_SETPIPE_SZ, pipe_buffer_size) != pipe_buffer_size) {
144 FAIL() << "failed to set pipe size: " << strerror(errno);
145 }
146
Josh Gao5675f3c2017-06-01 12:19:53 -0700147 ASSERT_GE(pipe_buffer_size, 1024 * 1024);
148
Josh Gao5f87bbd2019-01-09 17:01:49 -0800149 ssize_t rc = SendFileDescriptors(intercept_fd->get(), &req, sizeof(req), output_pipe_write.get());
150 output_pipe_write.reset();
151 if (rc != sizeof(req)) {
Josh Gao460b3362017-03-30 16:40:47 -0700152 FAIL() << "failed to send output fd to tombstoned: " << strerror(errno);
153 }
154
155 InterceptResponse response;
Josh Gao5f87bbd2019-01-09 17:01:49 -0800156 rc = TEMP_FAILURE_RETRY(read(intercept_fd->get(), &response, sizeof(response)));
Josh Gao460b3362017-03-30 16:40:47 -0700157 if (rc == -1) {
158 FAIL() << "failed to read response from tombstoned: " << strerror(errno);
159 } else if (rc == 0) {
160 FAIL() << "failed to read response from tombstoned (EOF)";
161 } else if (rc != sizeof(response)) {
162 FAIL() << "received packet of unexpected length from tombstoned: expected " << sizeof(response)
163 << ", received " << rc;
164 }
165
Narayan Kamathca5e9082017-06-02 15:42:06 +0100166 *status = response.status;
Josh Gao460b3362017-03-30 16:40:47 -0700167}
168
Josh Gaocbe70cb2016-10-18 18:17:52 -0700169class CrasherTest : public ::testing::Test {
170 public:
171 pid_t crasher_pid = -1;
Elliott Hughese4781d52021-03-17 09:15:15 -0700172 bool previous_wait_for_debugger;
Josh Gaocbe70cb2016-10-18 18:17:52 -0700173 unique_fd crasher_pipe;
174 unique_fd intercept_fd;
175
176 CrasherTest();
177 ~CrasherTest();
178
Narayan Kamatha73df602017-05-24 15:07:25 +0100179 void StartIntercept(unique_fd* output_fd, DebuggerdDumpType intercept_type = kDebuggerdTombstone);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700180
181 // Returns -1 if we fail to read a response from tombstoned, otherwise the received return code.
182 void FinishIntercept(int* result);
183
Josh Gao2e7b8e22017-05-04 17:12:57 -0700184 void StartProcess(std::function<void()> function, std::function<pid_t()> forker = fork);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700185 void StartCrasher(const std::string& crash_type);
186 void FinishCrasher();
187 void AssertDeath(int signo);
Peter Collingbourne10e428d2020-07-17 14:49:31 -0700188
189 static void Trap(void* ptr);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700190};
191
192CrasherTest::CrasherTest() {
Elliott Hughese4781d52021-03-17 09:15:15 -0700193 previous_wait_for_debugger = android::base::GetBoolProperty(kWaitForDebuggerKey, false);
194 android::base::SetProperty(kWaitForDebuggerKey, "0");
195
196 // Clear the old property too, just in case someone's been using it
197 // on this device. (We only document the new name, but we still support
198 // the old name so we don't break anyone's existing setups.)
199 android::base::SetProperty("debug.debuggerd.wait_for_gdb", "0");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700200}
201
202CrasherTest::~CrasherTest() {
203 if (crasher_pid != -1) {
204 kill(crasher_pid, SIGKILL);
205 int status;
Christopher Ferris172b0a02019-09-18 17:48:30 -0700206 TEMP_FAILURE_RETRY(waitpid(crasher_pid, &status, WUNTRACED));
Josh Gaocbe70cb2016-10-18 18:17:52 -0700207 }
208
Elliott Hughese4781d52021-03-17 09:15:15 -0700209 android::base::SetProperty(kWaitForDebuggerKey, previous_wait_for_debugger ? "1" : "0");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700210}
211
Narayan Kamatha73df602017-05-24 15:07:25 +0100212void CrasherTest::StartIntercept(unique_fd* output_fd, DebuggerdDumpType intercept_type) {
Josh Gaocbe70cb2016-10-18 18:17:52 -0700213 if (crasher_pid == -1) {
214 FAIL() << "crasher hasn't been started";
215 }
216
Narayan Kamathca5e9082017-06-02 15:42:06 +0100217 InterceptStatus status;
218 tombstoned_intercept(crasher_pid, &this->intercept_fd, output_fd, &status, intercept_type);
219 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700220}
221
222void CrasherTest::FinishIntercept(int* result) {
223 InterceptResponse response;
224
Christopher Ferris11555f02019-09-20 14:18:55 -0700225 ssize_t rc = TIMEOUT(30, read(intercept_fd.get(), &response, sizeof(response)));
Josh Gaocbe70cb2016-10-18 18:17:52 -0700226 if (rc == -1) {
227 FAIL() << "failed to read response from tombstoned: " << strerror(errno);
228 } else if (rc == 0) {
229 *result = -1;
230 } else if (rc != sizeof(response)) {
231 FAIL() << "received packet of unexpected length from tombstoned: expected " << sizeof(response)
232 << ", received " << rc;
233 } else {
Josh Gao460b3362017-03-30 16:40:47 -0700234 *result = response.status == InterceptStatus::kStarted ? 1 : 0;
Josh Gaocbe70cb2016-10-18 18:17:52 -0700235 }
236}
237
Josh Gao2e7b8e22017-05-04 17:12:57 -0700238void CrasherTest::StartProcess(std::function<void()> function, std::function<pid_t()> forker) {
Josh Gaofca7ca32017-01-23 12:05:35 -0800239 unique_fd read_pipe;
Josh Gaocbe70cb2016-10-18 18:17:52 -0700240 unique_fd crasher_read_pipe;
241 if (!Pipe(&crasher_read_pipe, &crasher_pipe)) {
242 FAIL() << "failed to create pipe: " << strerror(errno);
243 }
244
Josh Gao2e7b8e22017-05-04 17:12:57 -0700245 crasher_pid = forker();
Josh Gaocbe70cb2016-10-18 18:17:52 -0700246 if (crasher_pid == -1) {
247 FAIL() << "fork failed: " << strerror(errno);
248 } else if (crasher_pid == 0) {
Josh Gao502cfd22017-02-17 01:39:15 -0800249 char dummy;
250 crasher_pipe.reset();
251 TEMP_FAILURE_RETRY(read(crasher_read_pipe.get(), &dummy, 1));
Josh Gaofca7ca32017-01-23 12:05:35 -0800252 function();
253 _exit(0);
254 }
255}
256
Josh Gaocbe70cb2016-10-18 18:17:52 -0700257void CrasherTest::FinishCrasher() {
258 if (crasher_pipe == -1) {
259 FAIL() << "crasher pipe uninitialized";
260 }
261
Christopher Ferris172b0a02019-09-18 17:48:30 -0700262 ssize_t rc = TEMP_FAILURE_RETRY(write(crasher_pipe.get(), "\n", 1));
Josh Gaocbe70cb2016-10-18 18:17:52 -0700263 if (rc == -1) {
264 FAIL() << "failed to write to crasher pipe: " << strerror(errno);
265 } else if (rc == 0) {
266 FAIL() << "crasher pipe was closed";
267 }
268}
269
270void CrasherTest::AssertDeath(int signo) {
271 int status;
Christopher Ferris11555f02019-09-20 14:18:55 -0700272 pid_t pid = TIMEOUT(30, waitpid(crasher_pid, &status, 0));
Josh Gaocbe70cb2016-10-18 18:17:52 -0700273 if (pid != crasher_pid) {
Christopher Ferrisafc0ff72019-06-26 15:08:51 -0700274 printf("failed to wait for crasher (expected pid %d, return value %d): %s\n", crasher_pid, pid,
275 strerror(errno));
Josh Gao2b2ae0c2017-08-21 14:31:17 -0700276 sleep(100);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700277 FAIL() << "failed to wait for crasher: " << strerror(errno);
278 }
279
Josh Gaoe06f2a42017-04-27 16:50:38 -0700280 if (signo == 0) {
Christopher Ferris67022562021-04-16 13:30:32 -0700281 ASSERT_TRUE(WIFEXITED(status)) << "Terminated due to unexpected signal " << WTERMSIG(status);
Josh Gaoe06f2a42017-04-27 16:50:38 -0700282 ASSERT_EQ(0, WEXITSTATUS(signo));
283 } else {
284 ASSERT_FALSE(WIFEXITED(status));
285 ASSERT_TRUE(WIFSIGNALED(status)) << "crasher didn't terminate via a signal";
286 ASSERT_EQ(signo, WTERMSIG(status));
Josh Gaocbe70cb2016-10-18 18:17:52 -0700287 }
Josh Gaocbe70cb2016-10-18 18:17:52 -0700288 crasher_pid = -1;
289}
290
291static void ConsumeFd(unique_fd fd, std::string* output) {
292 constexpr size_t read_length = PAGE_SIZE;
293 std::string result;
294
295 while (true) {
296 size_t offset = result.size();
297 result.resize(result.size() + PAGE_SIZE);
298 ssize_t rc = TEMP_FAILURE_RETRY(read(fd.get(), &result[offset], read_length));
299 if (rc == -1) {
300 FAIL() << "read failed: " << strerror(errno);
301 } else if (rc == 0) {
302 result.resize(result.size() - PAGE_SIZE);
303 break;
304 }
305
306 result.resize(result.size() - PAGE_SIZE + rc);
307 }
308
309 *output = std::move(result);
310}
311
Mitch Phillips78f06702021-06-01 14:35:43 -0700312class LogcatCollector {
313 public:
314 LogcatCollector() { system("logcat -c"); }
315
316 void Collect(std::string* output) {
317 FILE* cmd_stdout = popen("logcat -d '*:S DEBUG'", "r");
318 ASSERT_NE(cmd_stdout, nullptr);
319 unique_fd tmp_fd(TEMP_FAILURE_RETRY(dup(fileno(cmd_stdout))));
320 ConsumeFd(std::move(tmp_fd), output);
321 pclose(cmd_stdout);
322 }
323};
324
Josh Gaocbe70cb2016-10-18 18:17:52 -0700325TEST_F(CrasherTest, smoke) {
326 int intercept_result;
327 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800328 StartProcess([]() {
329 *reinterpret_cast<volatile char*>(0xdead) = '1';
330 });
331
Josh Gaocbe70cb2016-10-18 18:17:52 -0700332 StartIntercept(&output_fd);
333 FinishCrasher();
334 AssertDeath(SIGSEGV);
335 FinishIntercept(&intercept_result);
336
337 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
338
339 std::string result;
340 ConsumeFd(std::move(output_fd), &result);
341 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\), code 1 \(SEGV_MAPERR\), fault addr 0xdead)");
Peter Collingbourne864f15d2020-09-14 20:27:36 -0700342
343 if (mte_supported()) {
344 // Test that the default TAGGED_ADDR_CTRL value is set.
Peter Collingbourne939d0742021-02-02 19:00:45 -0800345 ASSERT_MATCH(result, R"(tagged_addr_ctrl: 000000000007fff3)");
Peter Collingbourne864f15d2020-09-14 20:27:36 -0700346 }
Josh Gaocbe70cb2016-10-18 18:17:52 -0700347}
348
Peter Collingbournef03af882020-03-20 18:09:00 -0700349TEST_F(CrasherTest, tagged_fault_addr) {
350#if !defined(__aarch64__)
351 GTEST_SKIP() << "Requires aarch64";
352#endif
353 int intercept_result;
354 unique_fd output_fd;
355 StartProcess([]() {
356 *reinterpret_cast<volatile char*>(0x100000000000dead) = '1';
357 });
358
359 StartIntercept(&output_fd);
360 FinishCrasher();
361 AssertDeath(SIGSEGV);
362 FinishIntercept(&intercept_result);
363
364 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
365
366 std::string result;
367 ConsumeFd(std::move(output_fd), &result);
368
369 // The address can either be tagged (new kernels) or untagged (old kernels).
370 ASSERT_MATCH(
371 result,
372 R"(signal 11 \(SIGSEGV\), code 1 \(SEGV_MAPERR\), fault addr (0x100000000000dead|0xdead))");
373}
374
Peter Collingbourne10e428d2020-07-17 14:49:31 -0700375// Marked as weak to prevent the compiler from removing the malloc in the caller. In theory, the
376// compiler could still clobber the argument register before trapping, but that's unlikely.
377__attribute__((weak)) void CrasherTest::Trap(void* ptr ATTRIBUTE_UNUSED) {
378 __builtin_trap();
379}
380
381TEST_F(CrasherTest, heap_addr_in_register) {
382#if defined(__i386__)
383 GTEST_SKIP() << "architecture does not pass arguments in registers";
384#endif
385 int intercept_result;
386 unique_fd output_fd;
387 StartProcess([]() {
388 // Crash with a heap pointer in the first argument register.
389 Trap(malloc(1));
390 });
391
392 StartIntercept(&output_fd);
393 FinishCrasher();
394 int status;
395 ASSERT_EQ(crasher_pid, TIMEOUT(30, waitpid(crasher_pid, &status, 0)));
396 ASSERT_TRUE(WIFSIGNALED(status)) << "crasher didn't terminate via a signal";
397 // Don't test the signal number because different architectures use different signals for
398 // __builtin_trap().
399 FinishIntercept(&intercept_result);
400
401 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
402
403 std::string result;
404 ConsumeFd(std::move(output_fd), &result);
405
406#if defined(__aarch64__)
Peter Collingbourne0ea08c22021-02-05 14:59:08 -0800407 ASSERT_MATCH(result, "memory near x0 \\(\\[anon:");
Peter Collingbourne10e428d2020-07-17 14:49:31 -0700408#elif defined(__arm__)
Peter Collingbourne0ea08c22021-02-05 14:59:08 -0800409 ASSERT_MATCH(result, "memory near r0 \\(\\[anon:");
Peter Collingbourne10e428d2020-07-17 14:49:31 -0700410#elif defined(__x86_64__)
Peter Collingbourne0ea08c22021-02-05 14:59:08 -0800411 ASSERT_MATCH(result, "memory near rdi \\(\\[anon:");
Peter Collingbourne10e428d2020-07-17 14:49:31 -0700412#else
413 ASSERT_TRUE(false) << "unsupported architecture";
414#endif
415}
416
Peter Collingbournecd278072020-12-21 14:08:38 -0800417#if defined(__aarch64__)
Peter Collingbournef8622522020-04-07 14:07:32 -0700418static void SetTagCheckingLevelSync() {
Elliott Hughes03b283a2021-01-15 11:34:26 -0800419 if (mallopt(M_BIONIC_SET_HEAP_TAGGING_LEVEL, M_HEAP_TAGGING_LEVEL_SYNC) == 0) {
Peter Collingbournef8622522020-04-07 14:07:32 -0700420 abort();
421 }
422}
423#endif
424
Mitch Phillips7168a212021-03-09 16:53:23 -0800425// Number of iterations required to reliably guarantee a GWP-ASan crash.
426// GWP-ASan's sample rate is not truly nondeterministic, it initialises a
427// thread-local counter at 2*SampleRate, and decrements on each malloc(). Once
428// the counter reaches zero, we provide a sampled allocation. Then, double that
429// figure to allow for left/right allocation alignment, as this is done randomly
430// without bias.
431#define GWP_ASAN_ITERATIONS_TO_ENSURE_CRASH (0x20000)
432
433struct GwpAsanTestParameters {
434 size_t alloc_size;
435 bool free_before_access;
436 int access_offset;
437 std::string cause_needle; // Needle to be found in the "Cause: [GWP-ASan]" line.
438};
439
440struct GwpAsanCrasherTest : CrasherTest, testing::WithParamInterface<GwpAsanTestParameters> {};
441
442GwpAsanTestParameters gwp_asan_tests[] = {
443 {/* alloc_size */ 7, /* free_before_access */ true, /* access_offset */ 0, "Use After Free, 0 bytes into a 7-byte allocation"},
444 {/* alloc_size */ 7, /* free_before_access */ true, /* access_offset */ 1, "Use After Free, 1 byte into a 7-byte allocation"},
445 {/* alloc_size */ 7, /* free_before_access */ false, /* access_offset */ 16, "Buffer Overflow, 9 bytes right of a 7-byte allocation"},
446 {/* alloc_size */ 16, /* free_before_access */ false, /* access_offset */ -1, "Buffer Underflow, 1 byte left of a 16-byte allocation"},
447};
448
449INSTANTIATE_TEST_SUITE_P(GwpAsanTests, GwpAsanCrasherTest, testing::ValuesIn(gwp_asan_tests));
450
451TEST_P(GwpAsanCrasherTest, gwp_asan_uaf) {
452 if (mte_supported()) {
453 // Skip this test on MTE hardware, as MTE will reliably catch these errors
454 // instead of GWP-ASan.
455 GTEST_SKIP() << "Skipped on MTE.";
456 }
457
458 GwpAsanTestParameters params = GetParam();
Mitch Phillips78f06702021-06-01 14:35:43 -0700459 LogcatCollector logcat_collector;
Mitch Phillips7168a212021-03-09 16:53:23 -0800460
461 int intercept_result;
462 unique_fd output_fd;
463 StartProcess([&params]() {
464 for (unsigned i = 0; i < GWP_ASAN_ITERATIONS_TO_ENSURE_CRASH; ++i) {
465 volatile char* p = reinterpret_cast<volatile char*>(malloc(params.alloc_size));
466 if (params.free_before_access) free(static_cast<void*>(const_cast<char*>(p)));
467 p[params.access_offset] = 42;
468 if (!params.free_before_access) free(static_cast<void*>(const_cast<char*>(p)));
469 }
470 });
471
472 StartIntercept(&output_fd);
473 FinishCrasher();
474 AssertDeath(SIGSEGV);
475 FinishIntercept(&intercept_result);
476
477 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
478
Mitch Phillips78f06702021-06-01 14:35:43 -0700479 std::vector<std::string> log_sources(2);
480 ConsumeFd(std::move(output_fd), &log_sources[0]);
481 logcat_collector.Collect(&log_sources[1]);
Mitch Phillips7168a212021-03-09 16:53:23 -0800482
Mitch Phillips78f06702021-06-01 14:35:43 -0700483 for (const auto& result : log_sources) {
484 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\), code 2 \(SEGV_ACCERR\))");
485 ASSERT_MATCH(result, R"(Cause: \[GWP-ASan\]: )" + params.cause_needle);
486 if (params.free_before_access) {
487 ASSERT_MATCH(result, R"(deallocated by thread .*\n.*#00 pc)");
488 }
489 ASSERT_MATCH(result, R"((^|\s)allocated by thread .*\n.*#00 pc)");
Mitch Phillips7168a212021-03-09 16:53:23 -0800490 }
Mitch Phillips7168a212021-03-09 16:53:23 -0800491}
492
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800493struct SizeParamCrasherTest : CrasherTest, testing::WithParamInterface<size_t> {};
494
Peter Collingbourneaa544792021-05-13 13:53:37 -0700495INSTANTIATE_TEST_SUITE_P(Sizes, SizeParamCrasherTest, testing::Values(0, 16, 131072));
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800496
497TEST_P(SizeParamCrasherTest, mte_uaf) {
Peter Collingbournecd278072020-12-21 14:08:38 -0800498#if defined(__aarch64__)
Peter Collingbournef8622522020-04-07 14:07:32 -0700499 if (!mte_supported()) {
500 GTEST_SKIP() << "Requires MTE";
501 }
502
Peter Collingbourneaa544792021-05-13 13:53:37 -0700503 // Any UAF on a zero-sized allocation will be out-of-bounds so it won't be reported.
504 if (GetParam() == 0) {
505 return;
506 }
507
Mitch Phillips78f06702021-06-01 14:35:43 -0700508 LogcatCollector logcat_collector;
509
Peter Collingbournef8622522020-04-07 14:07:32 -0700510 int intercept_result;
511 unique_fd output_fd;
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800512 StartProcess([&]() {
Peter Collingbournef8622522020-04-07 14:07:32 -0700513 SetTagCheckingLevelSync();
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800514 volatile int* p = (volatile int*)malloc(GetParam());
Peter Collingbournef8622522020-04-07 14:07:32 -0700515 free((void *)p);
516 p[0] = 42;
517 });
518
519 StartIntercept(&output_fd);
520 FinishCrasher();
521 AssertDeath(SIGSEGV);
522 FinishIntercept(&intercept_result);
523
524 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
525
Mitch Phillips78f06702021-06-01 14:35:43 -0700526 std::vector<std::string> log_sources(2);
527 ConsumeFd(std::move(output_fd), &log_sources[0]);
528 logcat_collector.Collect(&log_sources[1]);
Peter Collingbournef8622522020-04-07 14:07:32 -0700529
Mitch Phillips78f06702021-06-01 14:35:43 -0700530 for (const auto& result : log_sources) {
531 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\))");
532 ASSERT_MATCH(result, R"(Cause: \[MTE\]: Use After Free, 0 bytes into a )" +
533 std::to_string(GetParam()) + R"(-byte allocation)");
534 ASSERT_MATCH(result, R"(deallocated by thread .*?\n.*#00 pc)");
535 ASSERT_MATCH(result, R"((^|\s)allocated by thread .*?\n.*#00 pc)");
536 }
Peter Collingbournef8622522020-04-07 14:07:32 -0700537#else
Peter Collingbournecd278072020-12-21 14:08:38 -0800538 GTEST_SKIP() << "Requires aarch64";
Peter Collingbournef8622522020-04-07 14:07:32 -0700539#endif
540}
541
Peter Collingbournedc476342021-05-12 15:56:43 -0700542TEST_P(SizeParamCrasherTest, mte_oob_uaf) {
543#if defined(__aarch64__)
544 if (!mte_supported()) {
545 GTEST_SKIP() << "Requires MTE";
546 }
547
548 int intercept_result;
549 unique_fd output_fd;
550 StartProcess([&]() {
551 SetTagCheckingLevelSync();
552 volatile int* p = (volatile int*)malloc(GetParam());
553 free((void *)p);
554 p[-1] = 42;
555 });
556
557 StartIntercept(&output_fd);
558 FinishCrasher();
559 AssertDeath(SIGSEGV);
560 FinishIntercept(&intercept_result);
561
562 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
563
564 std::string result;
565 ConsumeFd(std::move(output_fd), &result);
566
567 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\))");
568 ASSERT_NOT_MATCH(result, R"(Cause: \[MTE\]: Use After Free, 4 bytes left)");
569#else
570 GTEST_SKIP() << "Requires aarch64";
571#endif
572}
573
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800574TEST_P(SizeParamCrasherTest, mte_overflow) {
Peter Collingbournecd278072020-12-21 14:08:38 -0800575#if defined(__aarch64__)
Peter Collingbournef8622522020-04-07 14:07:32 -0700576 if (!mte_supported()) {
577 GTEST_SKIP() << "Requires MTE";
578 }
579
Mitch Phillips78f06702021-06-01 14:35:43 -0700580 LogcatCollector logcat_collector;
Peter Collingbournef8622522020-04-07 14:07:32 -0700581 int intercept_result;
582 unique_fd output_fd;
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800583 StartProcess([&]() {
Peter Collingbournef8622522020-04-07 14:07:32 -0700584 SetTagCheckingLevelSync();
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800585 volatile char* p = (volatile char*)malloc(GetParam());
586 p[GetParam()] = 42;
Peter Collingbournef8622522020-04-07 14:07:32 -0700587 });
588
589 StartIntercept(&output_fd);
590 FinishCrasher();
591 AssertDeath(SIGSEGV);
592 FinishIntercept(&intercept_result);
593
594 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
595
Mitch Phillips78f06702021-06-01 14:35:43 -0700596 std::vector<std::string> log_sources(2);
597 ConsumeFd(std::move(output_fd), &log_sources[0]);
598 logcat_collector.Collect(&log_sources[1]);
Peter Collingbournef8622522020-04-07 14:07:32 -0700599
Mitch Phillips78f06702021-06-01 14:35:43 -0700600 for (const auto& result : log_sources) {
601 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\))");
602 ASSERT_MATCH(result, R"(Cause: \[MTE\]: Buffer Overflow, 0 bytes right of a )" +
603 std::to_string(GetParam()) + R"(-byte allocation)");
604 ASSERT_MATCH(result, R"((^|\s)allocated by thread .*?\n.*#00 pc)");
605 }
Peter Collingbournef8622522020-04-07 14:07:32 -0700606#else
Peter Collingbournecd278072020-12-21 14:08:38 -0800607 GTEST_SKIP() << "Requires aarch64";
Peter Collingbournef8622522020-04-07 14:07:32 -0700608#endif
609}
610
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800611TEST_P(SizeParamCrasherTest, mte_underflow) {
Peter Collingbournecd278072020-12-21 14:08:38 -0800612#if defined(__aarch64__)
Peter Collingbournef8622522020-04-07 14:07:32 -0700613 if (!mte_supported()) {
614 GTEST_SKIP() << "Requires MTE";
615 }
616
617 int intercept_result;
618 unique_fd output_fd;
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800619 StartProcess([&]() {
Peter Collingbournef8622522020-04-07 14:07:32 -0700620 SetTagCheckingLevelSync();
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800621 volatile int* p = (volatile int*)malloc(GetParam());
Peter Collingbournef8622522020-04-07 14:07:32 -0700622 p[-1] = 42;
623 });
624
625 StartIntercept(&output_fd);
626 FinishCrasher();
627 AssertDeath(SIGSEGV);
628 FinishIntercept(&intercept_result);
629
630 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
631
632 std::string result;
633 ConsumeFd(std::move(output_fd), &result);
634
635 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\), code 9 \(SEGV_MTESERR\))");
Peter Collingbournebb4b49c2021-01-06 21:02:19 -0800636 ASSERT_MATCH(result, R"(Cause: \[MTE\]: Buffer Underflow, 4 bytes left of a )" +
Peter Collingbourne1a1f7d72021-03-08 16:53:54 -0800637 std::to_string(GetParam()) + R"(-byte allocation)");
Mitch Phillips78f06702021-06-01 14:35:43 -0700638 ASSERT_MATCH(result, R"((^|\s)allocated by thread .*
Peter Collingbournebbe69052020-05-08 10:11:19 -0700639 #00 pc)");
Peter Collingbournef8622522020-04-07 14:07:32 -0700640#else
Peter Collingbournecd278072020-12-21 14:08:38 -0800641 GTEST_SKIP() << "Requires aarch64";
Peter Collingbournef8622522020-04-07 14:07:32 -0700642#endif
643}
644
645TEST_F(CrasherTest, mte_multiple_causes) {
Peter Collingbournecd278072020-12-21 14:08:38 -0800646#if defined(__aarch64__)
Peter Collingbournef8622522020-04-07 14:07:32 -0700647 if (!mte_supported()) {
648 GTEST_SKIP() << "Requires MTE";
649 }
650
Mitch Phillips78f06702021-06-01 14:35:43 -0700651 LogcatCollector logcat_collector;
652
Peter Collingbournef8622522020-04-07 14:07:32 -0700653 int intercept_result;
654 unique_fd output_fd;
655 StartProcess([]() {
656 SetTagCheckingLevelSync();
657
658 // Make two allocations with the same tag and close to one another. Check for both properties
659 // with a bounds check -- this relies on the fact that only if the allocations have the same tag
660 // would they be measured as closer than 128 bytes to each other. Otherwise they would be about
661 // (some non-zero value << 56) apart.
662 //
663 // The out-of-bounds access will be considered either an overflow of one or an underflow of the
664 // other.
665 std::set<uintptr_t> allocs;
666 for (int i = 0; i != 4096; ++i) {
667 uintptr_t alloc = reinterpret_cast<uintptr_t>(malloc(16));
668 auto it = allocs.insert(alloc).first;
669 if (it != allocs.begin() && *std::prev(it) + 128 > alloc) {
670 *reinterpret_cast<int*>(*std::prev(it) + 16) = 42;
671 }
672 if (std::next(it) != allocs.end() && alloc + 128 > *std::next(it)) {
673 *reinterpret_cast<int*>(alloc + 16) = 42;
674 }
675 }
676 });
677
678 StartIntercept(&output_fd);
679 FinishCrasher();
680 AssertDeath(SIGSEGV);
681 FinishIntercept(&intercept_result);
682
683 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
684
Mitch Phillips78f06702021-06-01 14:35:43 -0700685 std::vector<std::string> log_sources(2);
686 ConsumeFd(std::move(output_fd), &log_sources[0]);
687 logcat_collector.Collect(&log_sources[1]);
Peter Collingbournef8622522020-04-07 14:07:32 -0700688
Mitch Phillips78f06702021-06-01 14:35:43 -0700689 for (const auto& result : log_sources) {
690 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\))");
691 ASSERT_THAT(result, HasSubstr("Note: multiple potential causes for this crash were detected, "
692 "listing them in decreasing order of probability."));
693 // Adjacent untracked allocations may cause us to see the wrong underflow here (or only
694 // overflows), so we can't match explicitly for an underflow message.
695 ASSERT_MATCH(result,
696 R"(Cause: \[MTE\]: Buffer Overflow, 0 bytes right of a 16-byte allocation)");
697 // Ensure there's at least two allocation traces (one for each cause).
698 ASSERT_MATCH(
699 result,
700 R"((^|\s)allocated by thread .*?\n.*#00 pc(.|\n)*?(^|\s)allocated by thread .*?\n.*#00 pc)");
701 }
Peter Collingbournef8622522020-04-07 14:07:32 -0700702#else
Peter Collingbournecd278072020-12-21 14:08:38 -0800703 GTEST_SKIP() << "Requires aarch64";
Peter Collingbournef8622522020-04-07 14:07:32 -0700704#endif
705}
706
Peter Collingbournecd278072020-12-21 14:08:38 -0800707#if defined(__aarch64__)
Peter Collingbournefe8997a2020-07-20 15:08:52 -0700708static uintptr_t CreateTagMapping() {
709 uintptr_t mapping =
710 reinterpret_cast<uintptr_t>(mmap(nullptr, getpagesize(), PROT_READ | PROT_WRITE | PROT_MTE,
711 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0));
712 if (reinterpret_cast<void*>(mapping) == MAP_FAILED) {
713 return 0;
714 }
715 __asm__ __volatile__(".arch_extension mte; stg %0, [%0]"
716 :
717 : "r"(mapping + (1ULL << 56))
718 : "memory");
719 return mapping;
720}
721#endif
722
723TEST_F(CrasherTest, mte_tag_dump) {
Peter Collingbournecd278072020-12-21 14:08:38 -0800724#if defined(__aarch64__)
Peter Collingbournefe8997a2020-07-20 15:08:52 -0700725 if (!mte_supported()) {
726 GTEST_SKIP() << "Requires MTE";
727 }
728
729 int intercept_result;
730 unique_fd output_fd;
731 StartProcess([&]() {
732 SetTagCheckingLevelSync();
733 Trap(reinterpret_cast<void *>(CreateTagMapping()));
734 });
735
736 StartIntercept(&output_fd);
737 FinishCrasher();
738 AssertDeath(SIGTRAP);
739 FinishIntercept(&intercept_result);
740
741 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
742
743 std::string result;
744 ConsumeFd(std::move(output_fd), &result);
745
746 ASSERT_MATCH(result, R"(memory near x0:
747.*
748.*
749 01.............0 0000000000000000 0000000000000000 ................
750 00.............0)");
751#else
Peter Collingbournecd278072020-12-21 14:08:38 -0800752 GTEST_SKIP() << "Requires aarch64";
Peter Collingbournefe8997a2020-07-20 15:08:52 -0700753#endif
754}
755
Josh Gaocdea7502017-11-01 15:00:40 -0700756TEST_F(CrasherTest, LD_PRELOAD) {
757 int intercept_result;
758 unique_fd output_fd;
759 StartProcess([]() {
760 setenv("LD_PRELOAD", "nonexistent.so", 1);
761 *reinterpret_cast<volatile char*>(0xdead) = '1';
762 });
763
764 StartIntercept(&output_fd);
765 FinishCrasher();
766 AssertDeath(SIGSEGV);
767 FinishIntercept(&intercept_result);
768
769 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
770
771 std::string result;
772 ConsumeFd(std::move(output_fd), &result);
773 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\), code 1 \(SEGV_MAPERR\), fault addr 0xdead)");
774}
775
Josh Gaocbe70cb2016-10-18 18:17:52 -0700776TEST_F(CrasherTest, abort) {
777 int intercept_result;
778 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800779 StartProcess([]() {
780 abort();
781 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700782 StartIntercept(&output_fd);
783 FinishCrasher();
784 AssertDeath(SIGABRT);
785 FinishIntercept(&intercept_result);
786
787 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
788
789 std::string result;
790 ConsumeFd(std::move(output_fd), &result);
Andreas Gampe26cbafb2017-06-22 20:14:43 -0700791 ASSERT_BACKTRACE_FRAME(result, "abort");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700792}
793
794TEST_F(CrasherTest, signal) {
795 int intercept_result;
796 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800797 StartProcess([]() {
Josh Gao2b2ae0c2017-08-21 14:31:17 -0700798 while (true) {
799 sleep(1);
800 }
Josh Gao502cfd22017-02-17 01:39:15 -0800801 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700802 StartIntercept(&output_fd);
Josh Gao2b2ae0c2017-08-21 14:31:17 -0700803 FinishCrasher();
Josh Gaocbe70cb2016-10-18 18:17:52 -0700804 ASSERT_EQ(0, kill(crasher_pid, SIGSEGV));
805
806 AssertDeath(SIGSEGV);
807 FinishIntercept(&intercept_result);
808
809 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
810
811 std::string result;
812 ConsumeFd(std::move(output_fd), &result);
Elliott Hughes89722702018-05-02 10:47:00 -0700813 ASSERT_MATCH(
814 result,
815 R"(signal 11 \(SIGSEGV\), code 0 \(SI_USER from pid \d+, uid \d+\), fault addr --------)");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700816 ASSERT_MATCH(result, R"(backtrace:)");
817}
818
819TEST_F(CrasherTest, abort_message) {
820 int intercept_result;
821 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800822 StartProcess([]() {
Josh Gao1cc7bd82018-02-13 13:16:17 -0800823 // Arrived at experimentally;
824 // logd truncates at 4062.
825 // strlen("Abort message: ''") is 17.
826 // That's 4045, but we also want a NUL.
827 char buf[4045 + 1];
828 memset(buf, 'x', sizeof(buf));
829 buf[sizeof(buf) - 1] = '\0';
830 android_set_abort_message(buf);
Josh Gao502cfd22017-02-17 01:39:15 -0800831 abort();
832 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700833 StartIntercept(&output_fd);
834 FinishCrasher();
835 AssertDeath(SIGABRT);
836 FinishIntercept(&intercept_result);
837
838 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
839
840 std::string result;
841 ConsumeFd(std::move(output_fd), &result);
Josh Gao1cc7bd82018-02-13 13:16:17 -0800842 ASSERT_MATCH(result, R"(Abort message: 'x{4045}')");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700843}
844
Josh Gaoe06f2a42017-04-27 16:50:38 -0700845TEST_F(CrasherTest, abort_message_backtrace) {
846 int intercept_result;
847 unique_fd output_fd;
848 StartProcess([]() {
849 android_set_abort_message("not actually aborting");
Josh Gaoa48b41b2019-12-13 14:11:04 -0800850 raise(BIONIC_SIGNAL_DEBUGGER);
Josh Gaoe06f2a42017-04-27 16:50:38 -0700851 exit(0);
852 });
853 StartIntercept(&output_fd);
854 FinishCrasher();
855 AssertDeath(0);
856 FinishIntercept(&intercept_result);
857
858 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
859
860 std::string result;
861 ConsumeFd(std::move(output_fd), &result);
862 ASSERT_NOT_MATCH(result, R"(Abort message:)");
863}
864
Josh Gaocbe70cb2016-10-18 18:17:52 -0700865TEST_F(CrasherTest, intercept_timeout) {
866 int intercept_result;
867 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800868 StartProcess([]() {
869 abort();
870 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700871 StartIntercept(&output_fd);
872
873 // Don't let crasher finish until we timeout.
874 FinishIntercept(&intercept_result);
875
876 ASSERT_NE(1, intercept_result) << "tombstoned reported success? (intercept_result = "
877 << intercept_result << ")";
878
879 FinishCrasher();
880 AssertDeath(SIGABRT);
881}
882
Elliott Hughese4781d52021-03-17 09:15:15 -0700883TEST_F(CrasherTest, wait_for_debugger) {
884 if (!android::base::SetProperty(kWaitForDebuggerKey, "1")) {
885 FAIL() << "failed to enable wait_for_debugger";
Josh Gaocbe70cb2016-10-18 18:17:52 -0700886 }
887 sleep(1);
888
Josh Gao502cfd22017-02-17 01:39:15 -0800889 StartProcess([]() {
890 abort();
891 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700892 FinishCrasher();
893
894 int status;
Christopher Ferris172b0a02019-09-18 17:48:30 -0700895 ASSERT_EQ(crasher_pid, TEMP_FAILURE_RETRY(waitpid(crasher_pid, &status, WUNTRACED)));
Josh Gaocbe70cb2016-10-18 18:17:52 -0700896 ASSERT_TRUE(WIFSTOPPED(status));
897 ASSERT_EQ(SIGSTOP, WSTOPSIG(status));
898
899 ASSERT_EQ(0, kill(crasher_pid, SIGCONT));
900
901 AssertDeath(SIGABRT);
902}
903
Josh Gaocbe70cb2016-10-18 18:17:52 -0700904TEST_F(CrasherTest, backtrace) {
905 std::string result;
906 int intercept_result;
907 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800908
909 StartProcess([]() {
910 abort();
911 });
Narayan Kamatha73df602017-05-24 15:07:25 +0100912 StartIntercept(&output_fd, kDebuggerdNativeBacktrace);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700913
914 std::this_thread::sleep_for(500ms);
915
916 sigval val;
917 val.sival_int = 1;
Josh Gaoa48b41b2019-12-13 14:11:04 -0800918 ASSERT_EQ(0, sigqueue(crasher_pid, BIONIC_SIGNAL_DEBUGGER, val)) << strerror(errno);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700919 FinishIntercept(&intercept_result);
920 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
921 ConsumeFd(std::move(output_fd), &result);
Jaesung Chung58778e12017-06-15 18:20:34 +0900922 ASSERT_BACKTRACE_FRAME(result, "read");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700923
924 int status;
925 ASSERT_EQ(0, waitpid(crasher_pid, &status, WNOHANG | WUNTRACED));
926
927 StartIntercept(&output_fd);
928 FinishCrasher();
929 AssertDeath(SIGABRT);
930 FinishIntercept(&intercept_result);
931 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
932 ConsumeFd(std::move(output_fd), &result);
Andreas Gampe26cbafb2017-06-22 20:14:43 -0700933 ASSERT_BACKTRACE_FRAME(result, "abort");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700934}
Josh Gaofca7ca32017-01-23 12:05:35 -0800935
936TEST_F(CrasherTest, PR_SET_DUMPABLE_0_crash) {
Josh Gao502cfd22017-02-17 01:39:15 -0800937 int intercept_result;
938 unique_fd output_fd;
Josh Gaofca7ca32017-01-23 12:05:35 -0800939 StartProcess([]() {
940 prctl(PR_SET_DUMPABLE, 0);
Josh Gao502cfd22017-02-17 01:39:15 -0800941 abort();
Josh Gaofca7ca32017-01-23 12:05:35 -0800942 });
Josh Gao502cfd22017-02-17 01:39:15 -0800943
944 StartIntercept(&output_fd);
945 FinishCrasher();
946 AssertDeath(SIGABRT);
947 FinishIntercept(&intercept_result);
948
949 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
950
951 std::string result;
952 ConsumeFd(std::move(output_fd), &result);
Andreas Gampe26cbafb2017-06-22 20:14:43 -0700953 ASSERT_BACKTRACE_FRAME(result, "abort");
Josh Gaofca7ca32017-01-23 12:05:35 -0800954}
955
Josh Gao502cfd22017-02-17 01:39:15 -0800956TEST_F(CrasherTest, capabilities) {
957 ASSERT_EQ(0U, getuid()) << "capability test requires root";
958
Josh Gaofca7ca32017-01-23 12:05:35 -0800959 StartProcess([]() {
Josh Gao502cfd22017-02-17 01:39:15 -0800960 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) != 0) {
961 err(1, "failed to set PR_SET_KEEPCAPS");
962 }
963
964 if (setresuid(1, 1, 1) != 0) {
965 err(1, "setresuid failed");
966 }
967
968 __user_cap_header_struct capheader;
969 __user_cap_data_struct capdata[2];
970 memset(&capheader, 0, sizeof(capheader));
971 memset(&capdata, 0, sizeof(capdata));
972
973 capheader.version = _LINUX_CAPABILITY_VERSION_3;
974 capheader.pid = 0;
975
976 // Turn on every third capability.
977 static_assert(CAP_LAST_CAP > 33, "CAP_LAST_CAP <= 32");
978 for (int i = 0; i < CAP_LAST_CAP; i += 3) {
979 capdata[CAP_TO_INDEX(i)].permitted |= CAP_TO_MASK(i);
980 capdata[CAP_TO_INDEX(i)].effective |= CAP_TO_MASK(i);
981 }
982
983 // Make sure CAP_SYS_PTRACE is off.
984 capdata[CAP_TO_INDEX(CAP_SYS_PTRACE)].permitted &= ~(CAP_TO_MASK(CAP_SYS_PTRACE));
985 capdata[CAP_TO_INDEX(CAP_SYS_PTRACE)].effective &= ~(CAP_TO_MASK(CAP_SYS_PTRACE));
986
987 if (capset(&capheader, &capdata[0]) != 0) {
988 err(1, "capset failed");
989 }
990
991 if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_CLEAR_ALL, 0, 0, 0) != 0) {
992 err(1, "failed to drop ambient capabilities");
993 }
994
Josh Gaoa5199a92017-04-03 13:18:34 -0700995 pthread_setname_np(pthread_self(), "thread_name");
Josh Gao502cfd22017-02-17 01:39:15 -0800996 raise(SIGSYS);
Josh Gaofca7ca32017-01-23 12:05:35 -0800997 });
Josh Gao502cfd22017-02-17 01:39:15 -0800998
999 unique_fd output_fd;
1000 StartIntercept(&output_fd);
1001 FinishCrasher();
1002 AssertDeath(SIGSYS);
1003
1004 std::string result;
1005 int intercept_result;
1006 FinishIntercept(&intercept_result);
1007 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1008 ConsumeFd(std::move(output_fd), &result);
Josh Gaoa5199a92017-04-03 13:18:34 -07001009 ASSERT_MATCH(result, R"(name: thread_name\s+>>> .+debuggerd_test(32|64) <<<)");
Jaesung Chung58778e12017-06-15 18:20:34 +09001010 ASSERT_BACKTRACE_FRAME(result, "tgkill");
Josh Gaofca7ca32017-01-23 12:05:35 -08001011}
Josh Gaoc3c8c022017-02-13 16:36:18 -08001012
Josh Gao2e7b8e22017-05-04 17:12:57 -07001013TEST_F(CrasherTest, fake_pid) {
1014 int intercept_result;
1015 unique_fd output_fd;
1016
1017 // Prime the getpid/gettid caches.
1018 UNUSED(getpid());
1019 UNUSED(gettid());
1020
1021 std::function<pid_t()> clone_fn = []() {
1022 return syscall(__NR_clone, SIGCHLD, nullptr, nullptr, nullptr, nullptr);
1023 };
1024 StartProcess(
1025 []() {
1026 ASSERT_NE(getpid(), syscall(__NR_getpid));
1027 ASSERT_NE(gettid(), syscall(__NR_gettid));
1028 raise(SIGSEGV);
1029 },
1030 clone_fn);
1031
1032 StartIntercept(&output_fd);
1033 FinishCrasher();
1034 AssertDeath(SIGSEGV);
1035 FinishIntercept(&intercept_result);
1036
1037 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1038
1039 std::string result;
1040 ConsumeFd(std::move(output_fd), &result);
Jaesung Chung58778e12017-06-15 18:20:34 +09001041 ASSERT_BACKTRACE_FRAME(result, "tgkill");
Josh Gao2e7b8e22017-05-04 17:12:57 -07001042}
1043
Josh Gaoe04ca272018-01-16 15:38:17 -08001044static const char* const kDebuggerdSeccompPolicy =
1045 "/system/etc/seccomp_policy/crash_dump." ABI_STRING ".policy";
1046
Josh Gao70adac62018-02-22 11:38:33 -08001047static pid_t seccomp_fork_impl(void (*prejail)()) {
Josh Gao6f9eeec2018-09-12 13:55:47 -07001048 std::string policy;
1049 if (!android::base::ReadFileToString(kDebuggerdSeccompPolicy, &policy)) {
1050 PLOG(FATAL) << "failed to read policy file";
1051 }
1052
1053 // Allow a bunch of syscalls used by the tests.
1054 policy += "\nclone: 1";
1055 policy += "\nsigaltstack: 1";
1056 policy += "\nnanosleep: 1";
Christopher Ferrisab606682019-09-17 15:31:47 -07001057 policy += "\ngetrlimit: 1";
1058 policy += "\nugetrlimit: 1";
Josh Gao6f9eeec2018-09-12 13:55:47 -07001059
1060 FILE* tmp_file = tmpfile();
1061 if (!tmp_file) {
1062 PLOG(FATAL) << "tmpfile failed";
1063 }
1064
Christopher Ferris172b0a02019-09-18 17:48:30 -07001065 unique_fd tmp_fd(TEMP_FAILURE_RETRY(dup(fileno(tmp_file))));
Josh Gao6f9eeec2018-09-12 13:55:47 -07001066 if (!android::base::WriteStringToFd(policy, tmp_fd.get())) {
1067 PLOG(FATAL) << "failed to write policy to tmpfile";
1068 }
1069
1070 if (lseek(tmp_fd.get(), 0, SEEK_SET) != 0) {
1071 PLOG(FATAL) << "failed to seek tmp_fd";
Josh Gaoe04ca272018-01-16 15:38:17 -08001072 }
1073
1074 ScopedMinijail jail{minijail_new()};
1075 if (!jail) {
1076 LOG(FATAL) << "failed to create minijail";
1077 }
1078
1079 minijail_no_new_privs(jail.get());
1080 minijail_log_seccomp_filter_failures(jail.get());
1081 minijail_use_seccomp_filter(jail.get());
Josh Gao6f9eeec2018-09-12 13:55:47 -07001082 minijail_parse_seccomp_filters_from_fd(jail.get(), tmp_fd.release());
Josh Gaoe04ca272018-01-16 15:38:17 -08001083
1084 pid_t result = fork();
1085 if (result == -1) {
1086 return result;
1087 } else if (result != 0) {
1088 return result;
1089 }
1090
1091 // Spawn and detach a thread that spins forever.
1092 std::atomic<bool> thread_ready(false);
1093 std::thread thread([&jail, &thread_ready]() {
1094 minijail_enter(jail.get());
1095 thread_ready = true;
1096 for (;;)
1097 ;
1098 });
1099 thread.detach();
1100
1101 while (!thread_ready) {
1102 continue;
1103 }
1104
Josh Gao70adac62018-02-22 11:38:33 -08001105 if (prejail) {
1106 prejail();
1107 }
1108
Josh Gaoe04ca272018-01-16 15:38:17 -08001109 minijail_enter(jail.get());
1110 return result;
1111}
1112
Josh Gao70adac62018-02-22 11:38:33 -08001113static pid_t seccomp_fork() {
1114 return seccomp_fork_impl(nullptr);
1115}
1116
Josh Gaoe04ca272018-01-16 15:38:17 -08001117TEST_F(CrasherTest, seccomp_crash) {
1118 int intercept_result;
1119 unique_fd output_fd;
1120
1121 StartProcess([]() { abort(); }, &seccomp_fork);
1122
1123 StartIntercept(&output_fd);
1124 FinishCrasher();
1125 AssertDeath(SIGABRT);
1126 FinishIntercept(&intercept_result);
1127 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1128
1129 std::string result;
1130 ConsumeFd(std::move(output_fd), &result);
1131 ASSERT_BACKTRACE_FRAME(result, "abort");
1132}
1133
Josh Gao70adac62018-02-22 11:38:33 -08001134static pid_t seccomp_fork_rlimit() {
1135 return seccomp_fork_impl([]() {
1136 struct rlimit rlim = {
1137 .rlim_cur = 512 * 1024 * 1024,
1138 .rlim_max = 512 * 1024 * 1024,
1139 };
1140
1141 if (setrlimit(RLIMIT_AS, &rlim) != 0) {
1142 raise(SIGINT);
1143 }
1144 });
1145}
1146
1147TEST_F(CrasherTest, seccomp_crash_oom) {
1148 int intercept_result;
1149 unique_fd output_fd;
1150
1151 StartProcess(
1152 []() {
1153 std::vector<void*> vec;
1154 for (int i = 0; i < 512; ++i) {
1155 char* buf = static_cast<char*>(malloc(1024 * 1024));
1156 if (!buf) {
1157 abort();
1158 }
1159 memset(buf, 0xff, 1024 * 1024);
1160 vec.push_back(buf);
1161 }
1162 },
1163 &seccomp_fork_rlimit);
1164
1165 StartIntercept(&output_fd);
1166 FinishCrasher();
1167 AssertDeath(SIGABRT);
1168 FinishIntercept(&intercept_result);
1169 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1170
1171 // We can't actually generate a backtrace, just make sure that the process terminates.
1172}
1173
Josh Gaoe04ca272018-01-16 15:38:17 -08001174__attribute__((noinline)) extern "C" bool raise_debugger_signal(DebuggerdDumpType dump_type) {
1175 siginfo_t siginfo;
1176 siginfo.si_code = SI_QUEUE;
1177 siginfo.si_pid = getpid();
1178 siginfo.si_uid = getuid();
1179
1180 if (dump_type != kDebuggerdNativeBacktrace && dump_type != kDebuggerdTombstone) {
1181 PLOG(FATAL) << "invalid dump type";
1182 }
1183
1184 siginfo.si_value.sival_int = dump_type == kDebuggerdNativeBacktrace;
1185
Josh Gaoa48b41b2019-12-13 14:11:04 -08001186 if (syscall(__NR_rt_tgsigqueueinfo, getpid(), gettid(), BIONIC_SIGNAL_DEBUGGER, &siginfo) != 0) {
Josh Gaoe04ca272018-01-16 15:38:17 -08001187 PLOG(ERROR) << "libdebuggerd_client: failed to send signal to self";
1188 return false;
1189 }
1190
1191 return true;
1192}
1193
1194TEST_F(CrasherTest, seccomp_tombstone) {
1195 int intercept_result;
1196 unique_fd output_fd;
1197
1198 static const auto dump_type = kDebuggerdTombstone;
1199 StartProcess(
1200 []() {
1201 raise_debugger_signal(dump_type);
1202 _exit(0);
1203 },
1204 &seccomp_fork);
1205
1206 StartIntercept(&output_fd, dump_type);
1207 FinishCrasher();
1208 AssertDeath(0);
1209 FinishIntercept(&intercept_result);
1210 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1211
1212 std::string result;
1213 ConsumeFd(std::move(output_fd), &result);
1214 ASSERT_BACKTRACE_FRAME(result, "raise_debugger_signal");
1215}
1216
Josh Gao6f9eeec2018-09-12 13:55:47 -07001217extern "C" void foo() {
1218 LOG(INFO) << "foo";
1219 std::this_thread::sleep_for(1s);
1220}
1221
1222extern "C" void bar() {
1223 LOG(INFO) << "bar";
1224 std::this_thread::sleep_for(1s);
1225}
1226
Josh Gaoe04ca272018-01-16 15:38:17 -08001227TEST_F(CrasherTest, seccomp_backtrace) {
1228 int intercept_result;
1229 unique_fd output_fd;
1230
1231 static const auto dump_type = kDebuggerdNativeBacktrace;
1232 StartProcess(
1233 []() {
Josh Gao6f9eeec2018-09-12 13:55:47 -07001234 std::thread a(foo);
1235 std::thread b(bar);
1236
1237 std::this_thread::sleep_for(100ms);
1238
Josh Gaoe04ca272018-01-16 15:38:17 -08001239 raise_debugger_signal(dump_type);
1240 _exit(0);
1241 },
1242 &seccomp_fork);
1243
1244 StartIntercept(&output_fd, dump_type);
1245 FinishCrasher();
1246 AssertDeath(0);
1247 FinishIntercept(&intercept_result);
1248 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1249
1250 std::string result;
1251 ConsumeFd(std::move(output_fd), &result);
1252 ASSERT_BACKTRACE_FRAME(result, "raise_debugger_signal");
Josh Gao6f9eeec2018-09-12 13:55:47 -07001253 ASSERT_BACKTRACE_FRAME(result, "foo");
1254 ASSERT_BACKTRACE_FRAME(result, "bar");
Josh Gaoe04ca272018-01-16 15:38:17 -08001255}
1256
1257TEST_F(CrasherTest, seccomp_crash_logcat) {
1258 StartProcess([]() { abort(); }, &seccomp_fork);
1259 FinishCrasher();
1260
1261 // Make sure we don't get SIGSYS when trying to dump a crash to logcat.
1262 AssertDeath(SIGABRT);
1263}
1264
Josh Gaofd13bf02017-08-18 15:37:26 -07001265TEST_F(CrasherTest, competing_tracer) {
1266 int intercept_result;
1267 unique_fd output_fd;
1268 StartProcess([]() {
Josh Gao2b2ae0c2017-08-21 14:31:17 -07001269 raise(SIGABRT);
Josh Gaofd13bf02017-08-18 15:37:26 -07001270 });
1271
1272 StartIntercept(&output_fd);
Josh Gaofd13bf02017-08-18 15:37:26 -07001273
1274 ASSERT_EQ(0, ptrace(PTRACE_SEIZE, crasher_pid, 0, 0));
Josh Gao2b2ae0c2017-08-21 14:31:17 -07001275 FinishCrasher();
Josh Gaofd13bf02017-08-18 15:37:26 -07001276
1277 int status;
Christopher Ferris172b0a02019-09-18 17:48:30 -07001278 ASSERT_EQ(crasher_pid, TEMP_FAILURE_RETRY(waitpid(crasher_pid, &status, 0)));
Josh Gaofd13bf02017-08-18 15:37:26 -07001279 ASSERT_TRUE(WIFSTOPPED(status));
1280 ASSERT_EQ(SIGABRT, WSTOPSIG(status));
1281
1282 ASSERT_EQ(0, ptrace(PTRACE_CONT, crasher_pid, 0, 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 std::string regex = R"(failed to attach to thread \d+, already traced by )";
1289 regex += std::to_string(gettid());
1290 regex += R"( \(.+debuggerd_test)";
1291 ASSERT_MATCH(result, regex.c_str());
1292
Christopher Ferris172b0a02019-09-18 17:48:30 -07001293 ASSERT_EQ(crasher_pid, TEMP_FAILURE_RETRY(waitpid(crasher_pid, &status, 0)));
Josh Gao2b2ae0c2017-08-21 14:31:17 -07001294 ASSERT_TRUE(WIFSTOPPED(status));
1295 ASSERT_EQ(SIGABRT, WSTOPSIG(status));
1296
Josh Gaofd13bf02017-08-18 15:37:26 -07001297 ASSERT_EQ(0, ptrace(PTRACE_DETACH, crasher_pid, 0, SIGABRT));
1298 AssertDeath(SIGABRT);
1299}
1300
Josh Gaobf06a402018-08-27 16:34:01 -07001301TEST_F(CrasherTest, fdsan_warning_abort_message) {
1302 int intercept_result;
1303 unique_fd output_fd;
1304
1305 StartProcess([]() {
1306 android_fdsan_set_error_level(ANDROID_FDSAN_ERROR_LEVEL_WARN_ONCE);
Christopher Ferris172b0a02019-09-18 17:48:30 -07001307 unique_fd fd(TEMP_FAILURE_RETRY(open("/dev/null", O_RDONLY | O_CLOEXEC)));
Josh Gaobf06a402018-08-27 16:34:01 -07001308 if (fd == -1) {
1309 abort();
1310 }
1311 close(fd.get());
1312 _exit(0);
1313 });
1314
1315 StartIntercept(&output_fd);
1316 FinishCrasher();
1317 AssertDeath(0);
1318 FinishIntercept(&intercept_result);
1319 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1320
1321 std::string result;
1322 ConsumeFd(std::move(output_fd), &result);
1323 ASSERT_MATCH(result, "Abort message: 'attempted to close");
1324}
1325
Josh Gaoc3c8c022017-02-13 16:36:18 -08001326TEST(crash_dump, zombie) {
1327 pid_t forkpid = fork();
1328
Josh Gaoc3c8c022017-02-13 16:36:18 -08001329 pid_t rc;
1330 int status;
1331
1332 if (forkpid == 0) {
1333 errno = 0;
1334 rc = waitpid(-1, &status, WNOHANG | __WALL | __WNOTHREAD);
1335 if (rc != -1 || errno != ECHILD) {
1336 errx(2, "first waitpid returned %d (%s), expected failure with ECHILD", rc, strerror(errno));
1337 }
1338
Josh Gaoa48b41b2019-12-13 14:11:04 -08001339 raise(BIONIC_SIGNAL_DEBUGGER);
Josh Gaoc3c8c022017-02-13 16:36:18 -08001340
1341 errno = 0;
Christopher Ferris172b0a02019-09-18 17:48:30 -07001342 rc = TEMP_FAILURE_RETRY(waitpid(-1, &status, __WALL | __WNOTHREAD));
Josh Gaoc3c8c022017-02-13 16:36:18 -08001343 if (rc != -1 || errno != ECHILD) {
1344 errx(2, "second waitpid returned %d (%s), expected failure with ECHILD", rc, strerror(errno));
1345 }
1346 _exit(0);
1347 } else {
Christopher Ferris172b0a02019-09-18 17:48:30 -07001348 rc = TEMP_FAILURE_RETRY(waitpid(forkpid, &status, 0));
Josh Gaoc3c8c022017-02-13 16:36:18 -08001349 ASSERT_EQ(forkpid, rc);
1350 ASSERT_TRUE(WIFEXITED(status));
1351 ASSERT_EQ(0, WEXITSTATUS(status));
1352 }
1353}
Josh Gao352a8452017-03-30 16:46:21 -07001354
1355TEST(tombstoned, no_notify) {
1356 // Do this a few times.
1357 for (int i = 0; i < 3; ++i) {
1358 pid_t pid = 123'456'789 + i;
1359
1360 unique_fd intercept_fd, output_fd;
Narayan Kamathca5e9082017-06-02 15:42:06 +01001361 InterceptStatus status;
1362 tombstoned_intercept(pid, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
1363 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gao352a8452017-03-30 16:46:21 -07001364
1365 {
1366 unique_fd tombstoned_socket, input_fd;
Narayan Kamatha73df602017-05-24 15:07:25 +01001367 ASSERT_TRUE(tombstoned_connect(pid, &tombstoned_socket, &input_fd, kDebuggerdTombstone));
Josh Gao352a8452017-03-30 16:46:21 -07001368 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), &pid, sizeof(pid)));
1369 }
1370
1371 pid_t read_pid;
1372 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), &read_pid, sizeof(read_pid)));
1373 ASSERT_EQ(read_pid, pid);
1374 }
1375}
1376
1377TEST(tombstoned, stress) {
1378 // Spawn threads to simultaneously do a bunch of failing dumps and a bunch of successful dumps.
1379 static constexpr int kDumpCount = 100;
1380
1381 std::atomic<bool> start(false);
1382 std::vector<std::thread> threads;
1383 threads.emplace_back([&start]() {
1384 while (!start) {
1385 continue;
1386 }
1387
1388 // Use a way out of range pid, to avoid stomping on an actual process.
1389 pid_t pid_base = 1'000'000;
1390
1391 for (int dump = 0; dump < kDumpCount; ++dump) {
1392 pid_t pid = pid_base + dump;
1393
1394 unique_fd intercept_fd, output_fd;
Narayan Kamathca5e9082017-06-02 15:42:06 +01001395 InterceptStatus status;
1396 tombstoned_intercept(pid, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
1397 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gao352a8452017-03-30 16:46:21 -07001398
1399 // Pretend to crash, and then immediately close the socket.
1400 unique_fd sockfd(socket_local_client(kTombstonedCrashSocketName,
1401 ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_SEQPACKET));
1402 if (sockfd == -1) {
1403 FAIL() << "failed to connect to tombstoned: " << strerror(errno);
1404 }
1405 TombstonedCrashPacket packet = {};
1406 packet.packet_type = CrashPacketType::kDumpRequest;
1407 packet.packet.dump_request.pid = pid;
1408 if (TEMP_FAILURE_RETRY(write(sockfd, &packet, sizeof(packet))) != sizeof(packet)) {
1409 FAIL() << "failed to write to tombstoned: " << strerror(errno);
1410 }
1411
1412 continue;
1413 }
1414 });
1415
1416 threads.emplace_back([&start]() {
1417 while (!start) {
1418 continue;
1419 }
1420
1421 // Use a way out of range pid, to avoid stomping on an actual process.
1422 pid_t pid_base = 2'000'000;
1423
1424 for (int dump = 0; dump < kDumpCount; ++dump) {
1425 pid_t pid = pid_base + dump;
1426
1427 unique_fd intercept_fd, output_fd;
Narayan Kamathca5e9082017-06-02 15:42:06 +01001428 InterceptStatus status;
1429 tombstoned_intercept(pid, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
1430 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gao352a8452017-03-30 16:46:21 -07001431
1432 {
1433 unique_fd tombstoned_socket, input_fd;
Narayan Kamatha73df602017-05-24 15:07:25 +01001434 ASSERT_TRUE(tombstoned_connect(pid, &tombstoned_socket, &input_fd, kDebuggerdTombstone));
Josh Gao352a8452017-03-30 16:46:21 -07001435 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), &pid, sizeof(pid)));
1436 tombstoned_notify_completion(tombstoned_socket.get());
1437 }
1438
1439 // TODO: Fix the race that requires this sleep.
1440 std::this_thread::sleep_for(50ms);
1441
1442 pid_t read_pid;
1443 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), &read_pid, sizeof(read_pid)));
1444 ASSERT_EQ(read_pid, pid);
1445 }
1446 });
1447
1448 start = true;
1449
1450 for (std::thread& thread : threads) {
1451 thread.join();
1452 }
1453}
Narayan Kamathca5e9082017-06-02 15:42:06 +01001454
1455TEST(tombstoned, java_trace_intercept_smoke) {
1456 // Using a "real" PID is a little dangerous here - if the test fails
1457 // or crashes, we might end up getting a bogus / unreliable stack
1458 // trace.
1459 const pid_t self = getpid();
1460
1461 unique_fd intercept_fd, output_fd;
1462 InterceptStatus status;
1463 tombstoned_intercept(self, &intercept_fd, &output_fd, &status, kDebuggerdJavaBacktrace);
1464 ASSERT_EQ(InterceptStatus::kRegistered, status);
1465
Josh Gao76e1e302021-01-26 15:53:11 -08001466 // First connect to tombstoned requesting a native tombstone. This
Narayan Kamathca5e9082017-06-02 15:42:06 +01001467 // should result in a "regular" FD and not the installed intercept.
1468 const char native[] = "native";
1469 unique_fd tombstoned_socket, input_fd;
Josh Gao76e1e302021-01-26 15:53:11 -08001470 ASSERT_TRUE(tombstoned_connect(self, &tombstoned_socket, &input_fd, kDebuggerdTombstone));
Narayan Kamathca5e9082017-06-02 15:42:06 +01001471 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), native, sizeof(native)));
1472 tombstoned_notify_completion(tombstoned_socket.get());
1473
1474 // Then, connect to tombstoned asking for a java backtrace. This *should*
1475 // trigger the intercept.
1476 const char java[] = "java";
1477 ASSERT_TRUE(tombstoned_connect(self, &tombstoned_socket, &input_fd, kDebuggerdJavaBacktrace));
1478 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), java, sizeof(java)));
1479 tombstoned_notify_completion(tombstoned_socket.get());
1480
1481 char outbuf[sizeof(java)];
1482 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), outbuf, sizeof(outbuf)));
1483 ASSERT_STREQ("java", outbuf);
1484}
1485
1486TEST(tombstoned, multiple_intercepts) {
1487 const pid_t fake_pid = 1'234'567;
1488 unique_fd intercept_fd, output_fd;
1489 InterceptStatus status;
1490 tombstoned_intercept(fake_pid, &intercept_fd, &output_fd, &status, kDebuggerdJavaBacktrace);
1491 ASSERT_EQ(InterceptStatus::kRegistered, status);
1492
1493 unique_fd intercept_fd_2, output_fd_2;
1494 tombstoned_intercept(fake_pid, &intercept_fd_2, &output_fd_2, &status, kDebuggerdNativeBacktrace);
1495 ASSERT_EQ(InterceptStatus::kFailedAlreadyRegistered, status);
1496}
1497
1498TEST(tombstoned, intercept_any) {
1499 const pid_t fake_pid = 1'234'567;
1500
1501 unique_fd intercept_fd, output_fd;
1502 InterceptStatus status;
1503 tombstoned_intercept(fake_pid, &intercept_fd, &output_fd, &status, kDebuggerdNativeBacktrace);
1504 ASSERT_EQ(InterceptStatus::kRegistered, status);
1505
1506 const char any[] = "any";
1507 unique_fd tombstoned_socket, input_fd;
1508 ASSERT_TRUE(tombstoned_connect(fake_pid, &tombstoned_socket, &input_fd, kDebuggerdAnyIntercept));
1509 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), any, sizeof(any)));
1510 tombstoned_notify_completion(tombstoned_socket.get());
1511
1512 char outbuf[sizeof(any)];
1513 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), outbuf, sizeof(outbuf)));
1514 ASSERT_STREQ("any", outbuf);
1515}
Josh Gao2b22ae12018-09-12 14:51:03 -07001516
1517TEST(tombstoned, interceptless_backtrace) {
1518 // Generate 50 backtraces, and then check to see that we haven't created 50 new tombstones.
1519 auto get_tombstone_timestamps = []() -> std::map<int, time_t> {
1520 std::map<int, time_t> result;
1521 for (int i = 0; i < 99; ++i) {
1522 std::string path = android::base::StringPrintf("/data/tombstones/tombstone_%02d", i);
1523 struct stat st;
1524 if (stat(path.c_str(), &st) == 0) {
1525 result[i] = st.st_mtim.tv_sec;
1526 }
1527 }
1528 return result;
1529 };
1530
1531 auto before = get_tombstone_timestamps();
1532 for (int i = 0; i < 50; ++i) {
1533 raise_debugger_signal(kDebuggerdNativeBacktrace);
1534 }
1535 auto after = get_tombstone_timestamps();
1536
1537 int diff = 0;
1538 for (int i = 0; i < 99; ++i) {
1539 if (after.count(i) == 0) {
1540 continue;
1541 }
1542 if (before.count(i) == 0) {
1543 ++diff;
1544 continue;
1545 }
1546 if (before[i] != after[i]) {
1547 ++diff;
1548 }
1549 }
1550
1551 // We can't be sure that nothing's crash looping in the background.
1552 // This should be good enough, though...
1553 ASSERT_LT(diff, 10) << "too many new tombstones; is something crashing in the background?";
1554}
Christopher Ferris481e8372019-07-15 17:13:24 -07001555
1556static __attribute__((__noinline__)) void overflow_stack(void* p) {
1557 void* buf[1];
1558 buf[0] = p;
1559 static volatile void* global = buf;
1560 if (global) {
1561 global = buf;
1562 overflow_stack(&buf);
1563 }
1564}
1565
1566TEST_F(CrasherTest, stack_overflow) {
1567 int intercept_result;
1568 unique_fd output_fd;
1569 StartProcess([]() { overflow_stack(nullptr); });
1570
1571 StartIntercept(&output_fd);
1572 FinishCrasher();
1573 AssertDeath(SIGSEGV);
1574 FinishIntercept(&intercept_result);
1575
1576 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1577
1578 std::string result;
1579 ConsumeFd(std::move(output_fd), &result);
1580 ASSERT_MATCH(result, R"(Cause: stack pointer[^\n]*stack overflow.\n)");
1581}
Josh Gao76e1e302021-01-26 15:53:11 -08001582
Christopher Ferrisfe751c52021-04-16 09:40:40 -07001583static bool CopySharedLibrary(const char* tmp_dir, std::string* tmp_so_name) {
1584 std::string test_lib(testing::internal::GetArgvs()[0]);
1585 auto const value = test_lib.find_last_of('/');
1586 if (value == std::string::npos) {
1587 test_lib = "./";
1588 } else {
1589 test_lib = test_lib.substr(0, value + 1) + "./";
1590 }
1591 test_lib += "libcrash_test.so";
1592
1593 *tmp_so_name = std::string(tmp_dir) + "/libcrash_test.so";
1594 std::string cp_cmd = android::base::StringPrintf("cp %s %s", test_lib.c_str(), tmp_dir);
1595
1596 // Copy the shared so to a tempory directory.
1597 return system(cp_cmd.c_str()) == 0;
1598}
1599
1600TEST_F(CrasherTest, unreadable_elf) {
1601 int intercept_result;
1602 unique_fd output_fd;
1603 StartProcess([]() {
1604 TemporaryDir td;
1605 std::string tmp_so_name;
1606 if (!CopySharedLibrary(td.path, &tmp_so_name)) {
1607 _exit(1);
1608 }
1609 void* handle = dlopen(tmp_so_name.c_str(), RTLD_NOW);
1610 if (handle == nullptr) {
1611 _exit(1);
1612 }
1613 // Delete the original shared library so that we get the warning
1614 // about unreadable elf files.
1615 if (unlink(tmp_so_name.c_str()) == -1) {
1616 _exit(1);
1617 }
1618 void (*crash_func)() = reinterpret_cast<void (*)()>(dlsym(handle, "crash"));
1619 if (crash_func == nullptr) {
1620 _exit(1);
1621 }
1622 crash_func();
1623 });
1624
1625 StartIntercept(&output_fd);
1626 FinishCrasher();
1627 AssertDeath(SIGSEGV);
1628 FinishIntercept(&intercept_result);
1629
1630 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
1631
1632 std::string result;
1633 ConsumeFd(std::move(output_fd), &result);
1634 ASSERT_MATCH(result, R"(NOTE: Function names and BuildId information is missing )");
1635}
1636
Josh Gao76e1e302021-01-26 15:53:11 -08001637TEST(tombstoned, proto) {
1638 const pid_t self = getpid();
1639 unique_fd tombstoned_socket, text_fd, proto_fd;
1640 ASSERT_TRUE(
1641 tombstoned_connect(self, &tombstoned_socket, &text_fd, &proto_fd, kDebuggerdTombstoneProto));
1642
1643 tombstoned_notify_completion(tombstoned_socket.get());
1644
1645 ASSERT_NE(-1, text_fd.get());
1646 ASSERT_NE(-1, proto_fd.get());
1647
1648 struct stat text_st;
1649 ASSERT_EQ(0, fstat(text_fd.get(), &text_st));
1650
1651 // Give tombstoned some time to link the files into place.
1652 std::this_thread::sleep_for(100ms);
1653
1654 // Find the tombstone.
Christopher Ferris35da2882021-02-17 15:39:06 -08001655 std::optional<std::string> tombstone_file;
1656 std::unique_ptr<DIR, decltype(&closedir)> dir_h(opendir("/data/tombstones"), closedir);
1657 ASSERT_TRUE(dir_h != nullptr);
1658 std::regex tombstone_re("tombstone_\\d+");
1659 dirent* entry;
1660 while ((entry = readdir(dir_h.get())) != nullptr) {
1661 if (!std::regex_match(entry->d_name, tombstone_re)) {
1662 continue;
1663 }
1664 std::string path = android::base::StringPrintf("/data/tombstones/%s", entry->d_name);
Josh Gao76e1e302021-01-26 15:53:11 -08001665
1666 struct stat st;
1667 if (TEMP_FAILURE_RETRY(stat(path.c_str(), &st)) != 0) {
1668 continue;
1669 }
1670
1671 if (st.st_dev == text_st.st_dev && st.st_ino == text_st.st_ino) {
Christopher Ferris35da2882021-02-17 15:39:06 -08001672 tombstone_file = path;
Josh Gao76e1e302021-01-26 15:53:11 -08001673 break;
1674 }
1675 }
1676
Christopher Ferris35da2882021-02-17 15:39:06 -08001677 ASSERT_TRUE(tombstone_file);
1678 std::string proto_path = tombstone_file.value() + ".pb";
Josh Gao76e1e302021-01-26 15:53:11 -08001679
1680 struct stat proto_fd_st;
1681 struct stat proto_file_st;
1682 ASSERT_EQ(0, fstat(proto_fd.get(), &proto_fd_st));
1683 ASSERT_EQ(0, stat(proto_path.c_str(), &proto_file_st));
1684
1685 ASSERT_EQ(proto_fd_st.st_dev, proto_file_st.st_dev);
1686 ASSERT_EQ(proto_fd_st.st_ino, proto_file_st.st_ino);
1687}
1688
1689TEST(tombstoned, proto_intercept) {
1690 const pid_t self = getpid();
1691 unique_fd intercept_fd, output_fd;
1692 InterceptStatus status;
1693
1694 tombstoned_intercept(self, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
1695 ASSERT_EQ(InterceptStatus::kRegistered, status);
1696
1697 unique_fd tombstoned_socket, text_fd, proto_fd;
1698 ASSERT_TRUE(
1699 tombstoned_connect(self, &tombstoned_socket, &text_fd, &proto_fd, kDebuggerdTombstoneProto));
1700 ASSERT_TRUE(android::base::WriteStringToFd("foo", text_fd.get()));
1701 tombstoned_notify_completion(tombstoned_socket.get());
1702
1703 text_fd.reset();
1704
1705 std::string output;
1706 ASSERT_TRUE(android::base::ReadFdToString(output_fd, &output));
1707 ASSERT_EQ("foo", output);
1708}