blob: f8b4bad6e9161be2dec7a035779c23974657cdfa [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>
Josh Gao30171a82017-04-27 19:48:44 -070039#include <android-base/test_utils.h>
Josh Gaocbe70cb2016-10-18 18:17:52 -070040#include <android-base/unique_fd.h>
41#include <cutils/sockets.h>
Josh Gaocbe70cb2016-10-18 18:17:52 -070042#include <gtest/gtest.h>
43
Josh Gaoe04ca272018-01-16 15:38:17 -080044#include <libminijail.h>
45#include <scoped_minijail.h>
46
Narayan Kamath2d377cd2017-05-10 10:58:59 +010047#include "debuggerd/handler.h"
48#include "protocol.h"
49#include "tombstoned/tombstoned.h"
50#include "util.h"
51
Josh Gaocbe70cb2016-10-18 18:17:52 -070052using namespace std::chrono_literals;
53using android::base::unique_fd;
54
55#if defined(__LP64__)
Josh Gaocbe70cb2016-10-18 18:17:52 -070056#define ARCH_SUFFIX "64"
57#else
Josh Gaocbe70cb2016-10-18 18:17:52 -070058#define ARCH_SUFFIX ""
59#endif
60
61constexpr char kWaitForGdbKey[] = "debug.debuggerd.wait_for_gdb";
62
63#define TIMEOUT(seconds, expr) \
64 [&]() { \
65 struct sigaction old_sigaction; \
66 struct sigaction new_sigaction = {}; \
67 new_sigaction.sa_handler = [](int) {}; \
68 if (sigaction(SIGALRM, &new_sigaction, &new_sigaction) != 0) { \
69 err(1, "sigaction failed"); \
70 } \
71 alarm(seconds); \
72 auto value = expr; \
73 int saved_errno = errno; \
74 if (sigaction(SIGALRM, &old_sigaction, nullptr) != 0) { \
75 err(1, "sigaction failed"); \
76 } \
77 alarm(0); \
78 errno = saved_errno; \
79 return value; \
80 }()
81
Josh Gaoe04ca272018-01-16 15:38:17 -080082#define ASSERT_BACKTRACE_FRAME(result, frame_name) \
83 ASSERT_MATCH(result, R"(#\d\d pc [0-9a-f]+\s+ \S+ \()" frame_name R"(\+)");
Jaesung Chung58778e12017-06-15 18:20:34 +090084
Narayan Kamatha73df602017-05-24 15:07:25 +010085static void tombstoned_intercept(pid_t target_pid, unique_fd* intercept_fd, unique_fd* output_fd,
Narayan Kamathca5e9082017-06-02 15:42:06 +010086 InterceptStatus* status, DebuggerdDumpType intercept_type) {
Josh Gao460b3362017-03-30 16:40:47 -070087 intercept_fd->reset(socket_local_client(kTombstonedInterceptSocketName,
88 ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_SEQPACKET));
89 if (intercept_fd->get() == -1) {
90 FAIL() << "failed to contact tombstoned: " << strerror(errno);
91 }
92
Narayan Kamatha73df602017-05-24 15:07:25 +010093 InterceptRequest req = {.pid = target_pid, .dump_type = intercept_type};
Josh Gao460b3362017-03-30 16:40:47 -070094
95 unique_fd output_pipe_write;
96 if (!Pipe(output_fd, &output_pipe_write)) {
97 FAIL() << "failed to create output pipe: " << strerror(errno);
98 }
99
100 std::string pipe_size_str;
101 int pipe_buffer_size;
102 if (!android::base::ReadFileToString("/proc/sys/fs/pipe-max-size", &pipe_size_str)) {
103 FAIL() << "failed to read /proc/sys/fs/pipe-max-size: " << strerror(errno);
104 }
105
106 pipe_size_str = android::base::Trim(pipe_size_str);
107
108 if (!android::base::ParseInt(pipe_size_str.c_str(), &pipe_buffer_size, 0)) {
109 FAIL() << "failed to parse pipe max size";
110 }
111
112 if (fcntl(output_fd->get(), F_SETPIPE_SZ, pipe_buffer_size) != pipe_buffer_size) {
113 FAIL() << "failed to set pipe size: " << strerror(errno);
114 }
115
Josh Gao5675f3c2017-06-01 12:19:53 -0700116 ASSERT_GE(pipe_buffer_size, 1024 * 1024);
117
Josh Gao460b3362017-03-30 16:40:47 -0700118 if (send_fd(intercept_fd->get(), &req, sizeof(req), std::move(output_pipe_write)) != sizeof(req)) {
119 FAIL() << "failed to send output fd to tombstoned: " << strerror(errno);
120 }
121
122 InterceptResponse response;
123 ssize_t rc = TEMP_FAILURE_RETRY(read(intercept_fd->get(), &response, sizeof(response)));
124 if (rc == -1) {
125 FAIL() << "failed to read response from tombstoned: " << strerror(errno);
126 } else if (rc == 0) {
127 FAIL() << "failed to read response from tombstoned (EOF)";
128 } else if (rc != sizeof(response)) {
129 FAIL() << "received packet of unexpected length from tombstoned: expected " << sizeof(response)
130 << ", received " << rc;
131 }
132
Narayan Kamathca5e9082017-06-02 15:42:06 +0100133 *status = response.status;
Josh Gao460b3362017-03-30 16:40:47 -0700134}
135
Josh Gaocbe70cb2016-10-18 18:17:52 -0700136class CrasherTest : public ::testing::Test {
137 public:
138 pid_t crasher_pid = -1;
139 bool previous_wait_for_gdb;
140 unique_fd crasher_pipe;
141 unique_fd intercept_fd;
142
143 CrasherTest();
144 ~CrasherTest();
145
Narayan Kamatha73df602017-05-24 15:07:25 +0100146 void StartIntercept(unique_fd* output_fd, DebuggerdDumpType intercept_type = kDebuggerdTombstone);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700147
148 // Returns -1 if we fail to read a response from tombstoned, otherwise the received return code.
149 void FinishIntercept(int* result);
150
Josh Gao2e7b8e22017-05-04 17:12:57 -0700151 void StartProcess(std::function<void()> function, std::function<pid_t()> forker = fork);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700152 void StartCrasher(const std::string& crash_type);
153 void FinishCrasher();
154 void AssertDeath(int signo);
155};
156
157CrasherTest::CrasherTest() {
158 previous_wait_for_gdb = android::base::GetBoolProperty(kWaitForGdbKey, false);
159 android::base::SetProperty(kWaitForGdbKey, "0");
160}
161
162CrasherTest::~CrasherTest() {
163 if (crasher_pid != -1) {
164 kill(crasher_pid, SIGKILL);
165 int status;
166 waitpid(crasher_pid, &status, WUNTRACED);
167 }
168
169 android::base::SetProperty(kWaitForGdbKey, previous_wait_for_gdb ? "1" : "0");
170}
171
Narayan Kamatha73df602017-05-24 15:07:25 +0100172void CrasherTest::StartIntercept(unique_fd* output_fd, DebuggerdDumpType intercept_type) {
Josh Gaocbe70cb2016-10-18 18:17:52 -0700173 if (crasher_pid == -1) {
174 FAIL() << "crasher hasn't been started";
175 }
176
Narayan Kamathca5e9082017-06-02 15:42:06 +0100177 InterceptStatus status;
178 tombstoned_intercept(crasher_pid, &this->intercept_fd, output_fd, &status, intercept_type);
179 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700180}
181
182void CrasherTest::FinishIntercept(int* result) {
183 InterceptResponse response;
184
185 // Timeout for tombstoned intercept is 10 seconds.
186 ssize_t rc = TIMEOUT(20, read(intercept_fd.get(), &response, sizeof(response)));
187 if (rc == -1) {
188 FAIL() << "failed to read response from tombstoned: " << strerror(errno);
189 } else if (rc == 0) {
190 *result = -1;
191 } else if (rc != sizeof(response)) {
192 FAIL() << "received packet of unexpected length from tombstoned: expected " << sizeof(response)
193 << ", received " << rc;
194 } else {
Josh Gao460b3362017-03-30 16:40:47 -0700195 *result = response.status == InterceptStatus::kStarted ? 1 : 0;
Josh Gaocbe70cb2016-10-18 18:17:52 -0700196 }
197}
198
Josh Gao2e7b8e22017-05-04 17:12:57 -0700199void CrasherTest::StartProcess(std::function<void()> function, std::function<pid_t()> forker) {
Josh Gaofca7ca32017-01-23 12:05:35 -0800200 unique_fd read_pipe;
Josh Gaocbe70cb2016-10-18 18:17:52 -0700201 unique_fd crasher_read_pipe;
202 if (!Pipe(&crasher_read_pipe, &crasher_pipe)) {
203 FAIL() << "failed to create pipe: " << strerror(errno);
204 }
205
Josh Gao2e7b8e22017-05-04 17:12:57 -0700206 crasher_pid = forker();
Josh Gaocbe70cb2016-10-18 18:17:52 -0700207 if (crasher_pid == -1) {
208 FAIL() << "fork failed: " << strerror(errno);
209 } else if (crasher_pid == 0) {
Josh Gao502cfd22017-02-17 01:39:15 -0800210 char dummy;
211 crasher_pipe.reset();
212 TEMP_FAILURE_RETRY(read(crasher_read_pipe.get(), &dummy, 1));
Josh Gaofca7ca32017-01-23 12:05:35 -0800213 function();
214 _exit(0);
215 }
216}
217
Josh Gaocbe70cb2016-10-18 18:17:52 -0700218void CrasherTest::FinishCrasher() {
219 if (crasher_pipe == -1) {
220 FAIL() << "crasher pipe uninitialized";
221 }
222
223 ssize_t rc = write(crasher_pipe.get(), "\n", 1);
224 if (rc == -1) {
225 FAIL() << "failed to write to crasher pipe: " << strerror(errno);
226 } else if (rc == 0) {
227 FAIL() << "crasher pipe was closed";
228 }
229}
230
231void CrasherTest::AssertDeath(int signo) {
232 int status;
233 pid_t pid = TIMEOUT(5, waitpid(crasher_pid, &status, 0));
234 if (pid != crasher_pid) {
Josh Gao2b2ae0c2017-08-21 14:31:17 -0700235 printf("failed to wait for crasher (pid %d)\n", crasher_pid);
236 sleep(100);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700237 FAIL() << "failed to wait for crasher: " << strerror(errno);
238 }
239
Josh Gaoe06f2a42017-04-27 16:50:38 -0700240 if (signo == 0) {
241 ASSERT_TRUE(WIFEXITED(status));
242 ASSERT_EQ(0, WEXITSTATUS(signo));
243 } else {
244 ASSERT_FALSE(WIFEXITED(status));
245 ASSERT_TRUE(WIFSIGNALED(status)) << "crasher didn't terminate via a signal";
246 ASSERT_EQ(signo, WTERMSIG(status));
Josh Gaocbe70cb2016-10-18 18:17:52 -0700247 }
Josh Gaocbe70cb2016-10-18 18:17:52 -0700248 crasher_pid = -1;
249}
250
251static void ConsumeFd(unique_fd fd, std::string* output) {
252 constexpr size_t read_length = PAGE_SIZE;
253 std::string result;
254
255 while (true) {
256 size_t offset = result.size();
257 result.resize(result.size() + PAGE_SIZE);
258 ssize_t rc = TEMP_FAILURE_RETRY(read(fd.get(), &result[offset], read_length));
259 if (rc == -1) {
260 FAIL() << "read failed: " << strerror(errno);
261 } else if (rc == 0) {
262 result.resize(result.size() - PAGE_SIZE);
263 break;
264 }
265
266 result.resize(result.size() - PAGE_SIZE + rc);
267 }
268
269 *output = std::move(result);
270}
271
272TEST_F(CrasherTest, smoke) {
273 int intercept_result;
274 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800275 StartProcess([]() {
276 *reinterpret_cast<volatile char*>(0xdead) = '1';
277 });
278
Josh Gaocbe70cb2016-10-18 18:17:52 -0700279 StartIntercept(&output_fd);
280 FinishCrasher();
281 AssertDeath(SIGSEGV);
282 FinishIntercept(&intercept_result);
283
284 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
285
286 std::string result;
287 ConsumeFd(std::move(output_fd), &result);
288 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\), code 1 \(SEGV_MAPERR\), fault addr 0xdead)");
289}
290
Josh Gaocdea7502017-11-01 15:00:40 -0700291TEST_F(CrasherTest, LD_PRELOAD) {
292 int intercept_result;
293 unique_fd output_fd;
294 StartProcess([]() {
295 setenv("LD_PRELOAD", "nonexistent.so", 1);
296 *reinterpret_cast<volatile char*>(0xdead) = '1';
297 });
298
299 StartIntercept(&output_fd);
300 FinishCrasher();
301 AssertDeath(SIGSEGV);
302 FinishIntercept(&intercept_result);
303
304 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
305
306 std::string result;
307 ConsumeFd(std::move(output_fd), &result);
308 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\), code 1 \(SEGV_MAPERR\), fault addr 0xdead)");
309}
310
Josh Gaocbe70cb2016-10-18 18:17:52 -0700311TEST_F(CrasherTest, abort) {
312 int intercept_result;
313 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800314 StartProcess([]() {
315 abort();
316 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700317 StartIntercept(&output_fd);
318 FinishCrasher();
319 AssertDeath(SIGABRT);
320 FinishIntercept(&intercept_result);
321
322 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
323
324 std::string result;
325 ConsumeFd(std::move(output_fd), &result);
Andreas Gampe26cbafb2017-06-22 20:14:43 -0700326 ASSERT_BACKTRACE_FRAME(result, "abort");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700327}
328
329TEST_F(CrasherTest, signal) {
330 int intercept_result;
331 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800332 StartProcess([]() {
Josh Gao2b2ae0c2017-08-21 14:31:17 -0700333 while (true) {
334 sleep(1);
335 }
Josh Gao502cfd22017-02-17 01:39:15 -0800336 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700337 StartIntercept(&output_fd);
Josh Gao2b2ae0c2017-08-21 14:31:17 -0700338 FinishCrasher();
Josh Gaocbe70cb2016-10-18 18:17:52 -0700339 ASSERT_EQ(0, kill(crasher_pid, SIGSEGV));
340
341 AssertDeath(SIGSEGV);
342 FinishIntercept(&intercept_result);
343
344 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
345
346 std::string result;
347 ConsumeFd(std::move(output_fd), &result);
348 ASSERT_MATCH(result, R"(signal 11 \(SIGSEGV\), code 0 \(SI_USER\), fault addr --------)");
349 ASSERT_MATCH(result, R"(backtrace:)");
350}
351
352TEST_F(CrasherTest, abort_message) {
353 int intercept_result;
354 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800355 StartProcess([]() {
356 android_set_abort_message("abort message goes here");
357 abort();
358 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700359 StartIntercept(&output_fd);
360 FinishCrasher();
361 AssertDeath(SIGABRT);
362 FinishIntercept(&intercept_result);
363
364 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
365
366 std::string result;
367 ConsumeFd(std::move(output_fd), &result);
Josh Gao502cfd22017-02-17 01:39:15 -0800368 ASSERT_MATCH(result, R"(Abort message: 'abort message goes here')");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700369}
370
Josh Gaoe06f2a42017-04-27 16:50:38 -0700371TEST_F(CrasherTest, abort_message_backtrace) {
372 int intercept_result;
373 unique_fd output_fd;
374 StartProcess([]() {
375 android_set_abort_message("not actually aborting");
376 raise(DEBUGGER_SIGNAL);
377 exit(0);
378 });
379 StartIntercept(&output_fd);
380 FinishCrasher();
381 AssertDeath(0);
382 FinishIntercept(&intercept_result);
383
384 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
385
386 std::string result;
387 ConsumeFd(std::move(output_fd), &result);
388 ASSERT_NOT_MATCH(result, R"(Abort message:)");
389}
390
Josh Gaocbe70cb2016-10-18 18:17:52 -0700391TEST_F(CrasherTest, intercept_timeout) {
392 int intercept_result;
393 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800394 StartProcess([]() {
395 abort();
396 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700397 StartIntercept(&output_fd);
398
399 // Don't let crasher finish until we timeout.
400 FinishIntercept(&intercept_result);
401
402 ASSERT_NE(1, intercept_result) << "tombstoned reported success? (intercept_result = "
403 << intercept_result << ")";
404
405 FinishCrasher();
406 AssertDeath(SIGABRT);
407}
408
409TEST_F(CrasherTest, wait_for_gdb) {
410 if (!android::base::SetProperty(kWaitForGdbKey, "1")) {
411 FAIL() << "failed to enable wait_for_gdb";
412 }
413 sleep(1);
414
Josh Gao502cfd22017-02-17 01:39:15 -0800415 StartProcess([]() {
416 abort();
417 });
Josh Gaocbe70cb2016-10-18 18:17:52 -0700418 FinishCrasher();
419
420 int status;
421 ASSERT_EQ(crasher_pid, waitpid(crasher_pid, &status, WUNTRACED));
422 ASSERT_TRUE(WIFSTOPPED(status));
423 ASSERT_EQ(SIGSTOP, WSTOPSIG(status));
424
425 ASSERT_EQ(0, kill(crasher_pid, SIGCONT));
426
427 AssertDeath(SIGABRT);
428}
429
Josh Gaocbe70cb2016-10-18 18:17:52 -0700430TEST_F(CrasherTest, backtrace) {
431 std::string result;
432 int intercept_result;
433 unique_fd output_fd;
Josh Gao502cfd22017-02-17 01:39:15 -0800434
435 StartProcess([]() {
436 abort();
437 });
Narayan Kamatha73df602017-05-24 15:07:25 +0100438 StartIntercept(&output_fd, kDebuggerdNativeBacktrace);
Josh Gaocbe70cb2016-10-18 18:17:52 -0700439
440 std::this_thread::sleep_for(500ms);
441
442 sigval val;
443 val.sival_int = 1;
444 ASSERT_EQ(0, sigqueue(crasher_pid, DEBUGGER_SIGNAL, val)) << strerror(errno);
445 FinishIntercept(&intercept_result);
446 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
447 ConsumeFd(std::move(output_fd), &result);
Jaesung Chung58778e12017-06-15 18:20:34 +0900448 ASSERT_BACKTRACE_FRAME(result, "read");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700449
450 int status;
451 ASSERT_EQ(0, waitpid(crasher_pid, &status, WNOHANG | WUNTRACED));
452
453 StartIntercept(&output_fd);
454 FinishCrasher();
455 AssertDeath(SIGABRT);
456 FinishIntercept(&intercept_result);
457 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
458 ConsumeFd(std::move(output_fd), &result);
Andreas Gampe26cbafb2017-06-22 20:14:43 -0700459 ASSERT_BACKTRACE_FRAME(result, "abort");
Josh Gaocbe70cb2016-10-18 18:17:52 -0700460}
Josh Gaofca7ca32017-01-23 12:05:35 -0800461
462TEST_F(CrasherTest, PR_SET_DUMPABLE_0_crash) {
Josh Gao502cfd22017-02-17 01:39:15 -0800463 int intercept_result;
464 unique_fd output_fd;
Josh Gaofca7ca32017-01-23 12:05:35 -0800465 StartProcess([]() {
466 prctl(PR_SET_DUMPABLE, 0);
Josh Gao502cfd22017-02-17 01:39:15 -0800467 abort();
Josh Gaofca7ca32017-01-23 12:05:35 -0800468 });
Josh Gao502cfd22017-02-17 01:39:15 -0800469
470 StartIntercept(&output_fd);
471 FinishCrasher();
472 AssertDeath(SIGABRT);
473 FinishIntercept(&intercept_result);
474
475 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
476
477 std::string result;
478 ConsumeFd(std::move(output_fd), &result);
Andreas Gampe26cbafb2017-06-22 20:14:43 -0700479 ASSERT_BACKTRACE_FRAME(result, "abort");
Josh Gaofca7ca32017-01-23 12:05:35 -0800480}
481
Josh Gao502cfd22017-02-17 01:39:15 -0800482TEST_F(CrasherTest, capabilities) {
483 ASSERT_EQ(0U, getuid()) << "capability test requires root";
484
Josh Gaofca7ca32017-01-23 12:05:35 -0800485 StartProcess([]() {
Josh Gao502cfd22017-02-17 01:39:15 -0800486 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) != 0) {
487 err(1, "failed to set PR_SET_KEEPCAPS");
488 }
489
490 if (setresuid(1, 1, 1) != 0) {
491 err(1, "setresuid failed");
492 }
493
494 __user_cap_header_struct capheader;
495 __user_cap_data_struct capdata[2];
496 memset(&capheader, 0, sizeof(capheader));
497 memset(&capdata, 0, sizeof(capdata));
498
499 capheader.version = _LINUX_CAPABILITY_VERSION_3;
500 capheader.pid = 0;
501
502 // Turn on every third capability.
503 static_assert(CAP_LAST_CAP > 33, "CAP_LAST_CAP <= 32");
504 for (int i = 0; i < CAP_LAST_CAP; i += 3) {
505 capdata[CAP_TO_INDEX(i)].permitted |= CAP_TO_MASK(i);
506 capdata[CAP_TO_INDEX(i)].effective |= CAP_TO_MASK(i);
507 }
508
509 // Make sure CAP_SYS_PTRACE is off.
510 capdata[CAP_TO_INDEX(CAP_SYS_PTRACE)].permitted &= ~(CAP_TO_MASK(CAP_SYS_PTRACE));
511 capdata[CAP_TO_INDEX(CAP_SYS_PTRACE)].effective &= ~(CAP_TO_MASK(CAP_SYS_PTRACE));
512
513 if (capset(&capheader, &capdata[0]) != 0) {
514 err(1, "capset failed");
515 }
516
517 if (prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_CLEAR_ALL, 0, 0, 0) != 0) {
518 err(1, "failed to drop ambient capabilities");
519 }
520
Josh Gaoa5199a92017-04-03 13:18:34 -0700521 pthread_setname_np(pthread_self(), "thread_name");
Josh Gao502cfd22017-02-17 01:39:15 -0800522 raise(SIGSYS);
Josh Gaofca7ca32017-01-23 12:05:35 -0800523 });
Josh Gao502cfd22017-02-17 01:39:15 -0800524
525 unique_fd output_fd;
526 StartIntercept(&output_fd);
527 FinishCrasher();
528 AssertDeath(SIGSYS);
529
530 std::string result;
531 int intercept_result;
532 FinishIntercept(&intercept_result);
533 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
534 ConsumeFd(std::move(output_fd), &result);
Josh Gaoa5199a92017-04-03 13:18:34 -0700535 ASSERT_MATCH(result, R"(name: thread_name\s+>>> .+debuggerd_test(32|64) <<<)");
Jaesung Chung58778e12017-06-15 18:20:34 +0900536 ASSERT_BACKTRACE_FRAME(result, "tgkill");
Josh Gaofca7ca32017-01-23 12:05:35 -0800537}
Josh Gaoc3c8c022017-02-13 16:36:18 -0800538
Josh Gao2e7b8e22017-05-04 17:12:57 -0700539TEST_F(CrasherTest, fake_pid) {
540 int intercept_result;
541 unique_fd output_fd;
542
543 // Prime the getpid/gettid caches.
544 UNUSED(getpid());
545 UNUSED(gettid());
546
547 std::function<pid_t()> clone_fn = []() {
548 return syscall(__NR_clone, SIGCHLD, nullptr, nullptr, nullptr, nullptr);
549 };
550 StartProcess(
551 []() {
552 ASSERT_NE(getpid(), syscall(__NR_getpid));
553 ASSERT_NE(gettid(), syscall(__NR_gettid));
554 raise(SIGSEGV);
555 },
556 clone_fn);
557
558 StartIntercept(&output_fd);
559 FinishCrasher();
560 AssertDeath(SIGSEGV);
561 FinishIntercept(&intercept_result);
562
563 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
564
565 std::string result;
566 ConsumeFd(std::move(output_fd), &result);
Jaesung Chung58778e12017-06-15 18:20:34 +0900567 ASSERT_BACKTRACE_FRAME(result, "tgkill");
Josh Gao2e7b8e22017-05-04 17:12:57 -0700568}
569
Josh Gaoe04ca272018-01-16 15:38:17 -0800570static const char* const kDebuggerdSeccompPolicy =
571 "/system/etc/seccomp_policy/crash_dump." ABI_STRING ".policy";
572
573pid_t seccomp_fork() {
574 unique_fd policy_fd(open(kDebuggerdSeccompPolicy, O_RDONLY | O_CLOEXEC));
575 if (policy_fd == -1) {
576 LOG(FATAL) << "failed to open policy " << kDebuggerdSeccompPolicy;
577 }
578
579 ScopedMinijail jail{minijail_new()};
580 if (!jail) {
581 LOG(FATAL) << "failed to create minijail";
582 }
583
584 minijail_no_new_privs(jail.get());
585 minijail_log_seccomp_filter_failures(jail.get());
586 minijail_use_seccomp_filter(jail.get());
587 minijail_parse_seccomp_filters_from_fd(jail.get(), policy_fd.release());
588
589 pid_t result = fork();
590 if (result == -1) {
591 return result;
592 } else if (result != 0) {
593 return result;
594 }
595
596 // Spawn and detach a thread that spins forever.
597 std::atomic<bool> thread_ready(false);
598 std::thread thread([&jail, &thread_ready]() {
599 minijail_enter(jail.get());
600 thread_ready = true;
601 for (;;)
602 ;
603 });
604 thread.detach();
605
606 while (!thread_ready) {
607 continue;
608 }
609
610 minijail_enter(jail.get());
611 return result;
612}
613
614TEST_F(CrasherTest, seccomp_crash) {
615 int intercept_result;
616 unique_fd output_fd;
617
618 StartProcess([]() { abort(); }, &seccomp_fork);
619
620 StartIntercept(&output_fd);
621 FinishCrasher();
622 AssertDeath(SIGABRT);
623 FinishIntercept(&intercept_result);
624 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
625
626 std::string result;
627 ConsumeFd(std::move(output_fd), &result);
628 ASSERT_BACKTRACE_FRAME(result, "abort");
629}
630
631__attribute__((noinline)) extern "C" bool raise_debugger_signal(DebuggerdDumpType dump_type) {
632 siginfo_t siginfo;
633 siginfo.si_code = SI_QUEUE;
634 siginfo.si_pid = getpid();
635 siginfo.si_uid = getuid();
636
637 if (dump_type != kDebuggerdNativeBacktrace && dump_type != kDebuggerdTombstone) {
638 PLOG(FATAL) << "invalid dump type";
639 }
640
641 siginfo.si_value.sival_int = dump_type == kDebuggerdNativeBacktrace;
642
643 if (syscall(__NR_rt_tgsigqueueinfo, getpid(), gettid(), DEBUGGER_SIGNAL, &siginfo) != 0) {
644 PLOG(ERROR) << "libdebuggerd_client: failed to send signal to self";
645 return false;
646 }
647
648 return true;
649}
650
651TEST_F(CrasherTest, seccomp_tombstone) {
652 int intercept_result;
653 unique_fd output_fd;
654
655 static const auto dump_type = kDebuggerdTombstone;
656 StartProcess(
657 []() {
658 raise_debugger_signal(dump_type);
659 _exit(0);
660 },
661 &seccomp_fork);
662
663 StartIntercept(&output_fd, dump_type);
664 FinishCrasher();
665 AssertDeath(0);
666 FinishIntercept(&intercept_result);
667 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
668
669 std::string result;
670 ConsumeFd(std::move(output_fd), &result);
671 ASSERT_BACKTRACE_FRAME(result, "raise_debugger_signal");
672}
673
674TEST_F(CrasherTest, seccomp_backtrace) {
675 int intercept_result;
676 unique_fd output_fd;
677
678 static const auto dump_type = kDebuggerdNativeBacktrace;
679 StartProcess(
680 []() {
681 raise_debugger_signal(dump_type);
682 _exit(0);
683 },
684 &seccomp_fork);
685
686 StartIntercept(&output_fd, dump_type);
687 FinishCrasher();
688 AssertDeath(0);
689 FinishIntercept(&intercept_result);
690 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
691
692 std::string result;
693 ConsumeFd(std::move(output_fd), &result);
694 ASSERT_BACKTRACE_FRAME(result, "raise_debugger_signal");
695}
696
697TEST_F(CrasherTest, seccomp_crash_logcat) {
698 StartProcess([]() { abort(); }, &seccomp_fork);
699 FinishCrasher();
700
701 // Make sure we don't get SIGSYS when trying to dump a crash to logcat.
702 AssertDeath(SIGABRT);
703}
704
Josh Gaofd13bf02017-08-18 15:37:26 -0700705TEST_F(CrasherTest, competing_tracer) {
706 int intercept_result;
707 unique_fd output_fd;
708 StartProcess([]() {
Josh Gao2b2ae0c2017-08-21 14:31:17 -0700709 raise(SIGABRT);
Josh Gaofd13bf02017-08-18 15:37:26 -0700710 });
711
712 StartIntercept(&output_fd);
Josh Gaofd13bf02017-08-18 15:37:26 -0700713
714 ASSERT_EQ(0, ptrace(PTRACE_SEIZE, crasher_pid, 0, 0));
Josh Gao2b2ae0c2017-08-21 14:31:17 -0700715 FinishCrasher();
Josh Gaofd13bf02017-08-18 15:37:26 -0700716
717 int status;
718 ASSERT_EQ(crasher_pid, waitpid(crasher_pid, &status, 0));
719 ASSERT_TRUE(WIFSTOPPED(status));
720 ASSERT_EQ(SIGABRT, WSTOPSIG(status));
721
722 ASSERT_EQ(0, ptrace(PTRACE_CONT, crasher_pid, 0, SIGABRT));
723 FinishIntercept(&intercept_result);
724 ASSERT_EQ(1, intercept_result) << "tombstoned reported failure";
725
726 std::string result;
727 ConsumeFd(std::move(output_fd), &result);
728 std::string regex = R"(failed to attach to thread \d+, already traced by )";
729 regex += std::to_string(gettid());
730 regex += R"( \(.+debuggerd_test)";
731 ASSERT_MATCH(result, regex.c_str());
732
Josh Gao2b2ae0c2017-08-21 14:31:17 -0700733 ASSERT_EQ(crasher_pid, waitpid(crasher_pid, &status, 0));
734 ASSERT_TRUE(WIFSTOPPED(status));
735 ASSERT_EQ(SIGABRT, WSTOPSIG(status));
736
Josh Gaofd13bf02017-08-18 15:37:26 -0700737 ASSERT_EQ(0, ptrace(PTRACE_DETACH, crasher_pid, 0, SIGABRT));
738 AssertDeath(SIGABRT);
739}
740
Josh Gaoc3c8c022017-02-13 16:36:18 -0800741TEST(crash_dump, zombie) {
742 pid_t forkpid = fork();
743
Josh Gaoc3c8c022017-02-13 16:36:18 -0800744 pid_t rc;
745 int status;
746
747 if (forkpid == 0) {
748 errno = 0;
749 rc = waitpid(-1, &status, WNOHANG | __WALL | __WNOTHREAD);
750 if (rc != -1 || errno != ECHILD) {
751 errx(2, "first waitpid returned %d (%s), expected failure with ECHILD", rc, strerror(errno));
752 }
753
754 raise(DEBUGGER_SIGNAL);
755
756 errno = 0;
757 rc = waitpid(-1, &status, __WALL | __WNOTHREAD);
758 if (rc != -1 || errno != ECHILD) {
759 errx(2, "second waitpid returned %d (%s), expected failure with ECHILD", rc, strerror(errno));
760 }
761 _exit(0);
762 } else {
763 rc = waitpid(forkpid, &status, 0);
764 ASSERT_EQ(forkpid, rc);
765 ASSERT_TRUE(WIFEXITED(status));
766 ASSERT_EQ(0, WEXITSTATUS(status));
767 }
768}
Josh Gao352a8452017-03-30 16:46:21 -0700769
770TEST(tombstoned, no_notify) {
771 // Do this a few times.
772 for (int i = 0; i < 3; ++i) {
773 pid_t pid = 123'456'789 + i;
774
775 unique_fd intercept_fd, output_fd;
Narayan Kamathca5e9082017-06-02 15:42:06 +0100776 InterceptStatus status;
777 tombstoned_intercept(pid, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
778 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gao352a8452017-03-30 16:46:21 -0700779
780 {
781 unique_fd tombstoned_socket, input_fd;
Narayan Kamatha73df602017-05-24 15:07:25 +0100782 ASSERT_TRUE(tombstoned_connect(pid, &tombstoned_socket, &input_fd, kDebuggerdTombstone));
Josh Gao352a8452017-03-30 16:46:21 -0700783 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), &pid, sizeof(pid)));
784 }
785
786 pid_t read_pid;
787 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), &read_pid, sizeof(read_pid)));
788 ASSERT_EQ(read_pid, pid);
789 }
790}
791
792TEST(tombstoned, stress) {
793 // Spawn threads to simultaneously do a bunch of failing dumps and a bunch of successful dumps.
794 static constexpr int kDumpCount = 100;
795
796 std::atomic<bool> start(false);
797 std::vector<std::thread> threads;
798 threads.emplace_back([&start]() {
799 while (!start) {
800 continue;
801 }
802
803 // Use a way out of range pid, to avoid stomping on an actual process.
804 pid_t pid_base = 1'000'000;
805
806 for (int dump = 0; dump < kDumpCount; ++dump) {
807 pid_t pid = pid_base + dump;
808
809 unique_fd intercept_fd, output_fd;
Narayan Kamathca5e9082017-06-02 15:42:06 +0100810 InterceptStatus status;
811 tombstoned_intercept(pid, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
812 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gao352a8452017-03-30 16:46:21 -0700813
814 // Pretend to crash, and then immediately close the socket.
815 unique_fd sockfd(socket_local_client(kTombstonedCrashSocketName,
816 ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_SEQPACKET));
817 if (sockfd == -1) {
818 FAIL() << "failed to connect to tombstoned: " << strerror(errno);
819 }
820 TombstonedCrashPacket packet = {};
821 packet.packet_type = CrashPacketType::kDumpRequest;
822 packet.packet.dump_request.pid = pid;
823 if (TEMP_FAILURE_RETRY(write(sockfd, &packet, sizeof(packet))) != sizeof(packet)) {
824 FAIL() << "failed to write to tombstoned: " << strerror(errno);
825 }
826
827 continue;
828 }
829 });
830
831 threads.emplace_back([&start]() {
832 while (!start) {
833 continue;
834 }
835
836 // Use a way out of range pid, to avoid stomping on an actual process.
837 pid_t pid_base = 2'000'000;
838
839 for (int dump = 0; dump < kDumpCount; ++dump) {
840 pid_t pid = pid_base + dump;
841
842 unique_fd intercept_fd, output_fd;
Narayan Kamathca5e9082017-06-02 15:42:06 +0100843 InterceptStatus status;
844 tombstoned_intercept(pid, &intercept_fd, &output_fd, &status, kDebuggerdTombstone);
845 ASSERT_EQ(InterceptStatus::kRegistered, status);
Josh Gao352a8452017-03-30 16:46:21 -0700846
847 {
848 unique_fd tombstoned_socket, input_fd;
Narayan Kamatha73df602017-05-24 15:07:25 +0100849 ASSERT_TRUE(tombstoned_connect(pid, &tombstoned_socket, &input_fd, kDebuggerdTombstone));
Josh Gao352a8452017-03-30 16:46:21 -0700850 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), &pid, sizeof(pid)));
851 tombstoned_notify_completion(tombstoned_socket.get());
852 }
853
854 // TODO: Fix the race that requires this sleep.
855 std::this_thread::sleep_for(50ms);
856
857 pid_t read_pid;
858 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), &read_pid, sizeof(read_pid)));
859 ASSERT_EQ(read_pid, pid);
860 }
861 });
862
863 start = true;
864
865 for (std::thread& thread : threads) {
866 thread.join();
867 }
868}
Narayan Kamathca5e9082017-06-02 15:42:06 +0100869
870TEST(tombstoned, java_trace_intercept_smoke) {
871 // Using a "real" PID is a little dangerous here - if the test fails
872 // or crashes, we might end up getting a bogus / unreliable stack
873 // trace.
874 const pid_t self = getpid();
875
876 unique_fd intercept_fd, output_fd;
877 InterceptStatus status;
878 tombstoned_intercept(self, &intercept_fd, &output_fd, &status, kDebuggerdJavaBacktrace);
879 ASSERT_EQ(InterceptStatus::kRegistered, status);
880
881 // First connect to tombstoned requesting a native backtrace. This
882 // should result in a "regular" FD and not the installed intercept.
883 const char native[] = "native";
884 unique_fd tombstoned_socket, input_fd;
885 ASSERT_TRUE(tombstoned_connect(self, &tombstoned_socket, &input_fd, kDebuggerdNativeBacktrace));
886 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), native, sizeof(native)));
887 tombstoned_notify_completion(tombstoned_socket.get());
888
889 // Then, connect to tombstoned asking for a java backtrace. This *should*
890 // trigger the intercept.
891 const char java[] = "java";
892 ASSERT_TRUE(tombstoned_connect(self, &tombstoned_socket, &input_fd, kDebuggerdJavaBacktrace));
893 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), java, sizeof(java)));
894 tombstoned_notify_completion(tombstoned_socket.get());
895
896 char outbuf[sizeof(java)];
897 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), outbuf, sizeof(outbuf)));
898 ASSERT_STREQ("java", outbuf);
899}
900
901TEST(tombstoned, multiple_intercepts) {
902 const pid_t fake_pid = 1'234'567;
903 unique_fd intercept_fd, output_fd;
904 InterceptStatus status;
905 tombstoned_intercept(fake_pid, &intercept_fd, &output_fd, &status, kDebuggerdJavaBacktrace);
906 ASSERT_EQ(InterceptStatus::kRegistered, status);
907
908 unique_fd intercept_fd_2, output_fd_2;
909 tombstoned_intercept(fake_pid, &intercept_fd_2, &output_fd_2, &status, kDebuggerdNativeBacktrace);
910 ASSERT_EQ(InterceptStatus::kFailedAlreadyRegistered, status);
911}
912
913TEST(tombstoned, intercept_any) {
914 const pid_t fake_pid = 1'234'567;
915
916 unique_fd intercept_fd, output_fd;
917 InterceptStatus status;
918 tombstoned_intercept(fake_pid, &intercept_fd, &output_fd, &status, kDebuggerdNativeBacktrace);
919 ASSERT_EQ(InterceptStatus::kRegistered, status);
920
921 const char any[] = "any";
922 unique_fd tombstoned_socket, input_fd;
923 ASSERT_TRUE(tombstoned_connect(fake_pid, &tombstoned_socket, &input_fd, kDebuggerdAnyIntercept));
924 ASSERT_TRUE(android::base::WriteFully(input_fd.get(), any, sizeof(any)));
925 tombstoned_notify_completion(tombstoned_socket.get());
926
927 char outbuf[sizeof(any)];
928 ASSERT_TRUE(android::base::ReadFully(output_fd.get(), outbuf, sizeof(outbuf)));
929 ASSERT_STREQ("any", outbuf);
930}