blob: dfb7a6a7c0a193516b10e558079ff30035d6eef1 [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
17#include <err.h>
18#include <fcntl.h>
Josh Gaocdea7502017-11-01 15:00:40 -070019#include <stdlib.h>
Josh Gao502cfd22017-02-17 01:39:15 -080020#include <sys/capability.h>
Josh Gaofca7ca32017-01-23 12:05:35 -080021#include <sys/prctl.h>
Josh Gaofd13bf02017-08-18 15:37:26 -070022#include <sys/ptrace.h>
Josh Gao70adac62018-02-22 11:38:33 -080023#include <sys/resource.h>
Dan Albertc38057a2017-10-11 11:35:40 -070024#include <sys/syscall.h>
Josh Gaocbe70cb2016-10-18 18:17:52 -070025#include <sys/types.h>
Josh Gaofd13bf02017-08-18 15:37:26 -070026#include <unistd.h>
Josh Gaocbe70cb2016-10-18 18:17:52 -070027
28#include <chrono>
29#include <regex>
30#include <thread>
31
Josh Gao502cfd22017-02-17 01:39:15 -080032#include <android/set_abort_message.h>
33
Josh Gaocbe70cb2016-10-18 18:17:52 -070034#include <android-base/file.h>
35#include <android-base/logging.h>
Josh Gao2e7b8e22017-05-04 17:12:57 -070036#include <android-base/macros.h>
Josh Gaocbe70cb2016-10-18 18:17:52 -070037#include <android-base/parseint.h>
38#include <android-base/properties.h>
39#include <android-base/strings.h>
Josh Gao30171a82017-04-27 19:48:44 -070040#include <android-base/test_utils.h>
Josh Gaocbe70cb2016-10-18 18:17:52 -070041#include <android-base/unique_fd.h>
42#include <cutils/sockets.h>
Josh Gaocbe70cb2016-10-18 18:17:52 -070043#include <gtest/gtest.h>
44
Josh Gaoe04ca272018-01-16 15:38:17 -080045#include <libminijail.h>
46#include <scoped_minijail.h>
47
Narayan Kamath2d377cd2017-05-10 10:58:59 +010048#include "debuggerd/handler.h"
49#include "protocol.h"
50#include "tombstoned/tombstoned.h"
51#include "util.h"
52
Josh Gaocbe70cb2016-10-18 18:17:52 -070053using namespace std::chrono_literals;
54using android::base::unique_fd;
55
56#if defined(__LP64__)
Josh Gaocbe70cb2016-10-18 18:17:52 -070057#define ARCH_SUFFIX "64"
58#else
Josh Gaocbe70cb2016-10-18 18:17:52 -070059#define ARCH_SUFFIX ""
60#endif
61
62constexpr char kWaitForGdbKey[] = "debug.debuggerd.wait_for_gdb";
63
64#define TIMEOUT(seconds, expr) \
65 [&]() { \
66 struct sigaction old_sigaction; \
67 struct sigaction new_sigaction = {}; \
68 new_sigaction.sa_handler = [](int) {}; \
69 if (sigaction(SIGALRM, &new_sigaction, &new_sigaction) != 0) { \
70 err(1, "sigaction failed"); \
71 } \
72 alarm(seconds); \
73 auto value = expr; \
74 int saved_errno = errno; \
75 if (sigaction(SIGALRM, &old_sigaction, nullptr) != 0) { \
76 err(1, "sigaction failed"); \
77 } \
78 alarm(0); \
79 errno = saved_errno; \
80 return value; \
81 }()
82
Chih-Hung Hsieh3249b3a2018-05-11 16:01:21 -070083// Backtrace frame dump could contain:
84// #01 pc 0001cded /data/tmp/debuggerd_test32 (raise_debugger_signal+80)
85// or
86// #01 pc 00022a09 /data/tmp/debuggerd_test32 (offset 0x12000) (raise_debugger_signal+80)
Josh Gaoe04ca272018-01-16 15:38:17 -080087#define ASSERT_BACKTRACE_FRAME(result, frame_name) \
Chih-Hung Hsieh3249b3a2018-05-11 16:01:21 -070088 ASSERT_MATCH(result, \
89 R"(#\d\d pc [0-9a-f]+\s+ \S+ (\(offset 0x[0-9a-f]+\) )?\()" frame_name R"(\+)");
Jaesung Chung58778e12017-06-15 18:20:34 +090090
Narayan Kamatha73df602017-05-24 15:07:25 +010091static void tombstoned_intercept(pid_t target_pid, unique_fd* intercept_fd, unique_fd* output_fd,
Narayan Kamathca5e9082017-06-02 15:42:06 +010092 InterceptStatus* status, DebuggerdDumpType intercept_type) {
Josh Gao460b3362017-03-30 16:40:47 -070093 intercept_fd->reset(socket_local_client(kTombstonedInterceptSocketName,
94 ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_SEQPACKET));
95 if (intercept_fd->get() == -1) {
96 FAIL() << "failed to contact tombstoned: " << strerror(errno);
97 }
98
Narayan Kamatha73df602017-05-24 15:07:25 +010099 InterceptRequest req = {.pid = target_pid, .dump_type = intercept_type};
Josh Gao460b3362017-03-30 16:40:47 -0700100
101 unique_fd output_pipe_write;
102 if (!Pipe(output_fd, &output_pipe_write)) {
103 FAIL() << "failed to create output pipe: " << strerror(errno);
104 }
105
106 std::string pipe_size_str;
107 int pipe_buffer_size;
108 if (!android::base::ReadFileToString("/proc/sys/fs/pipe-max-size", &pipe_size_str)) {
109 FAIL() << "failed to read /proc/sys/fs/pipe-max-size: " << strerror(errno);
110 }
111
112 pipe_size_str = android::base::Trim(pipe_size_str);
113
114 if (!android::base::ParseInt(pipe_size_str.c_str(), &pipe_buffer_size, 0)) {
115 FAIL() << "failed to parse pipe max size";
116 }
117
118 if (fcntl(output_fd->get(), F_SETPIPE_SZ, pipe_buffer_size) != pipe_buffer_size) {
119 FAIL() << "failed to set pipe size: " << strerror(errno);
120 }
121
Josh Gao5675f3c2017-06-01 12:19:53 -0700122 ASSERT_GE(pipe_buffer_size, 1024 * 1024);
123
Josh Gao460b3362017-03-30 16:40:47 -0700124 if (send_fd(intercept_fd->get(), &req, sizeof(req), std::move(output_pipe_write)) != sizeof(req)) {
125 FAIL() << "failed to send output fd to tombstoned: " << strerror(errno);
126 }
127
128 InterceptResponse response;
129 ssize_t rc = TEMP_FAILURE_RETRY(read(intercept_fd->get(), &response, sizeof(response)));
130 if (rc == -1) {
131 FAIL() << "failed to read response from tombstoned: " << strerror(errno);
132 } else if (rc == 0) {
133 FAIL() << "failed to read response from tombstoned (EOF)";
134 } else if (rc != sizeof(response)) {
135 FAIL() << "received packet of unexpected length from tombstoned: expected " << sizeof(response)
136 << ", received " << rc;
137 }
138
Narayan Kamathca5e9082017-06-02 15:42:06 +0100139 *status = response.status;
Josh Gao460b3362017-03-30 16:40:47 -0700140}
141
Josh Gaocbe70cb2016-10-18 18:17:52 -0700142class CrasherTest : public ::testing::Test {
143 public:
144 pid_t crasher_pid = -1;
145 bool previous_wait_for_gdb;
146 unique_fd crasher_pipe;
147 unique_fd intercept_fd;
148
149 CrasherTest();
150 ~CrasherTest();
151
Narayan Kamatha73df602017-05-24 15:07:25 +0100152 void StartIntercept(unique_fd* output_fd, DebuggerdDumpType intercept_type = kDebuggerdTombstone);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700153
154 // Returns -1 if we fail to read a response from tombstoned, otherwise the received return code.
155 void FinishIntercept(int* result);
156
Josh Gao2e7b8e22017-05-04 17:12:57 -0700157 void StartProcess(std::function<void()> function, std::function<pid_t()> forker = fork);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700158 void StartCrasher(const std::string& crash_type);
159 void FinishCrasher();
160 void AssertDeath(int signo);
161};
162
163CrasherTest::CrasherTest() {
164 previous_wait_for_gdb = android::base::GetBoolProperty(kWaitForGdbKey, false);
165 android::base::SetProperty(kWaitForGdbKey, "0");
166}
167
168CrasherTest::~CrasherTest() {
169 if (crasher_pid != -1) {
170 kill(crasher_pid, SIGKILL);
171 int status;
172 waitpid(crasher_pid, &status, WUNTRACED);
173 }
174
175 android::base::SetProperty(kWaitForGdbKey, previous_wait_for_gdb ? "1" : "0");
176}
177
Narayan Kamatha73df602017-05-24 15:07:25 +0100178void CrasherTest::StartIntercept(unique_fd* output_fd, DebuggerdDumpType intercept_type) {
Josh Gaocbe70cb2016-10-18 18:17:52 -0700179 if (crasher_pid == -1) {
180 FAIL() << "crasher hasn't been started";
181 }
182
Narayan Kamathca5e9082017-06-02 15:42:06 +0100183 InterceptStatus status;
184 tombstoned_intercept(crasher_pid, &this->intercept_fd, output_fd, &status, intercept_type);
185 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700186}
187
188void CrasherTest::FinishIntercept(int* result) {
189 InterceptResponse response;
190
191 // Timeout for tombstoned intercept is 10 seconds.
192 ssize_t rc = TIMEOUT(20, read(intercept_fd.get(), &response, sizeof(response)));
193 if (rc == -1) {
194 FAIL() << "failed to read response from tombstoned: " << strerror(errno);
195 } else if (rc == 0) {
196 *result = -1;
197 } else if (rc != sizeof(response)) {
198 FAIL() << "received packet of unexpected length from tombstoned: expected " << sizeof(response)
199 << ", received " << rc;
200 } else {
Josh Gao460b3362017-03-30 16:40:47 -0700201 *result = response.status == InterceptStatus::kStarted ? 1 : 0;
Josh Gaocbe70cb2016-10-18 18:17:52 -0700202 }
203}
204
Josh Gao2e7b8e22017-05-04 17:12:57 -0700205void CrasherTest::StartProcess(std::function<void()> function, std::function<pid_t()> forker) {
Josh Gaofca7ca32017-01-23 12:05:35 -0800206 unique_fd read_pipe;
Josh Gaocbe70cb2016-10-18 18:17:52 -0700207 unique_fd crasher_read_pipe;
208 if (!Pipe(&crasher_read_pipe, &crasher_pipe)) {
209 FAIL() << "failed to create pipe: " << strerror(errno);
210 }
211
Josh Gao2e7b8e22017-05-04 17:12:57 -0700212 crasher_pid = forker();
Josh Gaocbe70cb2016-10-18 18:17:52 -0700213 if (crasher_pid == -1) {
214 FAIL() << "fork failed: " << strerror(errno);
215 } else if (crasher_pid == 0) {
Josh Gao502cfd22017-02-17 01:39:15 -0800216 char dummy;
217 crasher_pipe.reset();
218 TEMP_FAILURE_RETRY(read(crasher_read_pipe.get(), &dummy, 1));
Josh Gaofca7ca32017-01-23 12:05:35 -0800219 function();
220 _exit(0);
221 }
222}
223
Josh Gaocbe70cb2016-10-18 18:17:52 -0700224void CrasherTest::FinishCrasher() {
225 if (crasher_pipe == -1) {
226 FAIL() << "crasher pipe uninitialized";
227 }
228
229 ssize_t rc = write(crasher_pipe.get(), "\n", 1);
230 if (rc == -1) {
231 FAIL() << "failed to write to crasher pipe: " << strerror(errno);
232 } else if (rc == 0) {
233 FAIL() << "crasher pipe was closed";
234 }
235}
236
237void CrasherTest::AssertDeath(int signo) {
238 int status;
239 pid_t pid = TIMEOUT(5, waitpid(crasher_pid, &status, 0));
240 if (pid != crasher_pid) {
Josh Gao2b2ae0c2017-08-21 14:31:17 -0700241 printf("failed to wait for crasher (pid %d)\n", crasher_pid);
242 sleep(100);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700243 FAIL() << "failed to wait for crasher: " << strerror(errno);
244 }
245
Josh Gaoe06f2a42017-04-27 16:50:38 -0700246 if (signo == 0) {
247 ASSERT_TRUE(WIFEXITED(status));
248 ASSERT_EQ(0, WEXITSTATUS(signo));
249 } else {
250 ASSERT_FALSE(WIFEXITED(status));
251 ASSERT_TRUE(WIFSIGNALED(status)) << "crasher didn't terminate via a signal";
252 ASSERT_EQ(signo, WTERMSIG(status));
Josh Gaocbe70cb2016-10-18 18:17:52 -0700253 }
Josh Gaocbe70cb2016-10-18 18:17:52 -0700254 crasher_pid = -1;
255}
256
257static void ConsumeFd(unique_fd fd, std::string* output) {
258 constexpr size_t read_length = PAGE_SIZE;
259 std::string result;
260
261 while (true) {
262 size_t offset = result.size();
263 result.resize(result.size() + PAGE_SIZE);
264 ssize_t rc = TEMP_FAILURE_RETRY(read(fd.get(), &result[offset], read_length));
265 if (rc == -1) {
266 FAIL() << "read failed: " << strerror(errno);
267 } else if (rc == 0) {
268 result.resize(result.size() - PAGE_SIZE);
269 break;
270 }
271
272 result.resize(result.size() - PAGE_SIZE + rc);
273 }
274
275 *output = std::move(result);
276}
277
278TEST_F(CrasherTest, smoke) {
279 int intercept_result;
280 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800281 StartProcess([]() {
282 *reinterpret_cast<volatile char*>(0xdead) = '1';
283 });
284
Josh Gaocbe70cb2016-10-18 18:17:52 -0700285 StartIntercept(&output_fd);
286 FinishCrasher();
287 AssertDeath(SIGSEGV);
288 FinishIntercept(&intercept_result);
289
290 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
291
292 std::string result;
293 ConsumeFd(std::move(output_fd), &result);
294 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\), code 1 \(SEGV_MAPERR\), fault addr 0xdead)");
295}
296
Josh Gaocdea7502017-11-01 15:00:40 -0700297TEST_F(CrasherTest, LD_PRELOAD) {
298 int intercept_result;
299 unique_fd output_fd;
300 StartProcess([]() {
301 setenv("LD_PRELOAD", "nonexistent.so", 1);
302 *reinterpret_cast<volatile char*>(0xdead) = '1';
303 });
304
305 StartIntercept(&output_fd);
306 FinishCrasher();
307 AssertDeath(SIGSEGV);
308 FinishIntercept(&intercept_result);
309
310 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
311
312 std::string result;
313 ConsumeFd(std::move(output_fd), &result);
314 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\), code 1 \(SEGV_MAPERR\), fault addr 0xdead)");
315}
316
Josh Gaocbe70cb2016-10-18 18:17:52 -0700317TEST_F(CrasherTest, abort) {
318 int intercept_result;
319 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800320 StartProcess([]() {
321 abort();
322 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700323 StartIntercept(&output_fd);
324 FinishCrasher();
325 AssertDeath(SIGABRT);
326 FinishIntercept(&intercept_result);
327
328 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
329
330 std::string result;
331 ConsumeFd(std::move(output_fd), &result);
Andreas Gampe26cbafb2017-06-22 20:14:43 -0700332 ASSERT_BACKTRACE_FRAME(result, "abort");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700333}
334
335TEST_F(CrasherTest, signal) {
336 int intercept_result;
337 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800338 StartProcess([]() {
Josh Gao2b2ae0c2017-08-21 14:31:17 -0700339 while (true) {
340 sleep(1);
341 }
Josh Gao502cfd22017-02-17 01:39:15 -0800342 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700343 StartIntercept(&output_fd);
Josh Gao2b2ae0c2017-08-21 14:31:17 -0700344 FinishCrasher();
Josh Gaocbe70cb2016-10-18 18:17:52 -0700345 ASSERT_EQ(0, kill(crasher_pid, SIGSEGV));
346
347 AssertDeath(SIGSEGV);
348 FinishIntercept(&intercept_result);
349
350 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
351
352 std::string result;
353 ConsumeFd(std::move(output_fd), &result);
Elliott Hughes89722702018-05-02 10:47:00 -0700354 ASSERT_MATCH(
355 result,
356 R"(signal 11 \(SIGSEGV\), code 0 \(SI_USER from pid \d+, uid \d+\), fault addr --------)");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700357 ASSERT_MATCH(result, R"(backtrace:)");
358}
359
360TEST_F(CrasherTest, abort_message) {
361 int intercept_result;
362 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800363 StartProcess([]() {
Josh Gao1cc7bd82018-02-13 13:16:17 -0800364 // Arrived at experimentally;
365 // logd truncates at 4062.
366 // strlen("Abort message: ''") is 17.
367 // That's 4045, but we also want a NUL.
368 char buf[4045 + 1];
369 memset(buf, 'x', sizeof(buf));
370 buf[sizeof(buf) - 1] = '\0';
371 android_set_abort_message(buf);
Josh Gao502cfd22017-02-17 01:39:15 -0800372 abort();
373 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700374 StartIntercept(&output_fd);
375 FinishCrasher();
376 AssertDeath(SIGABRT);
377 FinishIntercept(&intercept_result);
378
379 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
380
381 std::string result;
382 ConsumeFd(std::move(output_fd), &result);
Josh Gao1cc7bd82018-02-13 13:16:17 -0800383 ASSERT_MATCH(result, R"(Abort message: 'x{4045}')");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700384}
385
Josh Gaoe06f2a42017-04-27 16:50:38 -0700386TEST_F(CrasherTest, abort_message_backtrace) {
387 int intercept_result;
388 unique_fd output_fd;
389 StartProcess([]() {
390 android_set_abort_message("not actually aborting");
391 raise(DEBUGGER_SIGNAL);
392 exit(0);
393 });
394 StartIntercept(&output_fd);
395 FinishCrasher();
396 AssertDeath(0);
397 FinishIntercept(&intercept_result);
398
399 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
400
401 std::string result;
402 ConsumeFd(std::move(output_fd), &result);
403 ASSERT_NOT_MATCH(result, R"(Abort message:)");
404}
405
Josh Gaocbe70cb2016-10-18 18:17:52 -0700406TEST_F(CrasherTest, intercept_timeout) {
407 int intercept_result;
408 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800409 StartProcess([]() {
410 abort();
411 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700412 StartIntercept(&output_fd);
413
414 // Don't let crasher finish until we timeout.
415 FinishIntercept(&intercept_result);
416
417 ASSERT_NE(1, intercept_result) << "tombstoned reported success? (intercept_result = "
418 << intercept_result << ")";
419
420 FinishCrasher();
421 AssertDeath(SIGABRT);
422}
423
424TEST_F(CrasherTest, wait_for_gdb) {
425 if (!android::base::SetProperty(kWaitForGdbKey, "1")) {
426 FAIL() << "failed to enable wait_for_gdb";
427 }
428 sleep(1);
429
Josh Gao502cfd22017-02-17 01:39:15 -0800430 StartProcess([]() {
431 abort();
432 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700433 FinishCrasher();
434
435 int status;
436 ASSERT_EQ(crasher_pid, waitpid(crasher_pid, &status, WUNTRACED));
437 ASSERT_TRUE(WIFSTOPPED(status));
438 ASSERT_EQ(SIGSTOP, WSTOPSIG(status));
439
440 ASSERT_EQ(0, kill(crasher_pid, SIGCONT));
441
442 AssertDeath(SIGABRT);
443}
444
Josh Gaocbe70cb2016-10-18 18:17:52 -0700445TEST_F(CrasherTest, backtrace) {
446 std::string result;
447 int intercept_result;
448 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800449
450 StartProcess([]() {
451 abort();
452 });
Narayan Kamatha73df602017-05-24 15:07:25 +0100453 StartIntercept(&output_fd, kDebuggerdNativeBacktrace);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700454
455 std::this_thread::sleep_for(500ms);
456
457 sigval val;
458 val.sival_int = 1;
459 ASSERT_EQ(0, sigqueue(crasher_pid, DEBUGGER_SIGNAL, val)) << strerror(errno);
460 FinishIntercept(&intercept_result);
461 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
462 ConsumeFd(std::move(output_fd), &result);
Jaesung Chung58778e12017-06-15 18:20:34 +0900463 ASSERT_BACKTRACE_FRAME(result, "read");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700464
465 int status;
466 ASSERT_EQ(0, waitpid(crasher_pid, &status, WNOHANG | WUNTRACED));
467
468 StartIntercept(&output_fd);
469 FinishCrasher();
470 AssertDeath(SIGABRT);
471 FinishIntercept(&intercept_result);
472 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
473 ConsumeFd(std::move(output_fd), &result);
Andreas Gampe26cbafb2017-06-22 20:14:43 -0700474 ASSERT_BACKTRACE_FRAME(result, "abort");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700475}
Josh Gaofca7ca32017-01-23 12:05:35 -0800476
477TEST_F(CrasherTest, PR_SET_DUMPABLE_0_crash) {
Josh Gao502cfd22017-02-17 01:39:15 -0800478 int intercept_result;
479 unique_fd output_fd;
Josh Gaofca7ca32017-01-23 12:05:35 -0800480 StartProcess([]() {
481 prctl(PR_SET_DUMPABLE, 0);
Josh Gao502cfd22017-02-17 01:39:15 -0800482 abort();
Josh Gaofca7ca32017-01-23 12:05:35 -0800483 });
Josh Gao502cfd22017-02-17 01:39:15 -0800484
485 StartIntercept(&output_fd);
486 FinishCrasher();
487 AssertDeath(SIGABRT);
488 FinishIntercept(&intercept_result);
489
490 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
491
492 std::string result;
493 ConsumeFd(std::move(output_fd), &result);
Andreas Gampe26cbafb2017-06-22 20:14:43 -0700494 ASSERT_BACKTRACE_FRAME(result, "abort");
Josh Gaofca7ca32017-01-23 12:05:35 -0800495}
496
Josh Gao502cfd22017-02-17 01:39:15 -0800497TEST_F(CrasherTest, capabilities) {
498 ASSERT_EQ(0U, getuid()) << "capability test requires root";
499
Josh Gaofca7ca32017-01-23 12:05:35 -0800500 StartProcess([]() {
Josh Gao502cfd22017-02-17 01:39:15 -0800501 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) != 0) {
502 err(1, "failed to set PR_SET_KEEPCAPS");
503 }
504
505 if (setresuid(1, 1, 1) != 0) {
506 err(1, "setresuid failed");
507 }
508
509 __user_cap_header_struct capheader;
510 __user_cap_data_struct capdata[2];
511 memset(&capheader, 0, sizeof(capheader));
512 memset(&capdata, 0, sizeof(capdata));
513
514 capheader.version = _LINUX_CAPABILITY_VERSION_3;
515 capheader.pid = 0;
516
517 // Turn on every third capability.
518 static_assert(CAP_LAST_CAP > 33, "CAP_LAST_CAP <= 32");
519 for (int i = 0; i < CAP_LAST_CAP; i += 3) {
520 capdata[CAP_TO_INDEX(i)].permitted |= CAP_TO_MASK(i);
521 capdata[CAP_TO_INDEX(i)].effective |= CAP_TO_MASK(i);
522 }
523
524 // Make sure CAP_SYS_PTRACE is off.
525 capdata[CAP_TO_INDEX(CAP_SYS_PTRACE)].permitted &= ~(CAP_TO_MASK(CAP_SYS_PTRACE));
526 capdata[CAP_TO_INDEX(CAP_SYS_PTRACE)].effective &= ~(CAP_TO_MASK(CAP_SYS_PTRACE));
527
528 if (capset(&capheader, &capdata[0]) != 0) {
529 err(1, "capset failed");
530 }
531
532 if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_CLEAR_ALL, 0, 0, 0) != 0) {
533 err(1, "failed to drop ambient capabilities");
534 }
535
Josh Gaoa5199a92017-04-03 13:18:34 -0700536 pthread_setname_np(pthread_self(), "thread_name");
Josh Gao502cfd22017-02-17 01:39:15 -0800537 raise(SIGSYS);
Josh Gaofca7ca32017-01-23 12:05:35 -0800538 });
Josh Gao502cfd22017-02-17 01:39:15 -0800539
540 unique_fd output_fd;
541 StartIntercept(&output_fd);
542 FinishCrasher();
543 AssertDeath(SIGSYS);
544
545 std::string result;
546 int intercept_result;
547 FinishIntercept(&intercept_result);
548 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
549 ConsumeFd(std::move(output_fd), &result);
Josh Gaoa5199a92017-04-03 13:18:34 -0700550 ASSERT_MATCH(result, R"(name: thread_name\s+>>> .+debuggerd_test(32|64) <<<)");
Jaesung Chung58778e12017-06-15 18:20:34 +0900551 ASSERT_BACKTRACE_FRAME(result, "tgkill");
Josh Gaofca7ca32017-01-23 12:05:35 -0800552}
Josh Gaoc3c8c022017-02-13 16:36:18 -0800553
Josh Gao2e7b8e22017-05-04 17:12:57 -0700554TEST_F(CrasherTest, fake_pid) {
555 int intercept_result;
556 unique_fd output_fd;
557
558 // Prime the getpid/gettid caches.
559 UNUSED(getpid());
560 UNUSED(gettid());
561
562 std::function<pid_t()> clone_fn = []() {
563 return syscall(__NR_clone, SIGCHLD, nullptr, nullptr, nullptr, nullptr);
564 };
565 StartProcess(
566 []() {
567 ASSERT_NE(getpid(), syscall(__NR_getpid));
568 ASSERT_NE(gettid(), syscall(__NR_gettid));
569 raise(SIGSEGV);
570 },
571 clone_fn);
572
573 StartIntercept(&output_fd);
574 FinishCrasher();
575 AssertDeath(SIGSEGV);
576 FinishIntercept(&intercept_result);
577
578 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
579
580 std::string result;
581 ConsumeFd(std::move(output_fd), &result);
Jaesung Chung58778e12017-06-15 18:20:34 +0900582 ASSERT_BACKTRACE_FRAME(result, "tgkill");
Josh Gao2e7b8e22017-05-04 17:12:57 -0700583}
584
Josh Gaoe04ca272018-01-16 15:38:17 -0800585static const char* const kDebuggerdSeccompPolicy =
586 "/system/etc/seccomp_policy/crash_dump." ABI_STRING ".policy";
587
Josh Gao70adac62018-02-22 11:38:33 -0800588static pid_t seccomp_fork_impl(void (*prejail)()) {
Josh Gaoe04ca272018-01-16 15:38:17 -0800589 unique_fd policy_fd(open(kDebuggerdSeccompPolicy, O_RDONLY | O_CLOEXEC));
590 if (policy_fd == -1) {
591 LOG(FATAL) << "failed to open policy " << kDebuggerdSeccompPolicy;
592 }
593
594 ScopedMinijail jail{minijail_new()};
595 if (!jail) {
596 LOG(FATAL) << "failed to create minijail";
597 }
598
599 minijail_no_new_privs(jail.get());
600 minijail_log_seccomp_filter_failures(jail.get());
601 minijail_use_seccomp_filter(jail.get());
602 minijail_parse_seccomp_filters_from_fd(jail.get(), policy_fd.release());
603
604 pid_t result = fork();
605 if (result == -1) {
606 return result;
607 } else if (result != 0) {
608 return result;
609 }
610
611 // Spawn and detach a thread that spins forever.
612 std::atomic<bool> thread_ready(false);
613 std::thread thread([&jail, &thread_ready]() {
614 minijail_enter(jail.get());
615 thread_ready = true;
616 for (;;)
617 ;
618 });
619 thread.detach();
620
621 while (!thread_ready) {
622 continue;
623 }
624
Josh Gao70adac62018-02-22 11:38:33 -0800625 if (prejail) {
626 prejail();
627 }
628
Josh Gaoe04ca272018-01-16 15:38:17 -0800629 minijail_enter(jail.get());
630 return result;
631}
632
Josh Gao70adac62018-02-22 11:38:33 -0800633static pid_t seccomp_fork() {
634 return seccomp_fork_impl(nullptr);
635}
636
Josh Gaoe04ca272018-01-16 15:38:17 -0800637TEST_F(CrasherTest, seccomp_crash) {
638 int intercept_result;
639 unique_fd output_fd;
640
641 StartProcess([]() { abort(); }, &seccomp_fork);
642
643 StartIntercept(&output_fd);
644 FinishCrasher();
645 AssertDeath(SIGABRT);
646 FinishIntercept(&intercept_result);
647 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
648
649 std::string result;
650 ConsumeFd(std::move(output_fd), &result);
651 ASSERT_BACKTRACE_FRAME(result, "abort");
652}
653
Josh Gao70adac62018-02-22 11:38:33 -0800654static pid_t seccomp_fork_rlimit() {
655 return seccomp_fork_impl([]() {
656 struct rlimit rlim = {
657 .rlim_cur = 512 * 1024 * 1024,
658 .rlim_max = 512 * 1024 * 1024,
659 };
660
661 if (setrlimit(RLIMIT_AS, &rlim) != 0) {
662 raise(SIGINT);
663 }
664 });
665}
666
667TEST_F(CrasherTest, seccomp_crash_oom) {
668 int intercept_result;
669 unique_fd output_fd;
670
671 StartProcess(
672 []() {
673 std::vector<void*> vec;
674 for (int i = 0; i < 512; ++i) {
675 char* buf = static_cast<char*>(malloc(1024 * 1024));
676 if (!buf) {
677 abort();
678 }
679 memset(buf, 0xff, 1024 * 1024);
680 vec.push_back(buf);
681 }
682 },
683 &seccomp_fork_rlimit);
684
685 StartIntercept(&output_fd);
686 FinishCrasher();
687 AssertDeath(SIGABRT);
688 FinishIntercept(&intercept_result);
689 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
690
691 // We can't actually generate a backtrace, just make sure that the process terminates.
692}
693
Josh Gaoe04ca272018-01-16 15:38:17 -0800694__attribute__((noinline)) extern "C" bool raise_debugger_signal(DebuggerdDumpType dump_type) {
695 siginfo_t siginfo;
696 siginfo.si_code = SI_QUEUE;
697 siginfo.si_pid = getpid();
698 siginfo.si_uid = getuid();
699
700 if (dump_type != kDebuggerdNativeBacktrace && dump_type != kDebuggerdTombstone) {
701 PLOG(FATAL) << "invalid dump type";
702 }
703
704 siginfo.si_value.sival_int = dump_type == kDebuggerdNativeBacktrace;
705
706 if (syscall(__NR_rt_tgsigqueueinfo, getpid(), gettid(), DEBUGGER_SIGNAL, &siginfo) != 0) {
707 PLOG(ERROR) << "libdebuggerd_client: failed to send signal to self";
708 return false;
709 }
710
711 return true;
712}
713
714TEST_F(CrasherTest, seccomp_tombstone) {
715 int intercept_result;
716 unique_fd output_fd;
717
718 static const auto dump_type = kDebuggerdTombstone;
719 StartProcess(
720 []() {
721 raise_debugger_signal(dump_type);
722 _exit(0);
723 },
724 &seccomp_fork);
725
726 StartIntercept(&output_fd, dump_type);
727 FinishCrasher();
728 AssertDeath(0);
729 FinishIntercept(&intercept_result);
730 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
731
732 std::string result;
733 ConsumeFd(std::move(output_fd), &result);
734 ASSERT_BACKTRACE_FRAME(result, "raise_debugger_signal");
735}
736
737TEST_F(CrasherTest, seccomp_backtrace) {
738 int intercept_result;
739 unique_fd output_fd;
740
741 static const auto dump_type = kDebuggerdNativeBacktrace;
742 StartProcess(
743 []() {
744 raise_debugger_signal(dump_type);
745 _exit(0);
746 },
747 &seccomp_fork);
748
749 StartIntercept(&output_fd, dump_type);
750 FinishCrasher();
751 AssertDeath(0);
752 FinishIntercept(&intercept_result);
753 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
754
755 std::string result;
756 ConsumeFd(std::move(output_fd), &result);
757 ASSERT_BACKTRACE_FRAME(result, "raise_debugger_signal");
758}
759
760TEST_F(CrasherTest, seccomp_crash_logcat) {
761 StartProcess([]() { abort(); }, &seccomp_fork);
762 FinishCrasher();
763
764 // Make sure we don't get SIGSYS when trying to dump a crash to logcat.
765 AssertDeath(SIGABRT);
766}
767
Josh Gaofd13bf02017-08-18 15:37:26 -0700768TEST_F(CrasherTest, competing_tracer) {
769 int intercept_result;
770 unique_fd output_fd;
771 StartProcess([]() {
Josh Gao2b2ae0c2017-08-21 14:31:17 -0700772 raise(SIGABRT);
Josh Gaofd13bf02017-08-18 15:37:26 -0700773 });
774
775 StartIntercept(&output_fd);
Josh Gaofd13bf02017-08-18 15:37:26 -0700776
777 ASSERT_EQ(0, ptrace(PTRACE_SEIZE, crasher_pid, 0, 0));
Josh Gao2b2ae0c2017-08-21 14:31:17 -0700778 FinishCrasher();
Josh Gaofd13bf02017-08-18 15:37:26 -0700779
780 int status;
781 ASSERT_EQ(crasher_pid, waitpid(crasher_pid, &status, 0));
782 ASSERT_TRUE(WIFSTOPPED(status));
783 ASSERT_EQ(SIGABRT, WSTOPSIG(status));
784
785 ASSERT_EQ(0, ptrace(PTRACE_CONT, crasher_pid, 0, SIGABRT));
786 FinishIntercept(&intercept_result);
787 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
788
789 std::string result;
790 ConsumeFd(std::move(output_fd), &result);
791 std::string regex = R"(failed to attach to thread \d+, already traced by )";
792 regex += std::to_string(gettid());
793 regex += R"( \(.+debuggerd_test)";
794 ASSERT_MATCH(result, regex.c_str());
795
Josh Gao2b2ae0c2017-08-21 14:31:17 -0700796 ASSERT_EQ(crasher_pid, waitpid(crasher_pid, &status, 0));
797 ASSERT_TRUE(WIFSTOPPED(status));
798 ASSERT_EQ(SIGABRT, WSTOPSIG(status));
799
Josh Gaofd13bf02017-08-18 15:37:26 -0700800 ASSERT_EQ(0, ptrace(PTRACE_DETACH, crasher_pid, 0, SIGABRT));
801 AssertDeath(SIGABRT);
802}
803
Josh Gaoc3c8c022017-02-13 16:36:18 -0800804TEST(crash_dump, zombie) {
805 pid_t forkpid = fork();
806
Josh Gaoc3c8c022017-02-13 16:36:18 -0800807 pid_t rc;
808 int status;
809
810 if (forkpid == 0) {
811 errno = 0;
812 rc = waitpid(-1, &status, WNOHANG | __WALL | __WNOTHREAD);
813 if (rc != -1 || errno != ECHILD) {
814 errx(2, "first waitpid returned %d (%s), expected failure with ECHILD", rc, strerror(errno));
815 }
816
817 raise(DEBUGGER_SIGNAL);
818
819 errno = 0;
820 rc = waitpid(-1, &status, __WALL | __WNOTHREAD);
821 if (rc != -1 || errno != ECHILD) {
822 errx(2, "second waitpid returned %d (%s), expected failure with ECHILD", rc, strerror(errno));
823 }
824 _exit(0);
825 } else {
826 rc = waitpid(forkpid, &status, 0);
827 ASSERT_EQ(forkpid, rc);
828 ASSERT_TRUE(WIFEXITED(status));
829 ASSERT_EQ(0, WEXITSTATUS(status));
830 }
831}
Josh Gao352a8452017-03-30 16:46:21 -0700832
833TEST(tombstoned, no_notify) {
834 // Do this a few times.
835 for (int i = 0; i < 3; ++i) {
836 pid_t pid = 123'456'789 + i;
837
838 unique_fd intercept_fd, output_fd;
Narayan Kamathca5e9082017-06-02 15:42:06 +0100839 InterceptStatus status;
840 tombstoned_intercept(pid, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
841 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gao352a8452017-03-30 16:46:21 -0700842
843 {
844 unique_fd tombstoned_socket, input_fd;
Narayan Kamatha73df602017-05-24 15:07:25 +0100845 ASSERT_TRUE(tombstoned_connect(pid, &tombstoned_socket, &input_fd, kDebuggerdTombstone));
Josh Gao352a8452017-03-30 16:46:21 -0700846 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), &pid, sizeof(pid)));
847 }
848
849 pid_t read_pid;
850 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), &read_pid, sizeof(read_pid)));
851 ASSERT_EQ(read_pid, pid);
852 }
853}
854
855TEST(tombstoned, stress) {
856 // Spawn threads to simultaneously do a bunch of failing dumps and a bunch of successful dumps.
857 static constexpr int kDumpCount = 100;
858
859 std::atomic<bool> start(false);
860 std::vector<std::thread> threads;
861 threads.emplace_back([&start]() {
862 while (!start) {
863 continue;
864 }
865
866 // Use a way out of range pid, to avoid stomping on an actual process.
867 pid_t pid_base = 1'000'000;
868
869 for (int dump = 0; dump < kDumpCount; ++dump) {
870 pid_t pid = pid_base + dump;
871
872 unique_fd intercept_fd, output_fd;
Narayan Kamathca5e9082017-06-02 15:42:06 +0100873 InterceptStatus status;
874 tombstoned_intercept(pid, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
875 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gao352a8452017-03-30 16:46:21 -0700876
877 // Pretend to crash, and then immediately close the socket.
878 unique_fd sockfd(socket_local_client(kTombstonedCrashSocketName,
879 ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_SEQPACKET));
880 if (sockfd == -1) {
881 FAIL() << "failed to connect to tombstoned: " << strerror(errno);
882 }
883 TombstonedCrashPacket packet = {};
884 packet.packet_type = CrashPacketType::kDumpRequest;
885 packet.packet.dump_request.pid = pid;
886 if (TEMP_FAILURE_RETRY(write(sockfd, &packet, sizeof(packet))) != sizeof(packet)) {
887 FAIL() << "failed to write to tombstoned: " << strerror(errno);
888 }
889
890 continue;
891 }
892 });
893
894 threads.emplace_back([&start]() {
895 while (!start) {
896 continue;
897 }
898
899 // Use a way out of range pid, to avoid stomping on an actual process.
900 pid_t pid_base = 2'000'000;
901
902 for (int dump = 0; dump < kDumpCount; ++dump) {
903 pid_t pid = pid_base + dump;
904
905 unique_fd intercept_fd, output_fd;
Narayan Kamathca5e9082017-06-02 15:42:06 +0100906 InterceptStatus status;
907 tombstoned_intercept(pid, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
908 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gao352a8452017-03-30 16:46:21 -0700909
910 {
911 unique_fd tombstoned_socket, input_fd;
Narayan Kamatha73df602017-05-24 15:07:25 +0100912 ASSERT_TRUE(tombstoned_connect(pid, &tombstoned_socket, &input_fd, kDebuggerdTombstone));
Josh Gao352a8452017-03-30 16:46:21 -0700913 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), &pid, sizeof(pid)));
914 tombstoned_notify_completion(tombstoned_socket.get());
915 }
916
917 // TODO: Fix the race that requires this sleep.
918 std::this_thread::sleep_for(50ms);
919
920 pid_t read_pid;
921 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), &read_pid, sizeof(read_pid)));
922 ASSERT_EQ(read_pid, pid);
923 }
924 });
925
926 start = true;
927
928 for (std::thread& thread : threads) {
929 thread.join();
930 }
931}
Narayan Kamathca5e9082017-06-02 15:42:06 +0100932
933TEST(tombstoned, java_trace_intercept_smoke) {
934 // Using a "real" PID is a little dangerous here - if the test fails
935 // or crashes, we might end up getting a bogus / unreliable stack
936 // trace.
937 const pid_t self = getpid();
938
939 unique_fd intercept_fd, output_fd;
940 InterceptStatus status;
941 tombstoned_intercept(self, &intercept_fd, &output_fd, &status, kDebuggerdJavaBacktrace);
942 ASSERT_EQ(InterceptStatus::kRegistered, status);
943
944 // First connect to tombstoned requesting a native backtrace. This
945 // should result in a "regular" FD and not the installed intercept.
946 const char native[] = "native";
947 unique_fd tombstoned_socket, input_fd;
948 ASSERT_TRUE(tombstoned_connect(self, &tombstoned_socket, &input_fd, kDebuggerdNativeBacktrace));
949 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), native, sizeof(native)));
950 tombstoned_notify_completion(tombstoned_socket.get());
951
952 // Then, connect to tombstoned asking for a java backtrace. This *should*
953 // trigger the intercept.
954 const char java[] = "java";
955 ASSERT_TRUE(tombstoned_connect(self, &tombstoned_socket, &input_fd, kDebuggerdJavaBacktrace));
956 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), java, sizeof(java)));
957 tombstoned_notify_completion(tombstoned_socket.get());
958
959 char outbuf[sizeof(java)];
960 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), outbuf, sizeof(outbuf)));
961 ASSERT_STREQ("java", outbuf);
962}
963
964TEST(tombstoned, multiple_intercepts) {
965 const pid_t fake_pid = 1'234'567;
966 unique_fd intercept_fd, output_fd;
967 InterceptStatus status;
968 tombstoned_intercept(fake_pid, &intercept_fd, &output_fd, &status, kDebuggerdJavaBacktrace);
969 ASSERT_EQ(InterceptStatus::kRegistered, status);
970
971 unique_fd intercept_fd_2, output_fd_2;
972 tombstoned_intercept(fake_pid, &intercept_fd_2, &output_fd_2, &status, kDebuggerdNativeBacktrace);
973 ASSERT_EQ(InterceptStatus::kFailedAlreadyRegistered, status);
974}
975
976TEST(tombstoned, intercept_any) {
977 const pid_t fake_pid = 1'234'567;
978
979 unique_fd intercept_fd, output_fd;
980 InterceptStatus status;
981 tombstoned_intercept(fake_pid, &intercept_fd, &output_fd, &status, kDebuggerdNativeBacktrace);
982 ASSERT_EQ(InterceptStatus::kRegistered, status);
983
984 const char any[] = "any";
985 unique_fd tombstoned_socket, input_fd;
986 ASSERT_TRUE(tombstoned_connect(fake_pid, &tombstoned_socket, &input_fd, kDebuggerdAnyIntercept));
987 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), any, sizeof(any)));
988 tombstoned_notify_completion(tombstoned_socket.get());
989
990 char outbuf[sizeof(any)];
991 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), outbuf, sizeof(outbuf)));
992 ASSERT_STREQ("any", outbuf);
993}