blob: dbf81a4eea95cd3fcd767f69aace13c756f29c6e [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 Gao502cfd22017-02-17 01:39:15 -080019#include <sys/capability.h>
Josh Gaofca7ca32017-01-23 12:05:35 -080020#include <sys/prctl.h>
Josh Gaofd13bf02017-08-18 15:37:26 -070021#include <sys/ptrace.h>
Josh Gaocbe70cb2016-10-18 18:17:52 -070022#include <sys/types.h>
Josh Gaofd13bf02017-08-18 15:37:26 -070023#include <unistd.h>
Josh Gaocbe70cb2016-10-18 18:17:52 -070024
25#include <chrono>
26#include <regex>
27#include <thread>
28
Josh Gao502cfd22017-02-17 01:39:15 -080029#include <android/set_abort_message.h>
30
Josh Gaocbe70cb2016-10-18 18:17:52 -070031#include <android-base/file.h>
32#include <android-base/logging.h>
Josh Gao2e7b8e22017-05-04 17:12:57 -070033#include <android-base/macros.h>
Josh Gaocbe70cb2016-10-18 18:17:52 -070034#include <android-base/parseint.h>
35#include <android-base/properties.h>
36#include <android-base/strings.h>
37#include <android-base/unique_fd.h>
38#include <cutils/sockets.h>
Josh Gaocbe70cb2016-10-18 18:17:52 -070039#include <gtest/gtest.h>
40
Narayan Kamath2d377cd2017-05-10 10:58:59 +010041#include "debuggerd/handler.h"
42#include "protocol.h"
43#include "tombstoned/tombstoned.h"
44#include "util.h"
45
Josh Gaocbe70cb2016-10-18 18:17:52 -070046using namespace std::chrono_literals;
47using android::base::unique_fd;
48
49#if defined(__LP64__)
Josh Gaocbe70cb2016-10-18 18:17:52 -070050#define ARCH_SUFFIX "64"
51#else
Josh Gaocbe70cb2016-10-18 18:17:52 -070052#define ARCH_SUFFIX ""
53#endif
54
55constexpr char kWaitForGdbKey[] = "debug.debuggerd.wait_for_gdb";
56
57#define TIMEOUT(seconds, expr) \
58 [&]() { \
59 struct sigaction old_sigaction; \
60 struct sigaction new_sigaction = {}; \
61 new_sigaction.sa_handler = [](int) {}; \
62 if (sigaction(SIGALRM, &new_sigaction, &new_sigaction) != 0) { \
63 err(1, "sigaction failed"); \
64 } \
65 alarm(seconds); \
66 auto value = expr; \
67 int saved_errno = errno; \
68 if (sigaction(SIGALRM, &old_sigaction, nullptr) != 0) { \
69 err(1, "sigaction failed"); \
70 } \
71 alarm(0); \
72 errno = saved_errno; \
73 return value; \
74 }()
75
76#define ASSERT_MATCH(str, pattern) \
77 do { \
78 std::regex r((pattern)); \
79 if (!std::regex_search((str), r)) { \
80 FAIL() << "regex mismatch: expected " << (pattern) << " in: \n" << (str); \
81 } \
82 } while (0)
83
Josh Gaoe06f2a42017-04-27 16:50:38 -070084#define ASSERT_NOT_MATCH(str, pattern) \
85 do { \
86 std::regex r((pattern)); \
87 if (std::regex_search((str), r)) { \
88 FAIL() << "regex mismatch: expected to not find " << (pattern) << " in: \n" << (str); \
89 } \
90 } while (0)
91
Jaesung Chung58778e12017-06-15 18:20:34 +090092#define ASSERT_BACKTRACE_FRAME(result, frame_name) \
93 ASSERT_MATCH(result, R"(#\d\d pc [0-9a-f]+\s+ /system/lib)" ARCH_SUFFIX \
94 R"(/libc.so \()" frame_name R"(\+)")
95
Narayan Kamatha73df602017-05-24 15:07:25 +010096static void tombstoned_intercept(pid_t target_pid, unique_fd* intercept_fd, unique_fd* output_fd,
Narayan Kamathca5e9082017-06-02 15:42:06 +010097 InterceptStatus* status, DebuggerdDumpType intercept_type) {
Josh Gao460b3362017-03-30 16:40:47 -070098 intercept_fd->reset(socket_local_client(kTombstonedInterceptSocketName,
99 ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_SEQPACKET));
100 if (intercept_fd->get() == -1) {
101 FAIL() << "failed to contact tombstoned: " << strerror(errno);
102 }
103
Narayan Kamatha73df602017-05-24 15:07:25 +0100104 InterceptRequest req = {.pid = target_pid, .dump_type = intercept_type};
Josh Gao460b3362017-03-30 16:40:47 -0700105
106 unique_fd output_pipe_write;
107 if (!Pipe(output_fd, &output_pipe_write)) {
108 FAIL() << "failed to create output pipe: " << strerror(errno);
109 }
110
111 std::string pipe_size_str;
112 int pipe_buffer_size;
113 if (!android::base::ReadFileToString("/proc/sys/fs/pipe-max-size", &pipe_size_str)) {
114 FAIL() << "failed to read /proc/sys/fs/pipe-max-size: " << strerror(errno);
115 }
116
117 pipe_size_str = android::base::Trim(pipe_size_str);
118
119 if (!android::base::ParseInt(pipe_size_str.c_str(), &pipe_buffer_size, 0)) {
120 FAIL() << "failed to parse pipe max size";
121 }
122
123 if (fcntl(output_fd->get(), F_SETPIPE_SZ, pipe_buffer_size) != pipe_buffer_size) {
124 FAIL() << "failed to set pipe size: " << strerror(errno);
125 }
126
Josh Gao5675f3c2017-06-01 12:19:53 -0700127 ASSERT_GE(pipe_buffer_size, 1024 * 1024);
128
Josh Gao460b3362017-03-30 16:40:47 -0700129 if (send_fd(intercept_fd->get(), &req, sizeof(req), std::move(output_pipe_write)) != sizeof(req)) {
130 FAIL() << "failed to send output fd to tombstoned: " << strerror(errno);
131 }
132
133 InterceptResponse response;
134 ssize_t rc = TEMP_FAILURE_RETRY(read(intercept_fd->get(), &response, sizeof(response)));
135 if (rc == -1) {
136 FAIL() << "failed to read response from tombstoned: " << strerror(errno);
137 } else if (rc == 0) {
138 FAIL() << "failed to read response from tombstoned (EOF)";
139 } else if (rc != sizeof(response)) {
140 FAIL() << "received packet of unexpected length from tombstoned: expected " << sizeof(response)
141 << ", received " << rc;
142 }
143
Narayan Kamathca5e9082017-06-02 15:42:06 +0100144 *status = response.status;
Josh Gao460b3362017-03-30 16:40:47 -0700145}
146
Josh Gaocbe70cb2016-10-18 18:17:52 -0700147class CrasherTest : public ::testing::Test {
148 public:
149 pid_t crasher_pid = -1;
150 bool previous_wait_for_gdb;
151 unique_fd crasher_pipe;
152 unique_fd intercept_fd;
153
154 CrasherTest();
155 ~CrasherTest();
156
Narayan Kamatha73df602017-05-24 15:07:25 +0100157 void StartIntercept(unique_fd* output_fd, DebuggerdDumpType intercept_type = kDebuggerdTombstone);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700158
159 // Returns -1 if we fail to read a response from tombstoned, otherwise the received return code.
160 void FinishIntercept(int* result);
161
Josh Gao2e7b8e22017-05-04 17:12:57 -0700162 void StartProcess(std::function<void()> function, std::function<pid_t()> forker = fork);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700163 void StartCrasher(const std::string& crash_type);
164 void FinishCrasher();
165 void AssertDeath(int signo);
166};
167
168CrasherTest::CrasherTest() {
169 previous_wait_for_gdb = android::base::GetBoolProperty(kWaitForGdbKey, false);
170 android::base::SetProperty(kWaitForGdbKey, "0");
171}
172
173CrasherTest::~CrasherTest() {
174 if (crasher_pid != -1) {
175 kill(crasher_pid, SIGKILL);
176 int status;
177 waitpid(crasher_pid, &status, WUNTRACED);
178 }
179
180 android::base::SetProperty(kWaitForGdbKey, previous_wait_for_gdb ? "1" : "0");
181}
182
Narayan Kamatha73df602017-05-24 15:07:25 +0100183void CrasherTest::StartIntercept(unique_fd* output_fd, DebuggerdDumpType intercept_type) {
Josh Gaocbe70cb2016-10-18 18:17:52 -0700184 if (crasher_pid == -1) {
185 FAIL() << "crasher hasn't been started";
186 }
187
Narayan Kamathca5e9082017-06-02 15:42:06 +0100188 InterceptStatus status;
189 tombstoned_intercept(crasher_pid, &this->intercept_fd, output_fd, &status, intercept_type);
190 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700191}
192
193void CrasherTest::FinishIntercept(int* result) {
194 InterceptResponse response;
195
196 // Timeout for tombstoned intercept is 10 seconds.
197 ssize_t rc = TIMEOUT(20, read(intercept_fd.get(), &response, sizeof(response)));
198 if (rc == -1) {
199 FAIL() << "failed to read response from tombstoned: " << strerror(errno);
200 } else if (rc == 0) {
201 *result = -1;
202 } else if (rc != sizeof(response)) {
203 FAIL() << "received packet of unexpected length from tombstoned: expected " << sizeof(response)
204 << ", received " << rc;
205 } else {
Josh Gao460b3362017-03-30 16:40:47 -0700206 *result = response.status == InterceptStatus::kStarted ? 1 : 0;
Josh Gaocbe70cb2016-10-18 18:17:52 -0700207 }
208}
209
Josh Gao2e7b8e22017-05-04 17:12:57 -0700210void CrasherTest::StartProcess(std::function<void()> function, std::function<pid_t()> forker) {
Josh Gaofca7ca32017-01-23 12:05:35 -0800211 unique_fd read_pipe;
Josh Gaocbe70cb2016-10-18 18:17:52 -0700212 unique_fd crasher_read_pipe;
213 if (!Pipe(&crasher_read_pipe, &crasher_pipe)) {
214 FAIL() << "failed to create pipe: " << strerror(errno);
215 }
216
Josh Gao2e7b8e22017-05-04 17:12:57 -0700217 crasher_pid = forker();
Josh Gaocbe70cb2016-10-18 18:17:52 -0700218 if (crasher_pid == -1) {
219 FAIL() << "fork failed: " << strerror(errno);
220 } else if (crasher_pid == 0) {
Josh Gao502cfd22017-02-17 01:39:15 -0800221 char dummy;
222 crasher_pipe.reset();
223 TEMP_FAILURE_RETRY(read(crasher_read_pipe.get(), &dummy, 1));
Josh Gaofca7ca32017-01-23 12:05:35 -0800224 function();
225 _exit(0);
226 }
227}
228
Josh Gaocbe70cb2016-10-18 18:17:52 -0700229void CrasherTest::FinishCrasher() {
230 if (crasher_pipe == -1) {
231 FAIL() << "crasher pipe uninitialized";
232 }
233
234 ssize_t rc = write(crasher_pipe.get(), "\n", 1);
235 if (rc == -1) {
236 FAIL() << "failed to write to crasher pipe: " << strerror(errno);
237 } else if (rc == 0) {
238 FAIL() << "crasher pipe was closed";
239 }
240}
241
242void CrasherTest::AssertDeath(int signo) {
243 int status;
244 pid_t pid = TIMEOUT(5, waitpid(crasher_pid, &status, 0));
245 if (pid != crasher_pid) {
246 FAIL() << "failed to wait for crasher: " << strerror(errno);
247 }
248
Josh Gaoe06f2a42017-04-27 16:50:38 -0700249 if (signo == 0) {
250 ASSERT_TRUE(WIFEXITED(status));
251 ASSERT_EQ(0, WEXITSTATUS(signo));
252 } else {
253 ASSERT_FALSE(WIFEXITED(status));
254 ASSERT_TRUE(WIFSIGNALED(status)) << "crasher didn't terminate via a signal";
255 ASSERT_EQ(signo, WTERMSIG(status));
Josh Gaocbe70cb2016-10-18 18:17:52 -0700256 }
Josh Gaocbe70cb2016-10-18 18:17:52 -0700257 crasher_pid = -1;
258}
259
260static void ConsumeFd(unique_fd fd, std::string* output) {
261 constexpr size_t read_length = PAGE_SIZE;
262 std::string result;
263
264 while (true) {
265 size_t offset = result.size();
266 result.resize(result.size() + PAGE_SIZE);
267 ssize_t rc = TEMP_FAILURE_RETRY(read(fd.get(), &result[offset], read_length));
268 if (rc == -1) {
269 FAIL() << "read failed: " << strerror(errno);
270 } else if (rc == 0) {
271 result.resize(result.size() - PAGE_SIZE);
272 break;
273 }
274
275 result.resize(result.size() - PAGE_SIZE + rc);
276 }
277
278 *output = std::move(result);
279}
280
281TEST_F(CrasherTest, smoke) {
282 int intercept_result;
283 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800284 StartProcess([]() {
285 *reinterpret_cast<volatile char*>(0xdead) = '1';
286 });
287
Josh Gaocbe70cb2016-10-18 18:17:52 -0700288 StartIntercept(&output_fd);
289 FinishCrasher();
290 AssertDeath(SIGSEGV);
291 FinishIntercept(&intercept_result);
292
293 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
294
295 std::string result;
296 ConsumeFd(std::move(output_fd), &result);
297 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\), code 1 \(SEGV_MAPERR\), fault addr 0xdead)");
298}
299
300TEST_F(CrasherTest, abort) {
301 int intercept_result;
302 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800303 StartProcess([]() {
304 abort();
305 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700306 StartIntercept(&output_fd);
307 FinishCrasher();
308 AssertDeath(SIGABRT);
309 FinishIntercept(&intercept_result);
310
311 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
312
313 std::string result;
314 ConsumeFd(std::move(output_fd), &result);
Andreas Gampe26cbafb2017-06-22 20:14:43 -0700315 ASSERT_BACKTRACE_FRAME(result, "abort");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700316}
317
318TEST_F(CrasherTest, signal) {
319 int intercept_result;
320 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800321 StartProcess([]() {
322 abort();
323 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700324 StartIntercept(&output_fd);
325
326 // Wait for a bit, or we might end up killing the process before the signal
327 // handler even gets a chance to be registered.
328 std::this_thread::sleep_for(100ms);
329 ASSERT_EQ(0, kill(crasher_pid, SIGSEGV));
330
331 AssertDeath(SIGSEGV);
332 FinishIntercept(&intercept_result);
333
334 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
335
336 std::string result;
337 ConsumeFd(std::move(output_fd), &result);
338 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\), code 0 \(SI_USER\), fault addr --------)");
339 ASSERT_MATCH(result, R"(backtrace:)");
340}
341
342TEST_F(CrasherTest, abort_message) {
343 int intercept_result;
344 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800345 StartProcess([]() {
346 android_set_abort_message("abort message goes here");
347 abort();
348 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700349 StartIntercept(&output_fd);
350 FinishCrasher();
351 AssertDeath(SIGABRT);
352 FinishIntercept(&intercept_result);
353
354 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
355
356 std::string result;
357 ConsumeFd(std::move(output_fd), &result);
Josh Gao502cfd22017-02-17 01:39:15 -0800358 ASSERT_MATCH(result, R"(Abort message: 'abort message goes here')");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700359}
360
Josh Gaoe06f2a42017-04-27 16:50:38 -0700361TEST_F(CrasherTest, abort_message_backtrace) {
362 int intercept_result;
363 unique_fd output_fd;
364 StartProcess([]() {
365 android_set_abort_message("not actually aborting");
366 raise(DEBUGGER_SIGNAL);
367 exit(0);
368 });
369 StartIntercept(&output_fd);
370 FinishCrasher();
371 AssertDeath(0);
372 FinishIntercept(&intercept_result);
373
374 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
375
376 std::string result;
377 ConsumeFd(std::move(output_fd), &result);
378 ASSERT_NOT_MATCH(result, R"(Abort message:)");
379}
380
Josh Gaocbe70cb2016-10-18 18:17:52 -0700381TEST_F(CrasherTest, intercept_timeout) {
382 int intercept_result;
383 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800384 StartProcess([]() {
385 abort();
386 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700387 StartIntercept(&output_fd);
388
389 // Don't let crasher finish until we timeout.
390 FinishIntercept(&intercept_result);
391
392 ASSERT_NE(1, intercept_result) << "tombstoned reported success? (intercept_result = "
393 << intercept_result << ")";
394
395 FinishCrasher();
396 AssertDeath(SIGABRT);
397}
398
399TEST_F(CrasherTest, wait_for_gdb) {
400 if (!android::base::SetProperty(kWaitForGdbKey, "1")) {
401 FAIL() << "failed to enable wait_for_gdb";
402 }
403 sleep(1);
404
Josh Gao502cfd22017-02-17 01:39:15 -0800405 StartProcess([]() {
406 abort();
407 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700408 FinishCrasher();
409
410 int status;
411 ASSERT_EQ(crasher_pid, waitpid(crasher_pid, &status, WUNTRACED));
412 ASSERT_TRUE(WIFSTOPPED(status));
413 ASSERT_EQ(SIGSTOP, WSTOPSIG(status));
414
415 ASSERT_EQ(0, kill(crasher_pid, SIGCONT));
416
417 AssertDeath(SIGABRT);
418}
419
Josh Gao7c6e3132017-01-22 17:59:02 -0800420// wait_for_gdb shouldn't trigger on manually sent signals.
Josh Gaocbe70cb2016-10-18 18:17:52 -0700421TEST_F(CrasherTest, wait_for_gdb_signal) {
422 if (!android::base::SetProperty(kWaitForGdbKey, "1")) {
423 FAIL() << "failed to enable wait_for_gdb";
424 }
425
Josh Gao502cfd22017-02-17 01:39:15 -0800426 StartProcess([]() {
427 abort();
428 });
Josh Gao7c6e3132017-01-22 17:59:02 -0800429 ASSERT_EQ(0, kill(crasher_pid, SIGSEGV)) << strerror(errno);
430 AssertDeath(SIGSEGV);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700431}
432
433TEST_F(CrasherTest, backtrace) {
434 std::string result;
435 int intercept_result;
436 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800437
438 StartProcess([]() {
439 abort();
440 });
Narayan Kamatha73df602017-05-24 15:07:25 +0100441 StartIntercept(&output_fd, kDebuggerdNativeBacktrace);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700442
443 std::this_thread::sleep_for(500ms);
444
445 sigval val;
446 val.sival_int = 1;
447 ASSERT_EQ(0, sigqueue(crasher_pid, DEBUGGER_SIGNAL, val)) << strerror(errno);
448 FinishIntercept(&intercept_result);
449 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
450 ConsumeFd(std::move(output_fd), &result);
Jaesung Chung58778e12017-06-15 18:20:34 +0900451 ASSERT_BACKTRACE_FRAME(result, "read");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700452
453 int status;
454 ASSERT_EQ(0, waitpid(crasher_pid, &status, WNOHANG | WUNTRACED));
455
456 StartIntercept(&output_fd);
457 FinishCrasher();
458 AssertDeath(SIGABRT);
459 FinishIntercept(&intercept_result);
460 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
461 ConsumeFd(std::move(output_fd), &result);
Andreas Gampe26cbafb2017-06-22 20:14:43 -0700462 ASSERT_BACKTRACE_FRAME(result, "abort");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700463}
Josh Gaofca7ca32017-01-23 12:05:35 -0800464
465TEST_F(CrasherTest, PR_SET_DUMPABLE_0_crash) {
Josh Gao502cfd22017-02-17 01:39:15 -0800466 int intercept_result;
467 unique_fd output_fd;
Josh Gaofca7ca32017-01-23 12:05:35 -0800468 StartProcess([]() {
469 prctl(PR_SET_DUMPABLE, 0);
Josh Gao502cfd22017-02-17 01:39:15 -0800470 abort();
Josh Gaofca7ca32017-01-23 12:05:35 -0800471 });
Josh Gao502cfd22017-02-17 01:39:15 -0800472
473 StartIntercept(&output_fd);
474 FinishCrasher();
475 AssertDeath(SIGABRT);
476 FinishIntercept(&intercept_result);
477
478 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
479
480 std::string result;
481 ConsumeFd(std::move(output_fd), &result);
Andreas Gampe26cbafb2017-06-22 20:14:43 -0700482 ASSERT_BACKTRACE_FRAME(result, "abort");
Josh Gaofca7ca32017-01-23 12:05:35 -0800483}
484
Josh Gao502cfd22017-02-17 01:39:15 -0800485TEST_F(CrasherTest, capabilities) {
486 ASSERT_EQ(0U, getuid()) << "capability test requires root";
487
Josh Gaofca7ca32017-01-23 12:05:35 -0800488 StartProcess([]() {
Josh Gao502cfd22017-02-17 01:39:15 -0800489 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) != 0) {
490 err(1, "failed to set PR_SET_KEEPCAPS");
491 }
492
493 if (setresuid(1, 1, 1) != 0) {
494 err(1, "setresuid failed");
495 }
496
497 __user_cap_header_struct capheader;
498 __user_cap_data_struct capdata[2];
499 memset(&capheader, 0, sizeof(capheader));
500 memset(&capdata, 0, sizeof(capdata));
501
502 capheader.version = _LINUX_CAPABILITY_VERSION_3;
503 capheader.pid = 0;
504
505 // Turn on every third capability.
506 static_assert(CAP_LAST_CAP > 33, "CAP_LAST_CAP <= 32");
507 for (int i = 0; i < CAP_LAST_CAP; i += 3) {
508 capdata[CAP_TO_INDEX(i)].permitted |= CAP_TO_MASK(i);
509 capdata[CAP_TO_INDEX(i)].effective |= CAP_TO_MASK(i);
510 }
511
512 // Make sure CAP_SYS_PTRACE is off.
513 capdata[CAP_TO_INDEX(CAP_SYS_PTRACE)].permitted &= ~(CAP_TO_MASK(CAP_SYS_PTRACE));
514 capdata[CAP_TO_INDEX(CAP_SYS_PTRACE)].effective &= ~(CAP_TO_MASK(CAP_SYS_PTRACE));
515
516 if (capset(&capheader, &capdata[0]) != 0) {
517 err(1, "capset failed");
518 }
519
520 if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_CLEAR_ALL, 0, 0, 0) != 0) {
521 err(1, "failed to drop ambient capabilities");
522 }
523
Josh Gaoa5199a92017-04-03 13:18:34 -0700524 pthread_setname_np(pthread_self(), "thread_name");
Josh Gao502cfd22017-02-17 01:39:15 -0800525 raise(SIGSYS);
Josh Gaofca7ca32017-01-23 12:05:35 -0800526 });
Josh Gao502cfd22017-02-17 01:39:15 -0800527
528 unique_fd output_fd;
529 StartIntercept(&output_fd);
530 FinishCrasher();
531 AssertDeath(SIGSYS);
532
533 std::string result;
534 int intercept_result;
535 FinishIntercept(&intercept_result);
536 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
537 ConsumeFd(std::move(output_fd), &result);
Josh Gaoa5199a92017-04-03 13:18:34 -0700538 ASSERT_MATCH(result, R"(name: thread_name\s+>>> .+debuggerd_test(32|64) <<<)");
Jaesung Chung58778e12017-06-15 18:20:34 +0900539 ASSERT_BACKTRACE_FRAME(result, "tgkill");
Josh Gaofca7ca32017-01-23 12:05:35 -0800540}
Josh Gaoc3c8c022017-02-13 16:36:18 -0800541
Josh Gao2e7b8e22017-05-04 17:12:57 -0700542TEST_F(CrasherTest, fake_pid) {
543 int intercept_result;
544 unique_fd output_fd;
545
546 // Prime the getpid/gettid caches.
547 UNUSED(getpid());
548 UNUSED(gettid());
549
550 std::function<pid_t()> clone_fn = []() {
551 return syscall(__NR_clone, SIGCHLD, nullptr, nullptr, nullptr, nullptr);
552 };
553 StartProcess(
554 []() {
555 ASSERT_NE(getpid(), syscall(__NR_getpid));
556 ASSERT_NE(gettid(), syscall(__NR_gettid));
557 raise(SIGSEGV);
558 },
559 clone_fn);
560
561 StartIntercept(&output_fd);
562 FinishCrasher();
563 AssertDeath(SIGSEGV);
564 FinishIntercept(&intercept_result);
565
566 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
567
568 std::string result;
569 ConsumeFd(std::move(output_fd), &result);
Jaesung Chung58778e12017-06-15 18:20:34 +0900570 ASSERT_BACKTRACE_FRAME(result, "tgkill");
Josh Gao2e7b8e22017-05-04 17:12:57 -0700571}
572
Josh Gaofd13bf02017-08-18 15:37:26 -0700573TEST_F(CrasherTest, competing_tracer) {
574 int intercept_result;
575 unique_fd output_fd;
576 StartProcess([]() {
577 while (true) {
578 }
579 });
580
581 StartIntercept(&output_fd);
582 FinishCrasher();
583
584 ASSERT_EQ(0, ptrace(PTRACE_SEIZE, crasher_pid, 0, 0));
585 ASSERT_EQ(0, kill(crasher_pid, SIGABRT));
586
587 int status;
588 ASSERT_EQ(crasher_pid, waitpid(crasher_pid, &status, 0));
589 ASSERT_TRUE(WIFSTOPPED(status));
590 ASSERT_EQ(SIGABRT, WSTOPSIG(status));
591
592 ASSERT_EQ(0, ptrace(PTRACE_CONT, crasher_pid, 0, SIGABRT));
593 FinishIntercept(&intercept_result);
594 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
595
596 std::string result;
597 ConsumeFd(std::move(output_fd), &result);
598 std::string regex = R"(failed to attach to thread \d+, already traced by )";
599 regex += std::to_string(gettid());
600 regex += R"( \(.+debuggerd_test)";
601 ASSERT_MATCH(result, regex.c_str());
602
603 ASSERT_EQ(0, ptrace(PTRACE_DETACH, crasher_pid, 0, SIGABRT));
604 AssertDeath(SIGABRT);
605}
606
Josh Gaoc3c8c022017-02-13 16:36:18 -0800607TEST(crash_dump, zombie) {
608 pid_t forkpid = fork();
609
Josh Gaoc3c8c022017-02-13 16:36:18 -0800610 pid_t rc;
611 int status;
612
613 if (forkpid == 0) {
614 errno = 0;
615 rc = waitpid(-1, &status, WNOHANG | __WALL | __WNOTHREAD);
616 if (rc != -1 || errno != ECHILD) {
617 errx(2, "first waitpid returned %d (%s), expected failure with ECHILD", rc, strerror(errno));
618 }
619
620 raise(DEBUGGER_SIGNAL);
621
622 errno = 0;
623 rc = waitpid(-1, &status, __WALL | __WNOTHREAD);
624 if (rc != -1 || errno != ECHILD) {
625 errx(2, "second waitpid returned %d (%s), expected failure with ECHILD", rc, strerror(errno));
626 }
627 _exit(0);
628 } else {
629 rc = waitpid(forkpid, &status, 0);
630 ASSERT_EQ(forkpid, rc);
631 ASSERT_TRUE(WIFEXITED(status));
632 ASSERT_EQ(0, WEXITSTATUS(status));
633 }
634}
Josh Gao352a8452017-03-30 16:46:21 -0700635
636TEST(tombstoned, no_notify) {
637 // Do this a few times.
638 for (int i = 0; i < 3; ++i) {
639 pid_t pid = 123'456'789 + i;
640
641 unique_fd intercept_fd, output_fd;
Narayan Kamathca5e9082017-06-02 15:42:06 +0100642 InterceptStatus status;
643 tombstoned_intercept(pid, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
644 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gao352a8452017-03-30 16:46:21 -0700645
646 {
647 unique_fd tombstoned_socket, input_fd;
Narayan Kamatha73df602017-05-24 15:07:25 +0100648 ASSERT_TRUE(tombstoned_connect(pid, &tombstoned_socket, &input_fd, kDebuggerdTombstone));
Josh Gao352a8452017-03-30 16:46:21 -0700649 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), &pid, sizeof(pid)));
650 }
651
652 pid_t read_pid;
653 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), &read_pid, sizeof(read_pid)));
654 ASSERT_EQ(read_pid, pid);
655 }
656}
657
658TEST(tombstoned, stress) {
659 // Spawn threads to simultaneously do a bunch of failing dumps and a bunch of successful dumps.
660 static constexpr int kDumpCount = 100;
661
662 std::atomic<bool> start(false);
663 std::vector<std::thread> threads;
664 threads.emplace_back([&start]() {
665 while (!start) {
666 continue;
667 }
668
669 // Use a way out of range pid, to avoid stomping on an actual process.
670 pid_t pid_base = 1'000'000;
671
672 for (int dump = 0; dump < kDumpCount; ++dump) {
673 pid_t pid = pid_base + dump;
674
675 unique_fd intercept_fd, output_fd;
Narayan Kamathca5e9082017-06-02 15:42:06 +0100676 InterceptStatus status;
677 tombstoned_intercept(pid, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
678 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gao352a8452017-03-30 16:46:21 -0700679
680 // Pretend to crash, and then immediately close the socket.
681 unique_fd sockfd(socket_local_client(kTombstonedCrashSocketName,
682 ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_SEQPACKET));
683 if (sockfd == -1) {
684 FAIL() << "failed to connect to tombstoned: " << strerror(errno);
685 }
686 TombstonedCrashPacket packet = {};
687 packet.packet_type = CrashPacketType::kDumpRequest;
688 packet.packet.dump_request.pid = pid;
689 if (TEMP_FAILURE_RETRY(write(sockfd, &packet, sizeof(packet))) != sizeof(packet)) {
690 FAIL() << "failed to write to tombstoned: " << strerror(errno);
691 }
692
693 continue;
694 }
695 });
696
697 threads.emplace_back([&start]() {
698 while (!start) {
699 continue;
700 }
701
702 // Use a way out of range pid, to avoid stomping on an actual process.
703 pid_t pid_base = 2'000'000;
704
705 for (int dump = 0; dump < kDumpCount; ++dump) {
706 pid_t pid = pid_base + dump;
707
708 unique_fd intercept_fd, output_fd;
Narayan Kamathca5e9082017-06-02 15:42:06 +0100709 InterceptStatus status;
710 tombstoned_intercept(pid, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
711 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gao352a8452017-03-30 16:46:21 -0700712
713 {
714 unique_fd tombstoned_socket, input_fd;
Narayan Kamatha73df602017-05-24 15:07:25 +0100715 ASSERT_TRUE(tombstoned_connect(pid, &tombstoned_socket, &input_fd, kDebuggerdTombstone));
Josh Gao352a8452017-03-30 16:46:21 -0700716 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), &pid, sizeof(pid)));
717 tombstoned_notify_completion(tombstoned_socket.get());
718 }
719
720 // TODO: Fix the race that requires this sleep.
721 std::this_thread::sleep_for(50ms);
722
723 pid_t read_pid;
724 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), &read_pid, sizeof(read_pid)));
725 ASSERT_EQ(read_pid, pid);
726 }
727 });
728
729 start = true;
730
731 for (std::thread& thread : threads) {
732 thread.join();
733 }
734}
Narayan Kamathca5e9082017-06-02 15:42:06 +0100735
736TEST(tombstoned, java_trace_intercept_smoke) {
737 // Using a "real" PID is a little dangerous here - if the test fails
738 // or crashes, we might end up getting a bogus / unreliable stack
739 // trace.
740 const pid_t self = getpid();
741
742 unique_fd intercept_fd, output_fd;
743 InterceptStatus status;
744 tombstoned_intercept(self, &intercept_fd, &output_fd, &status, kDebuggerdJavaBacktrace);
745 ASSERT_EQ(InterceptStatus::kRegistered, status);
746
747 // First connect to tombstoned requesting a native backtrace. This
748 // should result in a "regular" FD and not the installed intercept.
749 const char native[] = "native";
750 unique_fd tombstoned_socket, input_fd;
751 ASSERT_TRUE(tombstoned_connect(self, &tombstoned_socket, &input_fd, kDebuggerdNativeBacktrace));
752 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), native, sizeof(native)));
753 tombstoned_notify_completion(tombstoned_socket.get());
754
755 // Then, connect to tombstoned asking for a java backtrace. This *should*
756 // trigger the intercept.
757 const char java[] = "java";
758 ASSERT_TRUE(tombstoned_connect(self, &tombstoned_socket, &input_fd, kDebuggerdJavaBacktrace));
759 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), java, sizeof(java)));
760 tombstoned_notify_completion(tombstoned_socket.get());
761
762 char outbuf[sizeof(java)];
763 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), outbuf, sizeof(outbuf)));
764 ASSERT_STREQ("java", outbuf);
765}
766
767TEST(tombstoned, multiple_intercepts) {
768 const pid_t fake_pid = 1'234'567;
769 unique_fd intercept_fd, output_fd;
770 InterceptStatus status;
771 tombstoned_intercept(fake_pid, &intercept_fd, &output_fd, &status, kDebuggerdJavaBacktrace);
772 ASSERT_EQ(InterceptStatus::kRegistered, status);
773
774 unique_fd intercept_fd_2, output_fd_2;
775 tombstoned_intercept(fake_pid, &intercept_fd_2, &output_fd_2, &status, kDebuggerdNativeBacktrace);
776 ASSERT_EQ(InterceptStatus::kFailedAlreadyRegistered, status);
777}
778
779TEST(tombstoned, intercept_any) {
780 const pid_t fake_pid = 1'234'567;
781
782 unique_fd intercept_fd, output_fd;
783 InterceptStatus status;
784 tombstoned_intercept(fake_pid, &intercept_fd, &output_fd, &status, kDebuggerdNativeBacktrace);
785 ASSERT_EQ(InterceptStatus::kRegistered, status);
786
787 const char any[] = "any";
788 unique_fd tombstoned_socket, input_fd;
789 ASSERT_TRUE(tombstoned_connect(fake_pid, &tombstoned_socket, &input_fd, kDebuggerdAnyIntercept));
790 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), any, sizeof(any)));
791 tombstoned_notify_completion(tombstoned_socket.get());
792
793 char outbuf[sizeof(any)];
794 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), outbuf, sizeof(outbuf)));
795 ASSERT_STREQ("any", outbuf);
796}