blob: e410be91016118bd3ed011b90b1e01d2eda3831b [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
Josh Gaoe04ca272018-01-16 15:38:17 -080083#define ASSERT_BACKTRACE_FRAME(result, frame_name) \
84 ASSERT_MATCH(result, R"(#\d\d pc [0-9a-f]+\s+ \S+ \()" frame_name R"(\+)");
Jaesung Chung58778e12017-06-15 18:20:34 +090085
Narayan Kamatha73df602017-05-24 15:07:25 +010086static void tombstoned_intercept(pid_t target_pid, unique_fd* intercept_fd, unique_fd* output_fd,
Narayan Kamathca5e9082017-06-02 15:42:06 +010087 InterceptStatus* status, DebuggerdDumpType intercept_type) {
Josh Gao460b3362017-03-30 16:40:47 -070088 intercept_fd->reset(socket_local_client(kTombstonedInterceptSocketName,
89 ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_SEQPACKET));
90 if (intercept_fd->get() == -1) {
91 FAIL() << "failed to contact tombstoned: " << strerror(errno);
92 }
93
Narayan Kamatha73df602017-05-24 15:07:25 +010094 InterceptRequest req = {.pid = target_pid, .dump_type = intercept_type};
Josh Gao460b3362017-03-30 16:40:47 -070095
96 unique_fd output_pipe_write;
97 if (!Pipe(output_fd, &output_pipe_write)) {
98 FAIL() << "failed to create output pipe: " << strerror(errno);
99 }
100
101 std::string pipe_size_str;
102 int pipe_buffer_size;
103 if (!android::base::ReadFileToString("/proc/sys/fs/pipe-max-size", &pipe_size_str)) {
104 FAIL() << "failed to read /proc/sys/fs/pipe-max-size: " << strerror(errno);
105 }
106
107 pipe_size_str = android::base::Trim(pipe_size_str);
108
109 if (!android::base::ParseInt(pipe_size_str.c_str(), &pipe_buffer_size, 0)) {
110 FAIL() << "failed to parse pipe max size";
111 }
112
113 if (fcntl(output_fd->get(), F_SETPIPE_SZ, pipe_buffer_size) != pipe_buffer_size) {
114 FAIL() << "failed to set pipe size: " << strerror(errno);
115 }
116
Josh Gao5675f3c2017-06-01 12:19:53 -0700117 ASSERT_GE(pipe_buffer_size, 1024 * 1024);
118
Josh Gao460b3362017-03-30 16:40:47 -0700119 if (send_fd(intercept_fd->get(), &req, sizeof(req), std::move(output_pipe_write)) != sizeof(req)) {
120 FAIL() << "failed to send output fd to tombstoned: " << strerror(errno);
121 }
122
123 InterceptResponse response;
124 ssize_t rc = TEMP_FAILURE_RETRY(read(intercept_fd->get(), &response, sizeof(response)));
125 if (rc == -1) {
126 FAIL() << "failed to read response from tombstoned: " << strerror(errno);
127 } else if (rc == 0) {
128 FAIL() << "failed to read response from tombstoned (EOF)";
129 } else if (rc != sizeof(response)) {
130 FAIL() << "received packet of unexpected length from tombstoned: expected " << sizeof(response)
131 << ", received " << rc;
132 }
133
Narayan Kamathca5e9082017-06-02 15:42:06 +0100134 *status = response.status;
Josh Gao460b3362017-03-30 16:40:47 -0700135}
136
Josh Gaocbe70cb2016-10-18 18:17:52 -0700137class CrasherTest : public ::testing::Test {
138 public:
139 pid_t crasher_pid = -1;
140 bool previous_wait_for_gdb;
141 unique_fd crasher_pipe;
142 unique_fd intercept_fd;
143
144 CrasherTest();
145 ~CrasherTest();
146
Narayan Kamatha73df602017-05-24 15:07:25 +0100147 void StartIntercept(unique_fd* output_fd, DebuggerdDumpType intercept_type = kDebuggerdTombstone);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700148
149 // Returns -1 if we fail to read a response from tombstoned, otherwise the received return code.
150 void FinishIntercept(int* result);
151
Josh Gao2e7b8e22017-05-04 17:12:57 -0700152 void StartProcess(std::function<void()> function, std::function<pid_t()> forker = fork);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700153 void StartCrasher(const std::string& crash_type);
154 void FinishCrasher();
155 void AssertDeath(int signo);
156};
157
158CrasherTest::CrasherTest() {
159 previous_wait_for_gdb = android::base::GetBoolProperty(kWaitForGdbKey, false);
160 android::base::SetProperty(kWaitForGdbKey, "0");
161}
162
163CrasherTest::~CrasherTest() {
164 if (crasher_pid != -1) {
165 kill(crasher_pid, SIGKILL);
166 int status;
167 waitpid(crasher_pid, &status, WUNTRACED);
168 }
169
170 android::base::SetProperty(kWaitForGdbKey, previous_wait_for_gdb ? "1" : "0");
171}
172
Narayan Kamatha73df602017-05-24 15:07:25 +0100173void CrasherTest::StartIntercept(unique_fd* output_fd, DebuggerdDumpType intercept_type) {
Josh Gaocbe70cb2016-10-18 18:17:52 -0700174 if (crasher_pid == -1) {
175 FAIL() << "crasher hasn't been started";
176 }
177
Narayan Kamathca5e9082017-06-02 15:42:06 +0100178 InterceptStatus status;
179 tombstoned_intercept(crasher_pid, &this->intercept_fd, output_fd, &status, intercept_type);
180 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700181}
182
183void CrasherTest::FinishIntercept(int* result) {
184 InterceptResponse response;
185
186 // Timeout for tombstoned intercept is 10 seconds.
187 ssize_t rc = TIMEOUT(20, read(intercept_fd.get(), &response, sizeof(response)));
188 if (rc == -1) {
189 FAIL() << "failed to read response from tombstoned: " << strerror(errno);
190 } else if (rc == 0) {
191 *result = -1;
192 } else if (rc != sizeof(response)) {
193 FAIL() << "received packet of unexpected length from tombstoned: expected " << sizeof(response)
194 << ", received " << rc;
195 } else {
Josh Gao460b3362017-03-30 16:40:47 -0700196 *result = response.status == InterceptStatus::kStarted ? 1 : 0;
Josh Gaocbe70cb2016-10-18 18:17:52 -0700197 }
198}
199
Josh Gao2e7b8e22017-05-04 17:12:57 -0700200void CrasherTest::StartProcess(std::function<void()> function, std::function<pid_t()> forker) {
Josh Gaofca7ca32017-01-23 12:05:35 -0800201 unique_fd read_pipe;
Josh Gaocbe70cb2016-10-18 18:17:52 -0700202 unique_fd crasher_read_pipe;
203 if (!Pipe(&crasher_read_pipe, &crasher_pipe)) {
204 FAIL() << "failed to create pipe: " << strerror(errno);
205 }
206
Josh Gao2e7b8e22017-05-04 17:12:57 -0700207 crasher_pid = forker();
Josh Gaocbe70cb2016-10-18 18:17:52 -0700208 if (crasher_pid == -1) {
209 FAIL() << "fork failed: " << strerror(errno);
210 } else if (crasher_pid == 0) {
Josh Gao502cfd22017-02-17 01:39:15 -0800211 char dummy;
212 crasher_pipe.reset();
213 TEMP_FAILURE_RETRY(read(crasher_read_pipe.get(), &dummy, 1));
Josh Gaofca7ca32017-01-23 12:05:35 -0800214 function();
215 _exit(0);
216 }
217}
218
Josh Gaocbe70cb2016-10-18 18:17:52 -0700219void CrasherTest::FinishCrasher() {
220 if (crasher_pipe == -1) {
221 FAIL() << "crasher pipe uninitialized";
222 }
223
224 ssize_t rc = write(crasher_pipe.get(), "\n", 1);
225 if (rc == -1) {
226 FAIL() << "failed to write to crasher pipe: " << strerror(errno);
227 } else if (rc == 0) {
228 FAIL() << "crasher pipe was closed";
229 }
230}
231
232void CrasherTest::AssertDeath(int signo) {
233 int status;
234 pid_t pid = TIMEOUT(5, waitpid(crasher_pid, &status, 0));
235 if (pid != crasher_pid) {
Josh Gao2b2ae0c2017-08-21 14:31:17 -0700236 printf("failed to wait for crasher (pid %d)\n", crasher_pid);
237 sleep(100);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700238 FAIL() << "failed to wait for crasher: " << strerror(errno);
239 }
240
Josh Gaoe06f2a42017-04-27 16:50:38 -0700241 if (signo == 0) {
242 ASSERT_TRUE(WIFEXITED(status));
243 ASSERT_EQ(0, WEXITSTATUS(signo));
244 } else {
245 ASSERT_FALSE(WIFEXITED(status));
246 ASSERT_TRUE(WIFSIGNALED(status)) << "crasher didn't terminate via a signal";
247 ASSERT_EQ(signo, WTERMSIG(status));
Josh Gaocbe70cb2016-10-18 18:17:52 -0700248 }
Josh Gaocbe70cb2016-10-18 18:17:52 -0700249 crasher_pid = -1;
250}
251
252static void ConsumeFd(unique_fd fd, std::string* output) {
253 constexpr size_t read_length = PAGE_SIZE;
254 std::string result;
255
256 while (true) {
257 size_t offset = result.size();
258 result.resize(result.size() + PAGE_SIZE);
259 ssize_t rc = TEMP_FAILURE_RETRY(read(fd.get(), &result[offset], read_length));
260 if (rc == -1) {
261 FAIL() << "read failed: " << strerror(errno);
262 } else if (rc == 0) {
263 result.resize(result.size() - PAGE_SIZE);
264 break;
265 }
266
267 result.resize(result.size() - PAGE_SIZE + rc);
268 }
269
270 *output = std::move(result);
271}
272
273TEST_F(CrasherTest, smoke) {
274 int intercept_result;
275 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800276 StartProcess([]() {
277 *reinterpret_cast<volatile char*>(0xdead) = '1';
278 });
279
Josh Gaocbe70cb2016-10-18 18:17:52 -0700280 StartIntercept(&output_fd);
281 FinishCrasher();
282 AssertDeath(SIGSEGV);
283 FinishIntercept(&intercept_result);
284
285 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
286
287 std::string result;
288 ConsumeFd(std::move(output_fd), &result);
289 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\), code 1 \(SEGV_MAPERR\), fault addr 0xdead)");
290}
291
Josh Gaocdea7502017-11-01 15:00:40 -0700292TEST_F(CrasherTest, LD_PRELOAD) {
293 int intercept_result;
294 unique_fd output_fd;
295 StartProcess([]() {
296 setenv("LD_PRELOAD", "nonexistent.so", 1);
297 *reinterpret_cast<volatile char*>(0xdead) = '1';
298 });
299
300 StartIntercept(&output_fd);
301 FinishCrasher();
302 AssertDeath(SIGSEGV);
303 FinishIntercept(&intercept_result);
304
305 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
306
307 std::string result;
308 ConsumeFd(std::move(output_fd), &result);
309 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\), code 1 \(SEGV_MAPERR\), fault addr 0xdead)");
310}
311
Josh Gaocbe70cb2016-10-18 18:17:52 -0700312TEST_F(CrasherTest, abort) {
313 int intercept_result;
314 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800315 StartProcess([]() {
316 abort();
317 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700318 StartIntercept(&output_fd);
319 FinishCrasher();
320 AssertDeath(SIGABRT);
321 FinishIntercept(&intercept_result);
322
323 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
324
325 std::string result;
326 ConsumeFd(std::move(output_fd), &result);
Andreas Gampe26cbafb2017-06-22 20:14:43 -0700327 ASSERT_BACKTRACE_FRAME(result, "abort");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700328}
329
330TEST_F(CrasherTest, signal) {
331 int intercept_result;
332 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800333 StartProcess([]() {
Josh Gao2b2ae0c2017-08-21 14:31:17 -0700334 while (true) {
335 sleep(1);
336 }
Josh Gao502cfd22017-02-17 01:39:15 -0800337 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700338 StartIntercept(&output_fd);
Josh Gao2b2ae0c2017-08-21 14:31:17 -0700339 FinishCrasher();
Josh Gaocbe70cb2016-10-18 18:17:52 -0700340 ASSERT_EQ(0, kill(crasher_pid, SIGSEGV));
341
342 AssertDeath(SIGSEGV);
343 FinishIntercept(&intercept_result);
344
345 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
346
347 std::string result;
348 ConsumeFd(std::move(output_fd), &result);
349 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\), code 0 \(SI_USER\), fault addr --------)");
350 ASSERT_MATCH(result, R"(backtrace:)");
351}
352
353TEST_F(CrasherTest, abort_message) {
354 int intercept_result;
355 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800356 StartProcess([]() {
Josh Gao1cc7bd82018-02-13 13:16:17 -0800357 // Arrived at experimentally;
358 // logd truncates at 4062.
359 // strlen("Abort message: ''") is 17.
360 // That's 4045, but we also want a NUL.
361 char buf[4045 + 1];
362 memset(buf, 'x', sizeof(buf));
363 buf[sizeof(buf) - 1] = '\0';
364 android_set_abort_message(buf);
Josh Gao502cfd22017-02-17 01:39:15 -0800365 abort();
366 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700367 StartIntercept(&output_fd);
368 FinishCrasher();
369 AssertDeath(SIGABRT);
370 FinishIntercept(&intercept_result);
371
372 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
373
374 std::string result;
375 ConsumeFd(std::move(output_fd), &result);
Josh Gao1cc7bd82018-02-13 13:16:17 -0800376 ASSERT_MATCH(result, R"(Abort message: 'x{4045}')");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700377}
378
Josh Gaoe06f2a42017-04-27 16:50:38 -0700379TEST_F(CrasherTest, abort_message_backtrace) {
380 int intercept_result;
381 unique_fd output_fd;
382 StartProcess([]() {
383 android_set_abort_message("not actually aborting");
384 raise(DEBUGGER_SIGNAL);
385 exit(0);
386 });
387 StartIntercept(&output_fd);
388 FinishCrasher();
389 AssertDeath(0);
390 FinishIntercept(&intercept_result);
391
392 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
393
394 std::string result;
395 ConsumeFd(std::move(output_fd), &result);
396 ASSERT_NOT_MATCH(result, R"(Abort message:)");
397}
398
Josh Gaocbe70cb2016-10-18 18:17:52 -0700399TEST_F(CrasherTest, intercept_timeout) {
400 int intercept_result;
401 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800402 StartProcess([]() {
403 abort();
404 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700405 StartIntercept(&output_fd);
406
407 // Don't let crasher finish until we timeout.
408 FinishIntercept(&intercept_result);
409
410 ASSERT_NE(1, intercept_result) << "tombstoned reported success? (intercept_result = "
411 << intercept_result << ")";
412
413 FinishCrasher();
414 AssertDeath(SIGABRT);
415}
416
417TEST_F(CrasherTest, wait_for_gdb) {
418 if (!android::base::SetProperty(kWaitForGdbKey, "1")) {
419 FAIL() << "failed to enable wait_for_gdb";
420 }
421 sleep(1);
422
Josh Gao502cfd22017-02-17 01:39:15 -0800423 StartProcess([]() {
424 abort();
425 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700426 FinishCrasher();
427
428 int status;
429 ASSERT_EQ(crasher_pid, waitpid(crasher_pid, &status, WUNTRACED));
430 ASSERT_TRUE(WIFSTOPPED(status));
431 ASSERT_EQ(SIGSTOP, WSTOPSIG(status));
432
433 ASSERT_EQ(0, kill(crasher_pid, SIGCONT));
434
435 AssertDeath(SIGABRT);
436}
437
Josh Gaocbe70cb2016-10-18 18:17:52 -0700438TEST_F(CrasherTest, backtrace) {
439 std::string result;
440 int intercept_result;
441 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800442
443 StartProcess([]() {
444 abort();
445 });
Narayan Kamatha73df602017-05-24 15:07:25 +0100446 StartIntercept(&output_fd, kDebuggerdNativeBacktrace);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700447
448 std::this_thread::sleep_for(500ms);
449
450 sigval val;
451 val.sival_int = 1;
452 ASSERT_EQ(0, sigqueue(crasher_pid, DEBUGGER_SIGNAL, val)) << strerror(errno);
453 FinishIntercept(&intercept_result);
454 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
455 ConsumeFd(std::move(output_fd), &result);
Jaesung Chung58778e12017-06-15 18:20:34 +0900456 ASSERT_BACKTRACE_FRAME(result, "read");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700457
458 int status;
459 ASSERT_EQ(0, waitpid(crasher_pid, &status, WNOHANG | WUNTRACED));
460
461 StartIntercept(&output_fd);
462 FinishCrasher();
463 AssertDeath(SIGABRT);
464 FinishIntercept(&intercept_result);
465 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
466 ConsumeFd(std::move(output_fd), &result);
Andreas Gampe26cbafb2017-06-22 20:14:43 -0700467 ASSERT_BACKTRACE_FRAME(result, "abort");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700468}
Josh Gaofca7ca32017-01-23 12:05:35 -0800469
470TEST_F(CrasherTest, PR_SET_DUMPABLE_0_crash) {
Josh Gao502cfd22017-02-17 01:39:15 -0800471 int intercept_result;
472 unique_fd output_fd;
Josh Gaofca7ca32017-01-23 12:05:35 -0800473 StartProcess([]() {
474 prctl(PR_SET_DUMPABLE, 0);
Josh Gao502cfd22017-02-17 01:39:15 -0800475 abort();
Josh Gaofca7ca32017-01-23 12:05:35 -0800476 });
Josh Gao502cfd22017-02-17 01:39:15 -0800477
478 StartIntercept(&output_fd);
479 FinishCrasher();
480 AssertDeath(SIGABRT);
481 FinishIntercept(&intercept_result);
482
483 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
484
485 std::string result;
486 ConsumeFd(std::move(output_fd), &result);
Andreas Gampe26cbafb2017-06-22 20:14:43 -0700487 ASSERT_BACKTRACE_FRAME(result, "abort");
Josh Gaofca7ca32017-01-23 12:05:35 -0800488}
489
Josh Gao502cfd22017-02-17 01:39:15 -0800490TEST_F(CrasherTest, capabilities) {
491 ASSERT_EQ(0U, getuid()) << "capability test requires root";
492
Josh Gaofca7ca32017-01-23 12:05:35 -0800493 StartProcess([]() {
Josh Gao502cfd22017-02-17 01:39:15 -0800494 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) != 0) {
495 err(1, "failed to set PR_SET_KEEPCAPS");
496 }
497
498 if (setresuid(1, 1, 1) != 0) {
499 err(1, "setresuid failed");
500 }
501
502 __user_cap_header_struct capheader;
503 __user_cap_data_struct capdata[2];
504 memset(&capheader, 0, sizeof(capheader));
505 memset(&capdata, 0, sizeof(capdata));
506
507 capheader.version = _LINUX_CAPABILITY_VERSION_3;
508 capheader.pid = 0;
509
510 // Turn on every third capability.
511 static_assert(CAP_LAST_CAP > 33, "CAP_LAST_CAP <= 32");
512 for (int i = 0; i < CAP_LAST_CAP; i += 3) {
513 capdata[CAP_TO_INDEX(i)].permitted |= CAP_TO_MASK(i);
514 capdata[CAP_TO_INDEX(i)].effective |= CAP_TO_MASK(i);
515 }
516
517 // Make sure CAP_SYS_PTRACE is off.
518 capdata[CAP_TO_INDEX(CAP_SYS_PTRACE)].permitted &= ~(CAP_TO_MASK(CAP_SYS_PTRACE));
519 capdata[CAP_TO_INDEX(CAP_SYS_PTRACE)].effective &= ~(CAP_TO_MASK(CAP_SYS_PTRACE));
520
521 if (capset(&capheader, &capdata[0]) != 0) {
522 err(1, "capset failed");
523 }
524
525 if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_CLEAR_ALL, 0, 0, 0) != 0) {
526 err(1, "failed to drop ambient capabilities");
527 }
528
Josh Gaoa5199a92017-04-03 13:18:34 -0700529 pthread_setname_np(pthread_self(), "thread_name");
Josh Gao502cfd22017-02-17 01:39:15 -0800530 raise(SIGSYS);
Josh Gaofca7ca32017-01-23 12:05:35 -0800531 });
Josh Gao502cfd22017-02-17 01:39:15 -0800532
533 unique_fd output_fd;
534 StartIntercept(&output_fd);
535 FinishCrasher();
536 AssertDeath(SIGSYS);
537
538 std::string result;
539 int intercept_result;
540 FinishIntercept(&intercept_result);
541 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
542 ConsumeFd(std::move(output_fd), &result);
Josh Gaoa5199a92017-04-03 13:18:34 -0700543 ASSERT_MATCH(result, R"(name: thread_name\s+>>> .+debuggerd_test(32|64) <<<)");
Jaesung Chung58778e12017-06-15 18:20:34 +0900544 ASSERT_BACKTRACE_FRAME(result, "tgkill");
Josh Gaofca7ca32017-01-23 12:05:35 -0800545}
Josh Gaoc3c8c022017-02-13 16:36:18 -0800546
Josh Gao2e7b8e22017-05-04 17:12:57 -0700547TEST_F(CrasherTest, fake_pid) {
548 int intercept_result;
549 unique_fd output_fd;
550
551 // Prime the getpid/gettid caches.
552 UNUSED(getpid());
553 UNUSED(gettid());
554
555 std::function<pid_t()> clone_fn = []() {
556 return syscall(__NR_clone, SIGCHLD, nullptr, nullptr, nullptr, nullptr);
557 };
558 StartProcess(
559 []() {
560 ASSERT_NE(getpid(), syscall(__NR_getpid));
561 ASSERT_NE(gettid(), syscall(__NR_gettid));
562 raise(SIGSEGV);
563 },
564 clone_fn);
565
566 StartIntercept(&output_fd);
567 FinishCrasher();
568 AssertDeath(SIGSEGV);
569 FinishIntercept(&intercept_result);
570
571 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
572
573 std::string result;
574 ConsumeFd(std::move(output_fd), &result);
Jaesung Chung58778e12017-06-15 18:20:34 +0900575 ASSERT_BACKTRACE_FRAME(result, "tgkill");
Josh Gao2e7b8e22017-05-04 17:12:57 -0700576}
577
Josh Gaoe04ca272018-01-16 15:38:17 -0800578static const char* const kDebuggerdSeccompPolicy =
579 "/system/etc/seccomp_policy/crash_dump." ABI_STRING ".policy";
580
Josh Gao70adac62018-02-22 11:38:33 -0800581static pid_t seccomp_fork_impl(void (*prejail)()) {
Josh Gaoe04ca272018-01-16 15:38:17 -0800582 unique_fd policy_fd(open(kDebuggerdSeccompPolicy, O_RDONLY | O_CLOEXEC));
583 if (policy_fd == -1) {
584 LOG(FATAL) << "failed to open policy " << kDebuggerdSeccompPolicy;
585 }
586
587 ScopedMinijail jail{minijail_new()};
588 if (!jail) {
589 LOG(FATAL) << "failed to create minijail";
590 }
591
592 minijail_no_new_privs(jail.get());
593 minijail_log_seccomp_filter_failures(jail.get());
594 minijail_use_seccomp_filter(jail.get());
595 minijail_parse_seccomp_filters_from_fd(jail.get(), policy_fd.release());
596
597 pid_t result = fork();
598 if (result == -1) {
599 return result;
600 } else if (result != 0) {
601 return result;
602 }
603
604 // Spawn and detach a thread that spins forever.
605 std::atomic<bool> thread_ready(false);
606 std::thread thread([&jail, &thread_ready]() {
607 minijail_enter(jail.get());
608 thread_ready = true;
609 for (;;)
610 ;
611 });
612 thread.detach();
613
614 while (!thread_ready) {
615 continue;
616 }
617
Josh Gao70adac62018-02-22 11:38:33 -0800618 if (prejail) {
619 prejail();
620 }
621
Josh Gaoe04ca272018-01-16 15:38:17 -0800622 minijail_enter(jail.get());
623 return result;
624}
625
Josh Gao70adac62018-02-22 11:38:33 -0800626static pid_t seccomp_fork() {
627 return seccomp_fork_impl(nullptr);
628}
629
Josh Gaoe04ca272018-01-16 15:38:17 -0800630TEST_F(CrasherTest, seccomp_crash) {
631 int intercept_result;
632 unique_fd output_fd;
633
634 StartProcess([]() { abort(); }, &seccomp_fork);
635
636 StartIntercept(&output_fd);
637 FinishCrasher();
638 AssertDeath(SIGABRT);
639 FinishIntercept(&intercept_result);
640 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
641
642 std::string result;
643 ConsumeFd(std::move(output_fd), &result);
644 ASSERT_BACKTRACE_FRAME(result, "abort");
645}
646
Josh Gao70adac62018-02-22 11:38:33 -0800647static pid_t seccomp_fork_rlimit() {
648 return seccomp_fork_impl([]() {
649 struct rlimit rlim = {
650 .rlim_cur = 512 * 1024 * 1024,
651 .rlim_max = 512 * 1024 * 1024,
652 };
653
654 if (setrlimit(RLIMIT_AS, &rlim) != 0) {
655 raise(SIGINT);
656 }
657 });
658}
659
660TEST_F(CrasherTest, seccomp_crash_oom) {
661 int intercept_result;
662 unique_fd output_fd;
663
664 StartProcess(
665 []() {
666 std::vector<void*> vec;
667 for (int i = 0; i < 512; ++i) {
668 char* buf = static_cast<char*>(malloc(1024 * 1024));
669 if (!buf) {
670 abort();
671 }
672 memset(buf, 0xff, 1024 * 1024);
673 vec.push_back(buf);
674 }
675 },
676 &seccomp_fork_rlimit);
677
678 StartIntercept(&output_fd);
679 FinishCrasher();
680 AssertDeath(SIGABRT);
681 FinishIntercept(&intercept_result);
682 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
683
684 // We can't actually generate a backtrace, just make sure that the process terminates.
685}
686
Josh Gaoe04ca272018-01-16 15:38:17 -0800687__attribute__((noinline)) extern "C" bool raise_debugger_signal(DebuggerdDumpType dump_type) {
688 siginfo_t siginfo;
689 siginfo.si_code = SI_QUEUE;
690 siginfo.si_pid = getpid();
691 siginfo.si_uid = getuid();
692
693 if (dump_type != kDebuggerdNativeBacktrace && dump_type != kDebuggerdTombstone) {
694 PLOG(FATAL) << "invalid dump type";
695 }
696
697 siginfo.si_value.sival_int = dump_type == kDebuggerdNativeBacktrace;
698
699 if (syscall(__NR_rt_tgsigqueueinfo, getpid(), gettid(), DEBUGGER_SIGNAL, &siginfo) != 0) {
700 PLOG(ERROR) << "libdebuggerd_client: failed to send signal to self";
701 return false;
702 }
703
704 return true;
705}
706
707TEST_F(CrasherTest, seccomp_tombstone) {
708 int intercept_result;
709 unique_fd output_fd;
710
711 static const auto dump_type = kDebuggerdTombstone;
712 StartProcess(
713 []() {
714 raise_debugger_signal(dump_type);
715 _exit(0);
716 },
717 &seccomp_fork);
718
719 StartIntercept(&output_fd, dump_type);
720 FinishCrasher();
721 AssertDeath(0);
722 FinishIntercept(&intercept_result);
723 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
724
725 std::string result;
726 ConsumeFd(std::move(output_fd), &result);
727 ASSERT_BACKTRACE_FRAME(result, "raise_debugger_signal");
728}
729
730TEST_F(CrasherTest, seccomp_backtrace) {
731 int intercept_result;
732 unique_fd output_fd;
733
734 static const auto dump_type = kDebuggerdNativeBacktrace;
735 StartProcess(
736 []() {
737 raise_debugger_signal(dump_type);
738 _exit(0);
739 },
740 &seccomp_fork);
741
742 StartIntercept(&output_fd, dump_type);
743 FinishCrasher();
744 AssertDeath(0);
745 FinishIntercept(&intercept_result);
746 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
747
748 std::string result;
749 ConsumeFd(std::move(output_fd), &result);
750 ASSERT_BACKTRACE_FRAME(result, "raise_debugger_signal");
751}
752
753TEST_F(CrasherTest, seccomp_crash_logcat) {
754 StartProcess([]() { abort(); }, &seccomp_fork);
755 FinishCrasher();
756
757 // Make sure we don't get SIGSYS when trying to dump a crash to logcat.
758 AssertDeath(SIGABRT);
759}
760
Josh Gaofd13bf02017-08-18 15:37:26 -0700761TEST_F(CrasherTest, competing_tracer) {
762 int intercept_result;
763 unique_fd output_fd;
764 StartProcess([]() {
Josh Gao2b2ae0c2017-08-21 14:31:17 -0700765 raise(SIGABRT);
Josh Gaofd13bf02017-08-18 15:37:26 -0700766 });
767
768 StartIntercept(&output_fd);
Josh Gaofd13bf02017-08-18 15:37:26 -0700769
770 ASSERT_EQ(0, ptrace(PTRACE_SEIZE, crasher_pid, 0, 0));
Josh Gao2b2ae0c2017-08-21 14:31:17 -0700771 FinishCrasher();
Josh Gaofd13bf02017-08-18 15:37:26 -0700772
773 int status;
774 ASSERT_EQ(crasher_pid, waitpid(crasher_pid, &status, 0));
775 ASSERT_TRUE(WIFSTOPPED(status));
776 ASSERT_EQ(SIGABRT, WSTOPSIG(status));
777
778 ASSERT_EQ(0, ptrace(PTRACE_CONT, crasher_pid, 0, SIGABRT));
779 FinishIntercept(&intercept_result);
780 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
781
782 std::string result;
783 ConsumeFd(std::move(output_fd), &result);
784 std::string regex = R"(failed to attach to thread \d+, already traced by )";
785 regex += std::to_string(gettid());
786 regex += R"( \(.+debuggerd_test)";
787 ASSERT_MATCH(result, regex.c_str());
788
Josh Gao2b2ae0c2017-08-21 14:31:17 -0700789 ASSERT_EQ(crasher_pid, waitpid(crasher_pid, &status, 0));
790 ASSERT_TRUE(WIFSTOPPED(status));
791 ASSERT_EQ(SIGABRT, WSTOPSIG(status));
792
Josh Gaofd13bf02017-08-18 15:37:26 -0700793 ASSERT_EQ(0, ptrace(PTRACE_DETACH, crasher_pid, 0, SIGABRT));
794 AssertDeath(SIGABRT);
795}
796
Josh Gaoc3c8c022017-02-13 16:36:18 -0800797TEST(crash_dump, zombie) {
798 pid_t forkpid = fork();
799
Josh Gaoc3c8c022017-02-13 16:36:18 -0800800 pid_t rc;
801 int status;
802
803 if (forkpid == 0) {
804 errno = 0;
805 rc = waitpid(-1, &status, WNOHANG | __WALL | __WNOTHREAD);
806 if (rc != -1 || errno != ECHILD) {
807 errx(2, "first waitpid returned %d (%s), expected failure with ECHILD", rc, strerror(errno));
808 }
809
810 raise(DEBUGGER_SIGNAL);
811
812 errno = 0;
813 rc = waitpid(-1, &status, __WALL | __WNOTHREAD);
814 if (rc != -1 || errno != ECHILD) {
815 errx(2, "second waitpid returned %d (%s), expected failure with ECHILD", rc, strerror(errno));
816 }
817 _exit(0);
818 } else {
819 rc = waitpid(forkpid, &status, 0);
820 ASSERT_EQ(forkpid, rc);
821 ASSERT_TRUE(WIFEXITED(status));
822 ASSERT_EQ(0, WEXITSTATUS(status));
823 }
824}
Josh Gao352a8452017-03-30 16:46:21 -0700825
826TEST(tombstoned, no_notify) {
827 // Do this a few times.
828 for (int i = 0; i < 3; ++i) {
829 pid_t pid = 123'456'789 + i;
830
831 unique_fd intercept_fd, output_fd;
Narayan Kamathca5e9082017-06-02 15:42:06 +0100832 InterceptStatus status;
833 tombstoned_intercept(pid, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
834 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gao352a8452017-03-30 16:46:21 -0700835
836 {
837 unique_fd tombstoned_socket, input_fd;
Narayan Kamatha73df602017-05-24 15:07:25 +0100838 ASSERT_TRUE(tombstoned_connect(pid, &tombstoned_socket, &input_fd, kDebuggerdTombstone));
Josh Gao352a8452017-03-30 16:46:21 -0700839 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), &pid, sizeof(pid)));
840 }
841
842 pid_t read_pid;
843 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), &read_pid, sizeof(read_pid)));
844 ASSERT_EQ(read_pid, pid);
845 }
846}
847
848TEST(tombstoned, stress) {
849 // Spawn threads to simultaneously do a bunch of failing dumps and a bunch of successful dumps.
850 static constexpr int kDumpCount = 100;
851
852 std::atomic<bool> start(false);
853 std::vector<std::thread> threads;
854 threads.emplace_back([&start]() {
855 while (!start) {
856 continue;
857 }
858
859 // Use a way out of range pid, to avoid stomping on an actual process.
860 pid_t pid_base = 1'000'000;
861
862 for (int dump = 0; dump < kDumpCount; ++dump) {
863 pid_t pid = pid_base + dump;
864
865 unique_fd intercept_fd, output_fd;
Narayan Kamathca5e9082017-06-02 15:42:06 +0100866 InterceptStatus status;
867 tombstoned_intercept(pid, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
868 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gao352a8452017-03-30 16:46:21 -0700869
870 // Pretend to crash, and then immediately close the socket.
871 unique_fd sockfd(socket_local_client(kTombstonedCrashSocketName,
872 ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_SEQPACKET));
873 if (sockfd == -1) {
874 FAIL() << "failed to connect to tombstoned: " << strerror(errno);
875 }
876 TombstonedCrashPacket packet = {};
877 packet.packet_type = CrashPacketType::kDumpRequest;
878 packet.packet.dump_request.pid = pid;
879 if (TEMP_FAILURE_RETRY(write(sockfd, &packet, sizeof(packet))) != sizeof(packet)) {
880 FAIL() << "failed to write to tombstoned: " << strerror(errno);
881 }
882
883 continue;
884 }
885 });
886
887 threads.emplace_back([&start]() {
888 while (!start) {
889 continue;
890 }
891
892 // Use a way out of range pid, to avoid stomping on an actual process.
893 pid_t pid_base = 2'000'000;
894
895 for (int dump = 0; dump < kDumpCount; ++dump) {
896 pid_t pid = pid_base + dump;
897
898 unique_fd intercept_fd, output_fd;
Narayan Kamathca5e9082017-06-02 15:42:06 +0100899 InterceptStatus status;
900 tombstoned_intercept(pid, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
901 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gao352a8452017-03-30 16:46:21 -0700902
903 {
904 unique_fd tombstoned_socket, input_fd;
Narayan Kamatha73df602017-05-24 15:07:25 +0100905 ASSERT_TRUE(tombstoned_connect(pid, &tombstoned_socket, &input_fd, kDebuggerdTombstone));
Josh Gao352a8452017-03-30 16:46:21 -0700906 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), &pid, sizeof(pid)));
907 tombstoned_notify_completion(tombstoned_socket.get());
908 }
909
910 // TODO: Fix the race that requires this sleep.
911 std::this_thread::sleep_for(50ms);
912
913 pid_t read_pid;
914 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), &read_pid, sizeof(read_pid)));
915 ASSERT_EQ(read_pid, pid);
916 }
917 });
918
919 start = true;
920
921 for (std::thread& thread : threads) {
922 thread.join();
923 }
924}
Narayan Kamathca5e9082017-06-02 15:42:06 +0100925
926TEST(tombstoned, java_trace_intercept_smoke) {
927 // Using a "real" PID is a little dangerous here - if the test fails
928 // or crashes, we might end up getting a bogus / unreliable stack
929 // trace.
930 const pid_t self = getpid();
931
932 unique_fd intercept_fd, output_fd;
933 InterceptStatus status;
934 tombstoned_intercept(self, &intercept_fd, &output_fd, &status, kDebuggerdJavaBacktrace);
935 ASSERT_EQ(InterceptStatus::kRegistered, status);
936
937 // First connect to tombstoned requesting a native backtrace. This
938 // should result in a "regular" FD and not the installed intercept.
939 const char native[] = "native";
940 unique_fd tombstoned_socket, input_fd;
941 ASSERT_TRUE(tombstoned_connect(self, &tombstoned_socket, &input_fd, kDebuggerdNativeBacktrace));
942 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), native, sizeof(native)));
943 tombstoned_notify_completion(tombstoned_socket.get());
944
945 // Then, connect to tombstoned asking for a java backtrace. This *should*
946 // trigger the intercept.
947 const char java[] = "java";
948 ASSERT_TRUE(tombstoned_connect(self, &tombstoned_socket, &input_fd, kDebuggerdJavaBacktrace));
949 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), java, sizeof(java)));
950 tombstoned_notify_completion(tombstoned_socket.get());
951
952 char outbuf[sizeof(java)];
953 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), outbuf, sizeof(outbuf)));
954 ASSERT_STREQ("java", outbuf);
955}
956
957TEST(tombstoned, multiple_intercepts) {
958 const pid_t fake_pid = 1'234'567;
959 unique_fd intercept_fd, output_fd;
960 InterceptStatus status;
961 tombstoned_intercept(fake_pid, &intercept_fd, &output_fd, &status, kDebuggerdJavaBacktrace);
962 ASSERT_EQ(InterceptStatus::kRegistered, status);
963
964 unique_fd intercept_fd_2, output_fd_2;
965 tombstoned_intercept(fake_pid, &intercept_fd_2, &output_fd_2, &status, kDebuggerdNativeBacktrace);
966 ASSERT_EQ(InterceptStatus::kFailedAlreadyRegistered, status);
967}
968
969TEST(tombstoned, intercept_any) {
970 const pid_t fake_pid = 1'234'567;
971
972 unique_fd intercept_fd, output_fd;
973 InterceptStatus status;
974 tombstoned_intercept(fake_pid, &intercept_fd, &output_fd, &status, kDebuggerdNativeBacktrace);
975 ASSERT_EQ(InterceptStatus::kRegistered, status);
976
977 const char any[] = "any";
978 unique_fd tombstoned_socket, input_fd;
979 ASSERT_TRUE(tombstoned_connect(fake_pid, &tombstoned_socket, &input_fd, kDebuggerdAnyIntercept));
980 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), any, sizeof(any)));
981 tombstoned_notify_completion(tombstoned_socket.get());
982
983 char outbuf[sizeof(any)];
984 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), outbuf, sizeof(outbuf)));
985 ASSERT_STREQ("any", outbuf);
986}