blob: 9b64be70f0a8f5a08fb779ca3e91bca7482ffcff [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);
Elliott Hughes89722702018-05-02 10:47:00 -0700349 ASSERT_MATCH(
350 result,
351 R"(signal 11 \(SIGSEGV\), code 0 \(SI_USER from pid \d+, uid \d+\), fault addr --------)");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700352 ASSERT_MATCH(result, R"(backtrace:)");
353}
354
355TEST_F(CrasherTest, abort_message) {
356 int intercept_result;
357 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800358 StartProcess([]() {
Josh Gao1cc7bd82018-02-13 13:16:17 -0800359 // Arrived at experimentally;
360 // logd truncates at 4062.
361 // strlen("Abort message: ''") is 17.
362 // That's 4045, but we also want a NUL.
363 char buf[4045 + 1];
364 memset(buf, 'x', sizeof(buf));
365 buf[sizeof(buf) - 1] = '\0';
366 android_set_abort_message(buf);
Josh Gao502cfd22017-02-17 01:39:15 -0800367 abort();
368 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700369 StartIntercept(&output_fd);
370 FinishCrasher();
371 AssertDeath(SIGABRT);
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);
Josh Gao1cc7bd82018-02-13 13:16:17 -0800378 ASSERT_MATCH(result, R"(Abort message: 'x{4045}')");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700379}
380
Josh Gaoe06f2a42017-04-27 16:50:38 -0700381TEST_F(CrasherTest, abort_message_backtrace) {
382 int intercept_result;
383 unique_fd output_fd;
384 StartProcess([]() {
385 android_set_abort_message("not actually aborting");
386 raise(DEBUGGER_SIGNAL);
387 exit(0);
388 });
389 StartIntercept(&output_fd);
390 FinishCrasher();
391 AssertDeath(0);
392 FinishIntercept(&intercept_result);
393
394 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
395
396 std::string result;
397 ConsumeFd(std::move(output_fd), &result);
398 ASSERT_NOT_MATCH(result, R"(Abort message:)");
399}
400
Josh Gaocbe70cb2016-10-18 18:17:52 -0700401TEST_F(CrasherTest, intercept_timeout) {
402 int intercept_result;
403 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800404 StartProcess([]() {
405 abort();
406 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700407 StartIntercept(&output_fd);
408
409 // Don't let crasher finish until we timeout.
410 FinishIntercept(&intercept_result);
411
412 ASSERT_NE(1, intercept_result) << "tombstoned reported success? (intercept_result = "
413 << intercept_result << ")";
414
415 FinishCrasher();
416 AssertDeath(SIGABRT);
417}
418
419TEST_F(CrasherTest, wait_for_gdb) {
420 if (!android::base::SetProperty(kWaitForGdbKey, "1")) {
421 FAIL() << "failed to enable wait_for_gdb";
422 }
423 sleep(1);
424
Josh Gao502cfd22017-02-17 01:39:15 -0800425 StartProcess([]() {
426 abort();
427 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700428 FinishCrasher();
429
430 int status;
431 ASSERT_EQ(crasher_pid, waitpid(crasher_pid, &status, WUNTRACED));
432 ASSERT_TRUE(WIFSTOPPED(status));
433 ASSERT_EQ(SIGSTOP, WSTOPSIG(status));
434
435 ASSERT_EQ(0, kill(crasher_pid, SIGCONT));
436
437 AssertDeath(SIGABRT);
438}
439
Josh Gaocbe70cb2016-10-18 18:17:52 -0700440TEST_F(CrasherTest, backtrace) {
441 std::string result;
442 int intercept_result;
443 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800444
445 StartProcess([]() {
446 abort();
447 });
Narayan Kamatha73df602017-05-24 15:07:25 +0100448 StartIntercept(&output_fd, kDebuggerdNativeBacktrace);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700449
450 std::this_thread::sleep_for(500ms);
451
452 sigval val;
453 val.sival_int = 1;
454 ASSERT_EQ(0, sigqueue(crasher_pid, DEBUGGER_SIGNAL, val)) << strerror(errno);
455 FinishIntercept(&intercept_result);
456 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
457 ConsumeFd(std::move(output_fd), &result);
Jaesung Chung58778e12017-06-15 18:20:34 +0900458 ASSERT_BACKTRACE_FRAME(result, "read");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700459
460 int status;
461 ASSERT_EQ(0, waitpid(crasher_pid, &status, WNOHANG | WUNTRACED));
462
463 StartIntercept(&output_fd);
464 FinishCrasher();
465 AssertDeath(SIGABRT);
466 FinishIntercept(&intercept_result);
467 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
468 ConsumeFd(std::move(output_fd), &result);
Andreas Gampe26cbafb2017-06-22 20:14:43 -0700469 ASSERT_BACKTRACE_FRAME(result, "abort");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700470}
Josh Gaofca7ca32017-01-23 12:05:35 -0800471
472TEST_F(CrasherTest, PR_SET_DUMPABLE_0_crash) {
Josh Gao502cfd22017-02-17 01:39:15 -0800473 int intercept_result;
474 unique_fd output_fd;
Josh Gaofca7ca32017-01-23 12:05:35 -0800475 StartProcess([]() {
476 prctl(PR_SET_DUMPABLE, 0);
Josh Gao502cfd22017-02-17 01:39:15 -0800477 abort();
Josh Gaofca7ca32017-01-23 12:05:35 -0800478 });
Josh Gao502cfd22017-02-17 01:39:15 -0800479
480 StartIntercept(&output_fd);
481 FinishCrasher();
482 AssertDeath(SIGABRT);
483 FinishIntercept(&intercept_result);
484
485 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
486
487 std::string result;
488 ConsumeFd(std::move(output_fd), &result);
Andreas Gampe26cbafb2017-06-22 20:14:43 -0700489 ASSERT_BACKTRACE_FRAME(result, "abort");
Josh Gaofca7ca32017-01-23 12:05:35 -0800490}
491
Josh Gao502cfd22017-02-17 01:39:15 -0800492TEST_F(CrasherTest, capabilities) {
493 ASSERT_EQ(0U, getuid()) << "capability test requires root";
494
Josh Gaofca7ca32017-01-23 12:05:35 -0800495 StartProcess([]() {
Josh Gao502cfd22017-02-17 01:39:15 -0800496 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) != 0) {
497 err(1, "failed to set PR_SET_KEEPCAPS");
498 }
499
500 if (setresuid(1, 1, 1) != 0) {
501 err(1, "setresuid failed");
502 }
503
504 __user_cap_header_struct capheader;
505 __user_cap_data_struct capdata[2];
506 memset(&capheader, 0, sizeof(capheader));
507 memset(&capdata, 0, sizeof(capdata));
508
509 capheader.version = _LINUX_CAPABILITY_VERSION_3;
510 capheader.pid = 0;
511
512 // Turn on every third capability.
513 static_assert(CAP_LAST_CAP > 33, "CAP_LAST_CAP <= 32");
514 for (int i = 0; i < CAP_LAST_CAP; i += 3) {
515 capdata[CAP_TO_INDEX(i)].permitted |= CAP_TO_MASK(i);
516 capdata[CAP_TO_INDEX(i)].effective |= CAP_TO_MASK(i);
517 }
518
519 // Make sure CAP_SYS_PTRACE is off.
520 capdata[CAP_TO_INDEX(CAP_SYS_PTRACE)].permitted &= ~(CAP_TO_MASK(CAP_SYS_PTRACE));
521 capdata[CAP_TO_INDEX(CAP_SYS_PTRACE)].effective &= ~(CAP_TO_MASK(CAP_SYS_PTRACE));
522
523 if (capset(&capheader, &capdata[0]) != 0) {
524 err(1, "capset failed");
525 }
526
527 if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_CLEAR_ALL, 0, 0, 0) != 0) {
528 err(1, "failed to drop ambient capabilities");
529 }
530
Josh Gaoa5199a92017-04-03 13:18:34 -0700531 pthread_setname_np(pthread_self(), "thread_name");
Josh Gao502cfd22017-02-17 01:39:15 -0800532 raise(SIGSYS);
Josh Gaofca7ca32017-01-23 12:05:35 -0800533 });
Josh Gao502cfd22017-02-17 01:39:15 -0800534
535 unique_fd output_fd;
536 StartIntercept(&output_fd);
537 FinishCrasher();
538 AssertDeath(SIGSYS);
539
540 std::string result;
541 int intercept_result;
542 FinishIntercept(&intercept_result);
543 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
544 ConsumeFd(std::move(output_fd), &result);
Josh Gaoa5199a92017-04-03 13:18:34 -0700545 ASSERT_MATCH(result, R"(name: thread_name\s+>>> .+debuggerd_test(32|64) <<<)");
Jaesung Chung58778e12017-06-15 18:20:34 +0900546 ASSERT_BACKTRACE_FRAME(result, "tgkill");
Josh Gaofca7ca32017-01-23 12:05:35 -0800547}
Josh Gaoc3c8c022017-02-13 16:36:18 -0800548
Josh Gao2e7b8e22017-05-04 17:12:57 -0700549TEST_F(CrasherTest, fake_pid) {
550 int intercept_result;
551 unique_fd output_fd;
552
553 // Prime the getpid/gettid caches.
554 UNUSED(getpid());
555 UNUSED(gettid());
556
557 std::function<pid_t()> clone_fn = []() {
558 return syscall(__NR_clone, SIGCHLD, nullptr, nullptr, nullptr, nullptr);
559 };
560 StartProcess(
561 []() {
562 ASSERT_NE(getpid(), syscall(__NR_getpid));
563 ASSERT_NE(gettid(), syscall(__NR_gettid));
564 raise(SIGSEGV);
565 },
566 clone_fn);
567
568 StartIntercept(&output_fd);
569 FinishCrasher();
570 AssertDeath(SIGSEGV);
571 FinishIntercept(&intercept_result);
572
573 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
574
575 std::string result;
576 ConsumeFd(std::move(output_fd), &result);
Jaesung Chung58778e12017-06-15 18:20:34 +0900577 ASSERT_BACKTRACE_FRAME(result, "tgkill");
Josh Gao2e7b8e22017-05-04 17:12:57 -0700578}
579
Josh Gaoe04ca272018-01-16 15:38:17 -0800580static const char* const kDebuggerdSeccompPolicy =
581 "/system/etc/seccomp_policy/crash_dump." ABI_STRING ".policy";
582
Josh Gao70adac62018-02-22 11:38:33 -0800583static pid_t seccomp_fork_impl(void (*prejail)()) {
Josh Gaoe04ca272018-01-16 15:38:17 -0800584 unique_fd policy_fd(open(kDebuggerdSeccompPolicy, O_RDONLY | O_CLOEXEC));
585 if (policy_fd == -1) {
586 LOG(FATAL) << "failed to open policy " << kDebuggerdSeccompPolicy;
587 }
588
589 ScopedMinijail jail{minijail_new()};
590 if (!jail) {
591 LOG(FATAL) << "failed to create minijail";
592 }
593
594 minijail_no_new_privs(jail.get());
595 minijail_log_seccomp_filter_failures(jail.get());
596 minijail_use_seccomp_filter(jail.get());
597 minijail_parse_seccomp_filters_from_fd(jail.get(), policy_fd.release());
598
599 pid_t result = fork();
600 if (result == -1) {
601 return result;
602 } else if (result != 0) {
603 return result;
604 }
605
606 // Spawn and detach a thread that spins forever.
607 std::atomic<bool> thread_ready(false);
608 std::thread thread([&jail, &thread_ready]() {
609 minijail_enter(jail.get());
610 thread_ready = true;
611 for (;;)
612 ;
613 });
614 thread.detach();
615
616 while (!thread_ready) {
617 continue;
618 }
619
Josh Gao70adac62018-02-22 11:38:33 -0800620 if (prejail) {
621 prejail();
622 }
623
Josh Gaoe04ca272018-01-16 15:38:17 -0800624 minijail_enter(jail.get());
625 return result;
626}
627
Josh Gao70adac62018-02-22 11:38:33 -0800628static pid_t seccomp_fork() {
629 return seccomp_fork_impl(nullptr);
630}
631
Josh Gaoe04ca272018-01-16 15:38:17 -0800632TEST_F(CrasherTest, seccomp_crash) {
633 int intercept_result;
634 unique_fd output_fd;
635
636 StartProcess([]() { abort(); }, &seccomp_fork);
637
638 StartIntercept(&output_fd);
639 FinishCrasher();
640 AssertDeath(SIGABRT);
641 FinishIntercept(&intercept_result);
642 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
643
644 std::string result;
645 ConsumeFd(std::move(output_fd), &result);
646 ASSERT_BACKTRACE_FRAME(result, "abort");
647}
648
Josh Gao70adac62018-02-22 11:38:33 -0800649static pid_t seccomp_fork_rlimit() {
650 return seccomp_fork_impl([]() {
651 struct rlimit rlim = {
652 .rlim_cur = 512 * 1024 * 1024,
653 .rlim_max = 512 * 1024 * 1024,
654 };
655
656 if (setrlimit(RLIMIT_AS, &rlim) != 0) {
657 raise(SIGINT);
658 }
659 });
660}
661
662TEST_F(CrasherTest, seccomp_crash_oom) {
663 int intercept_result;
664 unique_fd output_fd;
665
666 StartProcess(
667 []() {
668 std::vector<void*> vec;
669 for (int i = 0; i < 512; ++i) {
670 char* buf = static_cast<char*>(malloc(1024 * 1024));
671 if (!buf) {
672 abort();
673 }
674 memset(buf, 0xff, 1024 * 1024);
675 vec.push_back(buf);
676 }
677 },
678 &seccomp_fork_rlimit);
679
680 StartIntercept(&output_fd);
681 FinishCrasher();
682 AssertDeath(SIGABRT);
683 FinishIntercept(&intercept_result);
684 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
685
686 // We can't actually generate a backtrace, just make sure that the process terminates.
687}
688
Josh Gaoe04ca272018-01-16 15:38:17 -0800689__attribute__((noinline)) extern "C" bool raise_debugger_signal(DebuggerdDumpType dump_type) {
690 siginfo_t siginfo;
691 siginfo.si_code = SI_QUEUE;
692 siginfo.si_pid = getpid();
693 siginfo.si_uid = getuid();
694
695 if (dump_type != kDebuggerdNativeBacktrace && dump_type != kDebuggerdTombstone) {
696 PLOG(FATAL) << "invalid dump type";
697 }
698
699 siginfo.si_value.sival_int = dump_type == kDebuggerdNativeBacktrace;
700
701 if (syscall(__NR_rt_tgsigqueueinfo, getpid(), gettid(), DEBUGGER_SIGNAL, &siginfo) != 0) {
702 PLOG(ERROR) << "libdebuggerd_client: failed to send signal to self";
703 return false;
704 }
705
706 return true;
707}
708
709TEST_F(CrasherTest, seccomp_tombstone) {
710 int intercept_result;
711 unique_fd output_fd;
712
713 static const auto dump_type = kDebuggerdTombstone;
714 StartProcess(
715 []() {
716 raise_debugger_signal(dump_type);
717 _exit(0);
718 },
719 &seccomp_fork);
720
721 StartIntercept(&output_fd, dump_type);
722 FinishCrasher();
723 AssertDeath(0);
724 FinishIntercept(&intercept_result);
725 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
726
727 std::string result;
728 ConsumeFd(std::move(output_fd), &result);
729 ASSERT_BACKTRACE_FRAME(result, "raise_debugger_signal");
730}
731
732TEST_F(CrasherTest, seccomp_backtrace) {
733 int intercept_result;
734 unique_fd output_fd;
735
736 static const auto dump_type = kDebuggerdNativeBacktrace;
737 StartProcess(
738 []() {
739 raise_debugger_signal(dump_type);
740 _exit(0);
741 },
742 &seccomp_fork);
743
744 StartIntercept(&output_fd, dump_type);
745 FinishCrasher();
746 AssertDeath(0);
747 FinishIntercept(&intercept_result);
748 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
749
750 std::string result;
751 ConsumeFd(std::move(output_fd), &result);
752 ASSERT_BACKTRACE_FRAME(result, "raise_debugger_signal");
753}
754
755TEST_F(CrasherTest, seccomp_crash_logcat) {
756 StartProcess([]() { abort(); }, &seccomp_fork);
757 FinishCrasher();
758
759 // Make sure we don't get SIGSYS when trying to dump a crash to logcat.
760 AssertDeath(SIGABRT);
761}
762
Josh Gaofd13bf02017-08-18 15:37:26 -0700763TEST_F(CrasherTest, competing_tracer) {
764 int intercept_result;
765 unique_fd output_fd;
766 StartProcess([]() {
Josh Gao2b2ae0c2017-08-21 14:31:17 -0700767 raise(SIGABRT);
Josh Gaofd13bf02017-08-18 15:37:26 -0700768 });
769
770 StartIntercept(&output_fd);
Josh Gaofd13bf02017-08-18 15:37:26 -0700771
772 ASSERT_EQ(0, ptrace(PTRACE_SEIZE, crasher_pid, 0, 0));
Josh Gao2b2ae0c2017-08-21 14:31:17 -0700773 FinishCrasher();
Josh Gaofd13bf02017-08-18 15:37:26 -0700774
775 int status;
776 ASSERT_EQ(crasher_pid, waitpid(crasher_pid, &status, 0));
777 ASSERT_TRUE(WIFSTOPPED(status));
778 ASSERT_EQ(SIGABRT, WSTOPSIG(status));
779
780 ASSERT_EQ(0, ptrace(PTRACE_CONT, crasher_pid, 0, SIGABRT));
781 FinishIntercept(&intercept_result);
782 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
783
784 std::string result;
785 ConsumeFd(std::move(output_fd), &result);
786 std::string regex = R"(failed to attach to thread \d+, already traced by )";
787 regex += std::to_string(gettid());
788 regex += R"( \(.+debuggerd_test)";
789 ASSERT_MATCH(result, regex.c_str());
790
Josh Gao2b2ae0c2017-08-21 14:31:17 -0700791 ASSERT_EQ(crasher_pid, waitpid(crasher_pid, &status, 0));
792 ASSERT_TRUE(WIFSTOPPED(status));
793 ASSERT_EQ(SIGABRT, WSTOPSIG(status));
794
Josh Gaofd13bf02017-08-18 15:37:26 -0700795 ASSERT_EQ(0, ptrace(PTRACE_DETACH, crasher_pid, 0, SIGABRT));
796 AssertDeath(SIGABRT);
797}
798
Josh Gaoc3c8c022017-02-13 16:36:18 -0800799TEST(crash_dump, zombie) {
800 pid_t forkpid = fork();
801
Josh Gaoc3c8c022017-02-13 16:36:18 -0800802 pid_t rc;
803 int status;
804
805 if (forkpid == 0) {
806 errno = 0;
807 rc = waitpid(-1, &status, WNOHANG | __WALL | __WNOTHREAD);
808 if (rc != -1 || errno != ECHILD) {
809 errx(2, "first waitpid returned %d (%s), expected failure with ECHILD", rc, strerror(errno));
810 }
811
812 raise(DEBUGGER_SIGNAL);
813
814 errno = 0;
815 rc = waitpid(-1, &status, __WALL | __WNOTHREAD);
816 if (rc != -1 || errno != ECHILD) {
817 errx(2, "second waitpid returned %d (%s), expected failure with ECHILD", rc, strerror(errno));
818 }
819 _exit(0);
820 } else {
821 rc = waitpid(forkpid, &status, 0);
822 ASSERT_EQ(forkpid, rc);
823 ASSERT_TRUE(WIFEXITED(status));
824 ASSERT_EQ(0, WEXITSTATUS(status));
825 }
826}
Josh Gao352a8452017-03-30 16:46:21 -0700827
828TEST(tombstoned, no_notify) {
829 // Do this a few times.
830 for (int i = 0; i < 3; ++i) {
831 pid_t pid = 123'456'789 + i;
832
833 unique_fd intercept_fd, output_fd;
Narayan Kamathca5e9082017-06-02 15:42:06 +0100834 InterceptStatus status;
835 tombstoned_intercept(pid, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
836 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gao352a8452017-03-30 16:46:21 -0700837
838 {
839 unique_fd tombstoned_socket, input_fd;
Narayan Kamatha73df602017-05-24 15:07:25 +0100840 ASSERT_TRUE(tombstoned_connect(pid, &tombstoned_socket, &input_fd, kDebuggerdTombstone));
Josh Gao352a8452017-03-30 16:46:21 -0700841 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), &pid, sizeof(pid)));
842 }
843
844 pid_t read_pid;
845 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), &read_pid, sizeof(read_pid)));
846 ASSERT_EQ(read_pid, pid);
847 }
848}
849
850TEST(tombstoned, stress) {
851 // Spawn threads to simultaneously do a bunch of failing dumps and a bunch of successful dumps.
852 static constexpr int kDumpCount = 100;
853
854 std::atomic<bool> start(false);
855 std::vector<std::thread> threads;
856 threads.emplace_back([&start]() {
857 while (!start) {
858 continue;
859 }
860
861 // Use a way out of range pid, to avoid stomping on an actual process.
862 pid_t pid_base = 1'000'000;
863
864 for (int dump = 0; dump < kDumpCount; ++dump) {
865 pid_t pid = pid_base + dump;
866
867 unique_fd intercept_fd, output_fd;
Narayan Kamathca5e9082017-06-02 15:42:06 +0100868 InterceptStatus status;
869 tombstoned_intercept(pid, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
870 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gao352a8452017-03-30 16:46:21 -0700871
872 // Pretend to crash, and then immediately close the socket.
873 unique_fd sockfd(socket_local_client(kTombstonedCrashSocketName,
874 ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_SEQPACKET));
875 if (sockfd == -1) {
876 FAIL() << "failed to connect to tombstoned: " << strerror(errno);
877 }
878 TombstonedCrashPacket packet = {};
879 packet.packet_type = CrashPacketType::kDumpRequest;
880 packet.packet.dump_request.pid = pid;
881 if (TEMP_FAILURE_RETRY(write(sockfd, &packet, sizeof(packet))) != sizeof(packet)) {
882 FAIL() << "failed to write to tombstoned: " << strerror(errno);
883 }
884
885 continue;
886 }
887 });
888
889 threads.emplace_back([&start]() {
890 while (!start) {
891 continue;
892 }
893
894 // Use a way out of range pid, to avoid stomping on an actual process.
895 pid_t pid_base = 2'000'000;
896
897 for (int dump = 0; dump < kDumpCount; ++dump) {
898 pid_t pid = pid_base + dump;
899
900 unique_fd intercept_fd, output_fd;
Narayan Kamathca5e9082017-06-02 15:42:06 +0100901 InterceptStatus status;
902 tombstoned_intercept(pid, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
903 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gao352a8452017-03-30 16:46:21 -0700904
905 {
906 unique_fd tombstoned_socket, input_fd;
Narayan Kamatha73df602017-05-24 15:07:25 +0100907 ASSERT_TRUE(tombstoned_connect(pid, &tombstoned_socket, &input_fd, kDebuggerdTombstone));
Josh Gao352a8452017-03-30 16:46:21 -0700908 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), &pid, sizeof(pid)));
909 tombstoned_notify_completion(tombstoned_socket.get());
910 }
911
912 // TODO: Fix the race that requires this sleep.
913 std::this_thread::sleep_for(50ms);
914
915 pid_t read_pid;
916 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), &read_pid, sizeof(read_pid)));
917 ASSERT_EQ(read_pid, pid);
918 }
919 });
920
921 start = true;
922
923 for (std::thread& thread : threads) {
924 thread.join();
925 }
926}
Narayan Kamathca5e9082017-06-02 15:42:06 +0100927
928TEST(tombstoned, java_trace_intercept_smoke) {
929 // Using a "real" PID is a little dangerous here - if the test fails
930 // or crashes, we might end up getting a bogus / unreliable stack
931 // trace.
932 const pid_t self = getpid();
933
934 unique_fd intercept_fd, output_fd;
935 InterceptStatus status;
936 tombstoned_intercept(self, &intercept_fd, &output_fd, &status, kDebuggerdJavaBacktrace);
937 ASSERT_EQ(InterceptStatus::kRegistered, status);
938
939 // First connect to tombstoned requesting a native backtrace. This
940 // should result in a "regular" FD and not the installed intercept.
941 const char native[] = "native";
942 unique_fd tombstoned_socket, input_fd;
943 ASSERT_TRUE(tombstoned_connect(self, &tombstoned_socket, &input_fd, kDebuggerdNativeBacktrace));
944 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), native, sizeof(native)));
945 tombstoned_notify_completion(tombstoned_socket.get());
946
947 // Then, connect to tombstoned asking for a java backtrace. This *should*
948 // trigger the intercept.
949 const char java[] = "java";
950 ASSERT_TRUE(tombstoned_connect(self, &tombstoned_socket, &input_fd, kDebuggerdJavaBacktrace));
951 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), java, sizeof(java)));
952 tombstoned_notify_completion(tombstoned_socket.get());
953
954 char outbuf[sizeof(java)];
955 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), outbuf, sizeof(outbuf)));
956 ASSERT_STREQ("java", outbuf);
957}
958
959TEST(tombstoned, multiple_intercepts) {
960 const pid_t fake_pid = 1'234'567;
961 unique_fd intercept_fd, output_fd;
962 InterceptStatus status;
963 tombstoned_intercept(fake_pid, &intercept_fd, &output_fd, &status, kDebuggerdJavaBacktrace);
964 ASSERT_EQ(InterceptStatus::kRegistered, status);
965
966 unique_fd intercept_fd_2, output_fd_2;
967 tombstoned_intercept(fake_pid, &intercept_fd_2, &output_fd_2, &status, kDebuggerdNativeBacktrace);
968 ASSERT_EQ(InterceptStatus::kFailedAlreadyRegistered, status);
969}
970
971TEST(tombstoned, intercept_any) {
972 const pid_t fake_pid = 1'234'567;
973
974 unique_fd intercept_fd, output_fd;
975 InterceptStatus status;
976 tombstoned_intercept(fake_pid, &intercept_fd, &output_fd, &status, kDebuggerdNativeBacktrace);
977 ASSERT_EQ(InterceptStatus::kRegistered, status);
978
979 const char any[] = "any";
980 unique_fd tombstoned_socket, input_fd;
981 ASSERT_TRUE(tombstoned_connect(fake_pid, &tombstoned_socket, &input_fd, kDebuggerdAnyIntercept));
982 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), any, sizeof(any)));
983 tombstoned_notify_completion(tombstoned_socket.get());
984
985 char outbuf[sizeof(any)];
986 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), outbuf, sizeof(outbuf)));
987 ASSERT_STREQ("any", outbuf);
988}