blob: 8d0c98bb0363888f96bf5da80105c3d940198e10 [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>
Dan Albertc38057a2017-10-11 11:35:40 -070023#include <sys/syscall.h>
Josh Gaocbe70cb2016-10-18 18:17:52 -070024#include <sys/types.h>
Josh Gaofd13bf02017-08-18 15:37:26 -070025#include <unistd.h>
Josh Gaocbe70cb2016-10-18 18:17:52 -070026
27#include <chrono>
28#include <regex>
29#include <thread>
30
Josh Gao502cfd22017-02-17 01:39:15 -080031#include <android/set_abort_message.h>
32
Josh Gaocbe70cb2016-10-18 18:17:52 -070033#include <android-base/file.h>
34#include <android-base/logging.h>
Josh Gao2e7b8e22017-05-04 17:12:57 -070035#include <android-base/macros.h>
Josh Gaocbe70cb2016-10-18 18:17:52 -070036#include <android-base/parseint.h>
37#include <android-base/properties.h>
38#include <android-base/strings.h>
39#include <android-base/unique_fd.h>
40#include <cutils/sockets.h>
Josh Gaocbe70cb2016-10-18 18:17:52 -070041#include <gtest/gtest.h>
42
Narayan Kamath2d377cd2017-05-10 10:58:59 +010043#include "debuggerd/handler.h"
44#include "protocol.h"
45#include "tombstoned/tombstoned.h"
46#include "util.h"
47
Josh Gaocbe70cb2016-10-18 18:17:52 -070048using namespace std::chrono_literals;
49using android::base::unique_fd;
50
51#if defined(__LP64__)
Josh Gaocbe70cb2016-10-18 18:17:52 -070052#define ARCH_SUFFIX "64"
53#else
Josh Gaocbe70cb2016-10-18 18:17:52 -070054#define ARCH_SUFFIX ""
55#endif
56
57constexpr char kWaitForGdbKey[] = "debug.debuggerd.wait_for_gdb";
58
59#define TIMEOUT(seconds, expr) \
60 [&]() { \
61 struct sigaction old_sigaction; \
62 struct sigaction new_sigaction = {}; \
63 new_sigaction.sa_handler = [](int) {}; \
64 if (sigaction(SIGALRM, &new_sigaction, &new_sigaction) != 0) { \
65 err(1, "sigaction failed"); \
66 } \
67 alarm(seconds); \
68 auto value = expr; \
69 int saved_errno = errno; \
70 if (sigaction(SIGALRM, &old_sigaction, nullptr) != 0) { \
71 err(1, "sigaction failed"); \
72 } \
73 alarm(0); \
74 errno = saved_errno; \
75 return value; \
76 }()
77
78#define ASSERT_MATCH(str, pattern) \
79 do { \
80 std::regex r((pattern)); \
81 if (!std::regex_search((str), r)) { \
82 FAIL() << "regex mismatch: expected " << (pattern) << " in: \n" << (str); \
83 } \
84 } while (0)
85
Josh Gaoe06f2a42017-04-27 16:50:38 -070086#define ASSERT_NOT_MATCH(str, pattern) \
87 do { \
88 std::regex r((pattern)); \
89 if (std::regex_search((str), r)) { \
90 FAIL() << "regex mismatch: expected to not find " << (pattern) << " in: \n" << (str); \
91 } \
92 } while (0)
93
Jaesung Chung58778e12017-06-15 18:20:34 +090094#define ASSERT_BACKTRACE_FRAME(result, frame_name) \
95 ASSERT_MATCH(result, R"(#\d\d pc [0-9a-f]+\s+ /system/lib)" ARCH_SUFFIX \
96 R"(/libc.so \()" frame_name R"(\+)")
97
Narayan Kamatha73df602017-05-24 15:07:25 +010098static void tombstoned_intercept(pid_t target_pid, unique_fd* intercept_fd, unique_fd* output_fd,
Narayan Kamathca5e9082017-06-02 15:42:06 +010099 InterceptStatus* status, DebuggerdDumpType intercept_type) {
Josh Gao460b3362017-03-30 16:40:47 -0700100 intercept_fd->reset(socket_local_client(kTombstonedInterceptSocketName,
101 ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_SEQPACKET));
102 if (intercept_fd->get() == -1) {
103 FAIL() << "failed to contact tombstoned: " << strerror(errno);
104 }
105
Narayan Kamatha73df602017-05-24 15:07:25 +0100106 InterceptRequest req = {.pid = target_pid, .dump_type = intercept_type};
Josh Gao460b3362017-03-30 16:40:47 -0700107
108 unique_fd output_pipe_write;
109 if (!Pipe(output_fd, &output_pipe_write)) {
110 FAIL() << "failed to create output pipe: " << strerror(errno);
111 }
112
113 std::string pipe_size_str;
114 int pipe_buffer_size;
115 if (!android::base::ReadFileToString("/proc/sys/fs/pipe-max-size", &pipe_size_str)) {
116 FAIL() << "failed to read /proc/sys/fs/pipe-max-size: " << strerror(errno);
117 }
118
119 pipe_size_str = android::base::Trim(pipe_size_str);
120
121 if (!android::base::ParseInt(pipe_size_str.c_str(), &pipe_buffer_size, 0)) {
122 FAIL() << "failed to parse pipe max size";
123 }
124
125 if (fcntl(output_fd->get(), F_SETPIPE_SZ, pipe_buffer_size) != pipe_buffer_size) {
126 FAIL() << "failed to set pipe size: " << strerror(errno);
127 }
128
Josh Gao5675f3c2017-06-01 12:19:53 -0700129 ASSERT_GE(pipe_buffer_size, 1024 * 1024);
130
Josh Gao460b3362017-03-30 16:40:47 -0700131 if (send_fd(intercept_fd->get(), &req, sizeof(req), std::move(output_pipe_write)) != sizeof(req)) {
132 FAIL() << "failed to send output fd to tombstoned: " << strerror(errno);
133 }
134
135 InterceptResponse response;
136 ssize_t rc = TEMP_FAILURE_RETRY(read(intercept_fd->get(), &response, sizeof(response)));
137 if (rc == -1) {
138 FAIL() << "failed to read response from tombstoned: " << strerror(errno);
139 } else if (rc == 0) {
140 FAIL() << "failed to read response from tombstoned (EOF)";
141 } else if (rc != sizeof(response)) {
142 FAIL() << "received packet of unexpected length from tombstoned: expected " << sizeof(response)
143 << ", received " << rc;
144 }
145
Narayan Kamathca5e9082017-06-02 15:42:06 +0100146 *status = response.status;
Josh Gao460b3362017-03-30 16:40:47 -0700147}
148
Josh Gaocbe70cb2016-10-18 18:17:52 -0700149class CrasherTest : public ::testing::Test {
150 public:
151 pid_t crasher_pid = -1;
152 bool previous_wait_for_gdb;
153 unique_fd crasher_pipe;
154 unique_fd intercept_fd;
155
156 CrasherTest();
157 ~CrasherTest();
158
Narayan Kamatha73df602017-05-24 15:07:25 +0100159 void StartIntercept(unique_fd* output_fd, DebuggerdDumpType intercept_type = kDebuggerdTombstone);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700160
161 // Returns -1 if we fail to read a response from tombstoned, otherwise the received return code.
162 void FinishIntercept(int* result);
163
Josh Gao2e7b8e22017-05-04 17:12:57 -0700164 void StartProcess(std::function<void()> function, std::function<pid_t()> forker = fork);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700165 void StartCrasher(const std::string& crash_type);
166 void FinishCrasher();
167 void AssertDeath(int signo);
168};
169
170CrasherTest::CrasherTest() {
171 previous_wait_for_gdb = android::base::GetBoolProperty(kWaitForGdbKey, false);
172 android::base::SetProperty(kWaitForGdbKey, "0");
173}
174
175CrasherTest::~CrasherTest() {
176 if (crasher_pid != -1) {
177 kill(crasher_pid, SIGKILL);
178 int status;
179 waitpid(crasher_pid, &status, WUNTRACED);
180 }
181
182 android::base::SetProperty(kWaitForGdbKey, previous_wait_for_gdb ? "1" : "0");
183}
184
Narayan Kamatha73df602017-05-24 15:07:25 +0100185void CrasherTest::StartIntercept(unique_fd* output_fd, DebuggerdDumpType intercept_type) {
Josh Gaocbe70cb2016-10-18 18:17:52 -0700186 if (crasher_pid == -1) {
187 FAIL() << "crasher hasn't been started";
188 }
189
Narayan Kamathca5e9082017-06-02 15:42:06 +0100190 InterceptStatus status;
191 tombstoned_intercept(crasher_pid, &this->intercept_fd, output_fd, &status, intercept_type);
192 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700193}
194
195void CrasherTest::FinishIntercept(int* result) {
196 InterceptResponse response;
197
198 // Timeout for tombstoned intercept is 10 seconds.
199 ssize_t rc = TIMEOUT(20, read(intercept_fd.get(), &response, sizeof(response)));
200 if (rc == -1) {
201 FAIL() << "failed to read response from tombstoned: " << strerror(errno);
202 } else if (rc == 0) {
203 *result = -1;
204 } else if (rc != sizeof(response)) {
205 FAIL() << "received packet of unexpected length from tombstoned: expected " << sizeof(response)
206 << ", received " << rc;
207 } else {
Josh Gao460b3362017-03-30 16:40:47 -0700208 *result = response.status == InterceptStatus::kStarted ? 1 : 0;
Josh Gaocbe70cb2016-10-18 18:17:52 -0700209 }
210}
211
Josh Gao2e7b8e22017-05-04 17:12:57 -0700212void CrasherTest::StartProcess(std::function<void()> function, std::function<pid_t()> forker) {
Josh Gaofca7ca32017-01-23 12:05:35 -0800213 unique_fd read_pipe;
Josh Gaocbe70cb2016-10-18 18:17:52 -0700214 unique_fd crasher_read_pipe;
215 if (!Pipe(&crasher_read_pipe, &crasher_pipe)) {
216 FAIL() << "failed to create pipe: " << strerror(errno);
217 }
218
Josh Gao2e7b8e22017-05-04 17:12:57 -0700219 crasher_pid = forker();
Josh Gaocbe70cb2016-10-18 18:17:52 -0700220 if (crasher_pid == -1) {
221 FAIL() << "fork failed: " << strerror(errno);
222 } else if (crasher_pid == 0) {
Josh Gao502cfd22017-02-17 01:39:15 -0800223 char dummy;
224 crasher_pipe.reset();
225 TEMP_FAILURE_RETRY(read(crasher_read_pipe.get(), &dummy, 1));
Josh Gaofca7ca32017-01-23 12:05:35 -0800226 function();
227 _exit(0);
228 }
229}
230
Josh Gaocbe70cb2016-10-18 18:17:52 -0700231void CrasherTest::FinishCrasher() {
232 if (crasher_pipe == -1) {
233 FAIL() << "crasher pipe uninitialized";
234 }
235
236 ssize_t rc = write(crasher_pipe.get(), "\n", 1);
237 if (rc == -1) {
238 FAIL() << "failed to write to crasher pipe: " << strerror(errno);
239 } else if (rc == 0) {
240 FAIL() << "crasher pipe was closed";
241 }
242}
243
244void CrasherTest::AssertDeath(int signo) {
245 int status;
246 pid_t pid = TIMEOUT(5, waitpid(crasher_pid, &status, 0));
247 if (pid != crasher_pid) {
248 FAIL() << "failed to wait for crasher: " << strerror(errno);
249 }
250
Josh Gaoe06f2a42017-04-27 16:50:38 -0700251 if (signo == 0) {
252 ASSERT_TRUE(WIFEXITED(status));
253 ASSERT_EQ(0, WEXITSTATUS(signo));
254 } else {
255 ASSERT_FALSE(WIFEXITED(status));
256 ASSERT_TRUE(WIFSIGNALED(status)) << "crasher didn't terminate via a signal";
257 ASSERT_EQ(signo, WTERMSIG(status));
Josh Gaocbe70cb2016-10-18 18:17:52 -0700258 }
Josh Gaocbe70cb2016-10-18 18:17:52 -0700259 crasher_pid = -1;
260}
261
262static void ConsumeFd(unique_fd fd, std::string* output) {
263 constexpr size_t read_length = PAGE_SIZE;
264 std::string result;
265
266 while (true) {
267 size_t offset = result.size();
268 result.resize(result.size() + PAGE_SIZE);
269 ssize_t rc = TEMP_FAILURE_RETRY(read(fd.get(), &result[offset], read_length));
270 if (rc == -1) {
271 FAIL() << "read failed: " << strerror(errno);
272 } else if (rc == 0) {
273 result.resize(result.size() - PAGE_SIZE);
274 break;
275 }
276
277 result.resize(result.size() - PAGE_SIZE + rc);
278 }
279
280 *output = std::move(result);
281}
282
283TEST_F(CrasherTest, smoke) {
284 int intercept_result;
285 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800286 StartProcess([]() {
287 *reinterpret_cast<volatile char*>(0xdead) = '1';
288 });
289
Josh Gaocbe70cb2016-10-18 18:17:52 -0700290 StartIntercept(&output_fd);
291 FinishCrasher();
292 AssertDeath(SIGSEGV);
293 FinishIntercept(&intercept_result);
294
295 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
296
297 std::string result;
298 ConsumeFd(std::move(output_fd), &result);
299 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\), code 1 \(SEGV_MAPERR\), fault addr 0xdead)");
300}
301
Josh Gaocdea7502017-11-01 15:00:40 -0700302TEST_F(CrasherTest, LD_PRELOAD) {
303 int intercept_result;
304 unique_fd output_fd;
305 StartProcess([]() {
306 setenv("LD_PRELOAD", "nonexistent.so", 1);
307 *reinterpret_cast<volatile char*>(0xdead) = '1';
308 });
309
310 StartIntercept(&output_fd);
311 FinishCrasher();
312 AssertDeath(SIGSEGV);
313 FinishIntercept(&intercept_result);
314
315 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
316
317 std::string result;
318 ConsumeFd(std::move(output_fd), &result);
319 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\), code 1 \(SEGV_MAPERR\), fault addr 0xdead)");
320}
321
Josh Gaocbe70cb2016-10-18 18:17:52 -0700322TEST_F(CrasherTest, abort) {
323 int intercept_result;
324 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800325 StartProcess([]() {
326 abort();
327 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700328 StartIntercept(&output_fd);
329 FinishCrasher();
330 AssertDeath(SIGABRT);
331 FinishIntercept(&intercept_result);
332
333 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
334
335 std::string result;
336 ConsumeFd(std::move(output_fd), &result);
Andreas Gampe26cbafb2017-06-22 20:14:43 -0700337 ASSERT_BACKTRACE_FRAME(result, "abort");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700338}
339
340TEST_F(CrasherTest, signal) {
341 int intercept_result;
342 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800343 StartProcess([]() {
344 abort();
345 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700346 StartIntercept(&output_fd);
347
348 // Wait for a bit, or we might end up killing the process before the signal
349 // handler even gets a chance to be registered.
350 std::this_thread::sleep_for(100ms);
351 ASSERT_EQ(0, kill(crasher_pid, SIGSEGV));
352
353 AssertDeath(SIGSEGV);
354 FinishIntercept(&intercept_result);
355
356 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
357
358 std::string result;
359 ConsumeFd(std::move(output_fd), &result);
360 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\), code 0 \(SI_USER\), fault addr --------)");
361 ASSERT_MATCH(result, R"(backtrace:)");
362}
363
364TEST_F(CrasherTest, abort_message) {
365 int intercept_result;
366 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800367 StartProcess([]() {
368 android_set_abort_message("abort message goes here");
369 abort();
370 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700371 StartIntercept(&output_fd);
372 FinishCrasher();
373 AssertDeath(SIGABRT);
374 FinishIntercept(&intercept_result);
375
376 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
377
378 std::string result;
379 ConsumeFd(std::move(output_fd), &result);
Josh Gao502cfd22017-02-17 01:39:15 -0800380 ASSERT_MATCH(result, R"(Abort message: 'abort message goes here')");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700381}
382
Josh Gaoe06f2a42017-04-27 16:50:38 -0700383TEST_F(CrasherTest, abort_message_backtrace) {
384 int intercept_result;
385 unique_fd output_fd;
386 StartProcess([]() {
387 android_set_abort_message("not actually aborting");
388 raise(DEBUGGER_SIGNAL);
389 exit(0);
390 });
391 StartIntercept(&output_fd);
392 FinishCrasher();
393 AssertDeath(0);
394 FinishIntercept(&intercept_result);
395
396 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
397
398 std::string result;
399 ConsumeFd(std::move(output_fd), &result);
400 ASSERT_NOT_MATCH(result, R"(Abort message:)");
401}
402
Josh Gaocbe70cb2016-10-18 18:17:52 -0700403TEST_F(CrasherTest, intercept_timeout) {
404 int intercept_result;
405 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800406 StartProcess([]() {
407 abort();
408 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700409 StartIntercept(&output_fd);
410
411 // Don't let crasher finish until we timeout.
412 FinishIntercept(&intercept_result);
413
414 ASSERT_NE(1, intercept_result) << "tombstoned reported success? (intercept_result = "
415 << intercept_result << ")";
416
417 FinishCrasher();
418 AssertDeath(SIGABRT);
419}
420
421TEST_F(CrasherTest, wait_for_gdb) {
422 if (!android::base::SetProperty(kWaitForGdbKey, "1")) {
423 FAIL() << "failed to enable wait_for_gdb";
424 }
425 sleep(1);
426
Josh Gao502cfd22017-02-17 01:39:15 -0800427 StartProcess([]() {
428 abort();
429 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700430 FinishCrasher();
431
432 int status;
433 ASSERT_EQ(crasher_pid, waitpid(crasher_pid, &status, WUNTRACED));
434 ASSERT_TRUE(WIFSTOPPED(status));
435 ASSERT_EQ(SIGSTOP, WSTOPSIG(status));
436
437 ASSERT_EQ(0, kill(crasher_pid, SIGCONT));
438
439 AssertDeath(SIGABRT);
440}
441
Josh Gao7c6e3132017-01-22 17:59:02 -0800442// wait_for_gdb shouldn't trigger on manually sent signals.
Josh Gaocbe70cb2016-10-18 18:17:52 -0700443TEST_F(CrasherTest, wait_for_gdb_signal) {
444 if (!android::base::SetProperty(kWaitForGdbKey, "1")) {
445 FAIL() << "failed to enable wait_for_gdb";
446 }
447
Josh Gao502cfd22017-02-17 01:39:15 -0800448 StartProcess([]() {
449 abort();
450 });
Josh Gao7c6e3132017-01-22 17:59:02 -0800451 ASSERT_EQ(0, kill(crasher_pid, SIGSEGV)) << strerror(errno);
452 AssertDeath(SIGSEGV);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700453}
454
455TEST_F(CrasherTest, backtrace) {
456 std::string result;
457 int intercept_result;
458 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800459
460 StartProcess([]() {
461 abort();
462 });
Narayan Kamatha73df602017-05-24 15:07:25 +0100463 StartIntercept(&output_fd, kDebuggerdNativeBacktrace);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700464
465 std::this_thread::sleep_for(500ms);
466
467 sigval val;
468 val.sival_int = 1;
469 ASSERT_EQ(0, sigqueue(crasher_pid, DEBUGGER_SIGNAL, val)) << strerror(errno);
470 FinishIntercept(&intercept_result);
471 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
472 ConsumeFd(std::move(output_fd), &result);
Jaesung Chung58778e12017-06-15 18:20:34 +0900473 ASSERT_BACKTRACE_FRAME(result, "read");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700474
475 int status;
476 ASSERT_EQ(0, waitpid(crasher_pid, &status, WNOHANG | WUNTRACED));
477
478 StartIntercept(&output_fd);
479 FinishCrasher();
480 AssertDeath(SIGABRT);
481 FinishIntercept(&intercept_result);
482 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
483 ConsumeFd(std::move(output_fd), &result);
Andreas Gampe26cbafb2017-06-22 20:14:43 -0700484 ASSERT_BACKTRACE_FRAME(result, "abort");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700485}
Josh Gaofca7ca32017-01-23 12:05:35 -0800486
487TEST_F(CrasherTest, PR_SET_DUMPABLE_0_crash) {
Josh Gao502cfd22017-02-17 01:39:15 -0800488 int intercept_result;
489 unique_fd output_fd;
Josh Gaofca7ca32017-01-23 12:05:35 -0800490 StartProcess([]() {
491 prctl(PR_SET_DUMPABLE, 0);
Josh Gao502cfd22017-02-17 01:39:15 -0800492 abort();
Josh Gaofca7ca32017-01-23 12:05:35 -0800493 });
Josh Gao502cfd22017-02-17 01:39:15 -0800494
495 StartIntercept(&output_fd);
496 FinishCrasher();
497 AssertDeath(SIGABRT);
498 FinishIntercept(&intercept_result);
499
500 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
501
502 std::string result;
503 ConsumeFd(std::move(output_fd), &result);
Andreas Gampe26cbafb2017-06-22 20:14:43 -0700504 ASSERT_BACKTRACE_FRAME(result, "abort");
Josh Gaofca7ca32017-01-23 12:05:35 -0800505}
506
Josh Gao502cfd22017-02-17 01:39:15 -0800507TEST_F(CrasherTest, capabilities) {
508 ASSERT_EQ(0U, getuid()) << "capability test requires root";
509
Josh Gaofca7ca32017-01-23 12:05:35 -0800510 StartProcess([]() {
Josh Gao502cfd22017-02-17 01:39:15 -0800511 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) != 0) {
512 err(1, "failed to set PR_SET_KEEPCAPS");
513 }
514
515 if (setresuid(1, 1, 1) != 0) {
516 err(1, "setresuid failed");
517 }
518
519 __user_cap_header_struct capheader;
520 __user_cap_data_struct capdata[2];
521 memset(&capheader, 0, sizeof(capheader));
522 memset(&capdata, 0, sizeof(capdata));
523
524 capheader.version = _LINUX_CAPABILITY_VERSION_3;
525 capheader.pid = 0;
526
527 // Turn on every third capability.
528 static_assert(CAP_LAST_CAP > 33, "CAP_LAST_CAP <= 32");
529 for (int i = 0; i < CAP_LAST_CAP; i += 3) {
530 capdata[CAP_TO_INDEX(i)].permitted |= CAP_TO_MASK(i);
531 capdata[CAP_TO_INDEX(i)].effective |= CAP_TO_MASK(i);
532 }
533
534 // Make sure CAP_SYS_PTRACE is off.
535 capdata[CAP_TO_INDEX(CAP_SYS_PTRACE)].permitted &= ~(CAP_TO_MASK(CAP_SYS_PTRACE));
536 capdata[CAP_TO_INDEX(CAP_SYS_PTRACE)].effective &= ~(CAP_TO_MASK(CAP_SYS_PTRACE));
537
538 if (capset(&capheader, &capdata[0]) != 0) {
539 err(1, "capset failed");
540 }
541
542 if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_CLEAR_ALL, 0, 0, 0) != 0) {
543 err(1, "failed to drop ambient capabilities");
544 }
545
Josh Gaoa5199a92017-04-03 13:18:34 -0700546 pthread_setname_np(pthread_self(), "thread_name");
Josh Gao502cfd22017-02-17 01:39:15 -0800547 raise(SIGSYS);
Josh Gaofca7ca32017-01-23 12:05:35 -0800548 });
Josh Gao502cfd22017-02-17 01:39:15 -0800549
550 unique_fd output_fd;
551 StartIntercept(&output_fd);
552 FinishCrasher();
553 AssertDeath(SIGSYS);
554
555 std::string result;
556 int intercept_result;
557 FinishIntercept(&intercept_result);
558 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
559 ConsumeFd(std::move(output_fd), &result);
Josh Gaoa5199a92017-04-03 13:18:34 -0700560 ASSERT_MATCH(result, R"(name: thread_name\s+>>> .+debuggerd_test(32|64) <<<)");
Jaesung Chung58778e12017-06-15 18:20:34 +0900561 ASSERT_BACKTRACE_FRAME(result, "tgkill");
Josh Gaofca7ca32017-01-23 12:05:35 -0800562}
Josh Gaoc3c8c022017-02-13 16:36:18 -0800563
Josh Gao2e7b8e22017-05-04 17:12:57 -0700564TEST_F(CrasherTest, fake_pid) {
565 int intercept_result;
566 unique_fd output_fd;
567
568 // Prime the getpid/gettid caches.
569 UNUSED(getpid());
570 UNUSED(gettid());
571
572 std::function<pid_t()> clone_fn = []() {
573 return syscall(__NR_clone, SIGCHLD, nullptr, nullptr, nullptr, nullptr);
574 };
575 StartProcess(
576 []() {
577 ASSERT_NE(getpid(), syscall(__NR_getpid));
578 ASSERT_NE(gettid(), syscall(__NR_gettid));
579 raise(SIGSEGV);
580 },
581 clone_fn);
582
583 StartIntercept(&output_fd);
584 FinishCrasher();
585 AssertDeath(SIGSEGV);
586 FinishIntercept(&intercept_result);
587
588 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
589
590 std::string result;
591 ConsumeFd(std::move(output_fd), &result);
Jaesung Chung58778e12017-06-15 18:20:34 +0900592 ASSERT_BACKTRACE_FRAME(result, "tgkill");
Josh Gao2e7b8e22017-05-04 17:12:57 -0700593}
594
Josh Gaofd13bf02017-08-18 15:37:26 -0700595TEST_F(CrasherTest, competing_tracer) {
596 int intercept_result;
597 unique_fd output_fd;
598 StartProcess([]() {
599 while (true) {
600 }
601 });
602
603 StartIntercept(&output_fd);
604 FinishCrasher();
605
606 ASSERT_EQ(0, ptrace(PTRACE_SEIZE, crasher_pid, 0, 0));
607 ASSERT_EQ(0, kill(crasher_pid, SIGABRT));
608
609 int status;
610 ASSERT_EQ(crasher_pid, waitpid(crasher_pid, &status, 0));
611 ASSERT_TRUE(WIFSTOPPED(status));
612 ASSERT_EQ(SIGABRT, WSTOPSIG(status));
613
614 ASSERT_EQ(0, ptrace(PTRACE_CONT, crasher_pid, 0, SIGABRT));
615 FinishIntercept(&intercept_result);
616 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
617
618 std::string result;
619 ConsumeFd(std::move(output_fd), &result);
620 std::string regex = R"(failed to attach to thread \d+, already traced by )";
621 regex += std::to_string(gettid());
622 regex += R"( \(.+debuggerd_test)";
623 ASSERT_MATCH(result, regex.c_str());
624
625 ASSERT_EQ(0, ptrace(PTRACE_DETACH, crasher_pid, 0, SIGABRT));
626 AssertDeath(SIGABRT);
627}
628
Josh Gaoc3c8c022017-02-13 16:36:18 -0800629TEST(crash_dump, zombie) {
630 pid_t forkpid = fork();
631
Josh Gaoc3c8c022017-02-13 16:36:18 -0800632 pid_t rc;
633 int status;
634
635 if (forkpid == 0) {
636 errno = 0;
637 rc = waitpid(-1, &status, WNOHANG | __WALL | __WNOTHREAD);
638 if (rc != -1 || errno != ECHILD) {
639 errx(2, "first waitpid returned %d (%s), expected failure with ECHILD", rc, strerror(errno));
640 }
641
642 raise(DEBUGGER_SIGNAL);
643
644 errno = 0;
645 rc = waitpid(-1, &status, __WALL | __WNOTHREAD);
646 if (rc != -1 || errno != ECHILD) {
647 errx(2, "second waitpid returned %d (%s), expected failure with ECHILD", rc, strerror(errno));
648 }
649 _exit(0);
650 } else {
651 rc = waitpid(forkpid, &status, 0);
652 ASSERT_EQ(forkpid, rc);
653 ASSERT_TRUE(WIFEXITED(status));
654 ASSERT_EQ(0, WEXITSTATUS(status));
655 }
656}
Josh Gao352a8452017-03-30 16:46:21 -0700657
658TEST(tombstoned, no_notify) {
659 // Do this a few times.
660 for (int i = 0; i < 3; ++i) {
661 pid_t pid = 123'456'789 + i;
662
663 unique_fd intercept_fd, output_fd;
Narayan Kamathca5e9082017-06-02 15:42:06 +0100664 InterceptStatus status;
665 tombstoned_intercept(pid, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
666 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gao352a8452017-03-30 16:46:21 -0700667
668 {
669 unique_fd tombstoned_socket, input_fd;
Narayan Kamatha73df602017-05-24 15:07:25 +0100670 ASSERT_TRUE(tombstoned_connect(pid, &tombstoned_socket, &input_fd, kDebuggerdTombstone));
Josh Gao352a8452017-03-30 16:46:21 -0700671 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), &pid, sizeof(pid)));
672 }
673
674 pid_t read_pid;
675 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), &read_pid, sizeof(read_pid)));
676 ASSERT_EQ(read_pid, pid);
677 }
678}
679
680TEST(tombstoned, stress) {
681 // Spawn threads to simultaneously do a bunch of failing dumps and a bunch of successful dumps.
682 static constexpr int kDumpCount = 100;
683
684 std::atomic<bool> start(false);
685 std::vector<std::thread> threads;
686 threads.emplace_back([&start]() {
687 while (!start) {
688 continue;
689 }
690
691 // Use a way out of range pid, to avoid stomping on an actual process.
692 pid_t pid_base = 1'000'000;
693
694 for (int dump = 0; dump < kDumpCount; ++dump) {
695 pid_t pid = pid_base + dump;
696
697 unique_fd intercept_fd, output_fd;
Narayan Kamathca5e9082017-06-02 15:42:06 +0100698 InterceptStatus status;
699 tombstoned_intercept(pid, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
700 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gao352a8452017-03-30 16:46:21 -0700701
702 // Pretend to crash, and then immediately close the socket.
703 unique_fd sockfd(socket_local_client(kTombstonedCrashSocketName,
704 ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_SEQPACKET));
705 if (sockfd == -1) {
706 FAIL() << "failed to connect to tombstoned: " << strerror(errno);
707 }
708 TombstonedCrashPacket packet = {};
709 packet.packet_type = CrashPacketType::kDumpRequest;
710 packet.packet.dump_request.pid = pid;
711 if (TEMP_FAILURE_RETRY(write(sockfd, &packet, sizeof(packet))) != sizeof(packet)) {
712 FAIL() << "failed to write to tombstoned: " << strerror(errno);
713 }
714
715 continue;
716 }
717 });
718
719 threads.emplace_back([&start]() {
720 while (!start) {
721 continue;
722 }
723
724 // Use a way out of range pid, to avoid stomping on an actual process.
725 pid_t pid_base = 2'000'000;
726
727 for (int dump = 0; dump < kDumpCount; ++dump) {
728 pid_t pid = pid_base + dump;
729
730 unique_fd intercept_fd, output_fd;
Narayan Kamathca5e9082017-06-02 15:42:06 +0100731 InterceptStatus status;
732 tombstoned_intercept(pid, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
733 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gao352a8452017-03-30 16:46:21 -0700734
735 {
736 unique_fd tombstoned_socket, input_fd;
Narayan Kamatha73df602017-05-24 15:07:25 +0100737 ASSERT_TRUE(tombstoned_connect(pid, &tombstoned_socket, &input_fd, kDebuggerdTombstone));
Josh Gao352a8452017-03-30 16:46:21 -0700738 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), &pid, sizeof(pid)));
739 tombstoned_notify_completion(tombstoned_socket.get());
740 }
741
742 // TODO: Fix the race that requires this sleep.
743 std::this_thread::sleep_for(50ms);
744
745 pid_t read_pid;
746 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), &read_pid, sizeof(read_pid)));
747 ASSERT_EQ(read_pid, pid);
748 }
749 });
750
751 start = true;
752
753 for (std::thread& thread : threads) {
754 thread.join();
755 }
756}
Narayan Kamathca5e9082017-06-02 15:42:06 +0100757
758TEST(tombstoned, java_trace_intercept_smoke) {
759 // Using a "real" PID is a little dangerous here - if the test fails
760 // or crashes, we might end up getting a bogus / unreliable stack
761 // trace.
762 const pid_t self = getpid();
763
764 unique_fd intercept_fd, output_fd;
765 InterceptStatus status;
766 tombstoned_intercept(self, &intercept_fd, &output_fd, &status, kDebuggerdJavaBacktrace);
767 ASSERT_EQ(InterceptStatus::kRegistered, status);
768
769 // First connect to tombstoned requesting a native backtrace. This
770 // should result in a "regular" FD and not the installed intercept.
771 const char native[] = "native";
772 unique_fd tombstoned_socket, input_fd;
773 ASSERT_TRUE(tombstoned_connect(self, &tombstoned_socket, &input_fd, kDebuggerdNativeBacktrace));
774 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), native, sizeof(native)));
775 tombstoned_notify_completion(tombstoned_socket.get());
776
777 // Then, connect to tombstoned asking for a java backtrace. This *should*
778 // trigger the intercept.
779 const char java[] = "java";
780 ASSERT_TRUE(tombstoned_connect(self, &tombstoned_socket, &input_fd, kDebuggerdJavaBacktrace));
781 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), java, sizeof(java)));
782 tombstoned_notify_completion(tombstoned_socket.get());
783
784 char outbuf[sizeof(java)];
785 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), outbuf, sizeof(outbuf)));
786 ASSERT_STREQ("java", outbuf);
787}
788
789TEST(tombstoned, multiple_intercepts) {
790 const pid_t fake_pid = 1'234'567;
791 unique_fd intercept_fd, output_fd;
792 InterceptStatus status;
793 tombstoned_intercept(fake_pid, &intercept_fd, &output_fd, &status, kDebuggerdJavaBacktrace);
794 ASSERT_EQ(InterceptStatus::kRegistered, status);
795
796 unique_fd intercept_fd_2, output_fd_2;
797 tombstoned_intercept(fake_pid, &intercept_fd_2, &output_fd_2, &status, kDebuggerdNativeBacktrace);
798 ASSERT_EQ(InterceptStatus::kFailedAlreadyRegistered, status);
799}
800
801TEST(tombstoned, intercept_any) {
802 const pid_t fake_pid = 1'234'567;
803
804 unique_fd intercept_fd, output_fd;
805 InterceptStatus status;
806 tombstoned_intercept(fake_pid, &intercept_fd, &output_fd, &status, kDebuggerdNativeBacktrace);
807 ASSERT_EQ(InterceptStatus::kRegistered, status);
808
809 const char any[] = "any";
810 unique_fd tombstoned_socket, input_fd;
811 ASSERT_TRUE(tombstoned_connect(fake_pid, &tombstoned_socket, &input_fd, kDebuggerdAnyIntercept));
812 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), any, sizeof(any)));
813 tombstoned_notify_completion(tombstoned_socket.get());
814
815 char outbuf[sizeof(any)];
816 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), outbuf, sizeof(outbuf)));
817 ASSERT_STREQ("any", outbuf);
818}