blob: 8440adc38e052a27a77252348e5a7bdeaa6d48b5 [file] [log] [blame]
Pavel Labath1faca6c2016-04-21 15:13:22 +01001/*
2 * Copyright (C) 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 <sys/ptrace.h>
18
19#include <elf.h>
Josh Gao5e3fe952017-02-16 14:12:41 -080020#include <fcntl.h>
Pavel Labath1faca6c2016-04-21 15:13:22 +010021#include <sched.h>
22#include <sys/prctl.h>
Josh Gao5e3fe952017-02-16 14:12:41 -080023#include <sys/ptrace.h>
Pavel Labath1faca6c2016-04-21 15:13:22 +010024#include <sys/uio.h>
25#include <sys/user.h>
Josh Gao5e3fe952017-02-16 14:12:41 -080026#include <sys/wait.h>
Pavel Labath1faca6c2016-04-21 15:13:22 +010027#include <unistd.h>
28
29#include <gtest/gtest.h>
30
Pavel Labath3dad8d52017-02-22 18:22:46 +000031#include <android-base/macros.h>
Josh Gao5e3fe952017-02-16 14:12:41 -080032#include <android-base/unique_fd.h>
33
34using android::base::unique_fd;
35
Pavel Labath1faca6c2016-04-21 15:13:22 +010036// Host libc does not define this.
37#ifndef TRAP_HWBKPT
38#define TRAP_HWBKPT 4
39#endif
40
Pavel Labath1faca6c2016-04-21 15:13:22 +010041class ChildGuard {
42 public:
Chih-Hung Hsieh62e3a072016-05-03 12:08:05 -070043 explicit ChildGuard(pid_t pid) : pid(pid) {}
Pavel Labath1faca6c2016-04-21 15:13:22 +010044
45 ~ChildGuard() {
46 kill(pid, SIGKILL);
47 int status;
48 waitpid(pid, &status, 0);
49 }
50
51 private:
52 pid_t pid;
53};
54
Pavel Labathfb082ee2017-01-23 15:41:35 +000055enum class HwFeature { Watchpoint, Breakpoint };
56
57static bool is_hw_feature_supported(pid_t child, HwFeature feature) {
Pavel Labath1faca6c2016-04-21 15:13:22 +010058#if defined(__arm__)
59 long capabilities;
60 long result = ptrace(PTRACE_GETHBPREGS, child, 0, &capabilities);
61 if (result == -1) {
62 EXPECT_EQ(EIO, errno);
63 return false;
64 }
Pavel Labathfb082ee2017-01-23 15:41:35 +000065 switch (feature) {
66 case HwFeature::Watchpoint:
67 return ((capabilities >> 8) & 0xff) > 0;
68 case HwFeature::Breakpoint:
69 return (capabilities & 0xff) > 0;
70 }
Pavel Labath1faca6c2016-04-21 15:13:22 +010071#elif defined(__aarch64__)
72 user_hwdebug_state dreg_state;
73 iovec iov;
74 iov.iov_base = &dreg_state;
75 iov.iov_len = sizeof(dreg_state);
76
Pavel Labathfb082ee2017-01-23 15:41:35 +000077 long result = ptrace(PTRACE_GETREGSET, child,
78 feature == HwFeature::Watchpoint ? NT_ARM_HW_WATCH : NT_ARM_HW_BREAK, &iov);
Pavel Labath1faca6c2016-04-21 15:13:22 +010079 if (result == -1) {
80 EXPECT_EQ(EINVAL, errno);
81 return false;
82 }
83 return (dreg_state.dbg_info & 0xff) > 0;
84#elif defined(__i386__) || defined(__x86_64__)
Pavel Labathfb082ee2017-01-23 15:41:35 +000085 // We assume watchpoints and breakpoints are always supported on x86.
Pavel Labath3dad8d52017-02-22 18:22:46 +000086 UNUSED(child);
87 UNUSED(feature);
Pavel Labath1faca6c2016-04-21 15:13:22 +010088 return true;
89#else
90 // TODO: mips support.
Pavel Labath3dad8d52017-02-22 18:22:46 +000091 UNUSED(child);
92 UNUSED(feature);
Pavel Labath1faca6c2016-04-21 15:13:22 +010093 return false;
94#endif
95}
96
Pavel Labath3dad8d52017-02-22 18:22:46 +000097static void set_watchpoint(pid_t child, uintptr_t address, size_t size) {
98 ASSERT_EQ(0u, address & 0x7) << "address: " << address;
Pavel Labath1faca6c2016-04-21 15:13:22 +010099#if defined(__arm__) || defined(__aarch64__)
100 const unsigned byte_mask = (1 << size) - 1;
101 const unsigned type = 2; // Write.
102 const unsigned enable = 1;
103 const unsigned control = byte_mask << 5 | type << 3 | enable;
104
105#ifdef __arm__
106 ASSERT_EQ(0, ptrace(PTRACE_SETHBPREGS, child, -1, &address)) << strerror(errno);
107 ASSERT_EQ(0, ptrace(PTRACE_SETHBPREGS, child, -2, &control)) << strerror(errno);
108#else // aarch64
109 user_hwdebug_state dreg_state;
110 memset(&dreg_state, 0, sizeof dreg_state);
Pavel Labath3dad8d52017-02-22 18:22:46 +0000111 dreg_state.dbg_regs[0].addr = address;
Pavel Labath1faca6c2016-04-21 15:13:22 +0100112 dreg_state.dbg_regs[0].ctrl = control;
113
114 iovec iov;
115 iov.iov_base = &dreg_state;
116 iov.iov_len = offsetof(user_hwdebug_state, dbg_regs) + sizeof(dreg_state.dbg_regs[0]);
117
118 ASSERT_EQ(0, ptrace(PTRACE_SETREGSET, child, NT_ARM_HW_WATCH, &iov)) << strerror(errno);
119#endif
120#elif defined(__i386__) || defined(__x86_64__)
121 ASSERT_EQ(0, ptrace(PTRACE_POKEUSER, child, offsetof(user, u_debugreg[0]), address)) << strerror(errno);
122 errno = 0;
123 unsigned data = ptrace(PTRACE_PEEKUSER, child, offsetof(user, u_debugreg[7]), nullptr);
124 ASSERT_EQ(0, errno);
125
126 const unsigned size_flag = (size == 8) ? 2 : size - 1;
127 const unsigned enable = 1;
128 const unsigned type = 1; // Write.
129
130 const unsigned mask = 3 << 18 | 3 << 16 | 1;
131 const unsigned value = size_flag << 18 | type << 16 | enable;
132 data &= mask;
133 data |= value;
134 ASSERT_EQ(0, ptrace(PTRACE_POKEUSER, child, offsetof(user, u_debugreg[7]), data)) << strerror(errno);
135#else
Pavel Labath3dad8d52017-02-22 18:22:46 +0000136 UNUSED(child);
137 UNUSED(address);
138 UNUSED(size);
Pavel Labath1faca6c2016-04-21 15:13:22 +0100139#endif
140}
141
Pavel Labath3dad8d52017-02-22 18:22:46 +0000142template <typename T>
143static void run_watchpoint_test(std::function<void(T&)> child_func, size_t offset, size_t size) {
144 alignas(16) T data{};
Pavel Labath1faca6c2016-04-21 15:13:22 +0100145
146 pid_t child = fork();
147 ASSERT_NE(-1, child) << strerror(errno);
Pavel Labath3dad8d52017-02-22 18:22:46 +0000148 if (child == 0) {
149 // Extra precaution: make sure we go away if anything happens to our parent.
150 if (prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0) == -1) {
151 perror("prctl(PR_SET_PDEATHSIG)");
152 _exit(1);
153 }
154
155 if (ptrace(PTRACE_TRACEME, 0, nullptr, nullptr) == -1) {
156 perror("ptrace(PTRACE_TRACEME)");
157 _exit(2);
158 }
159
160 child_func(data);
161 _exit(0);
162 }
Pavel Labath1faca6c2016-04-21 15:13:22 +0100163
164 ChildGuard guard(child);
165
166 int status;
167 ASSERT_EQ(child, waitpid(child, &status, __WALL)) << strerror(errno);
168 ASSERT_TRUE(WIFSTOPPED(status)) << "Status was: " << status;
169 ASSERT_EQ(SIGSTOP, WSTOPSIG(status)) << "Status was: " << status;
170
Pavel Labathfb082ee2017-01-23 15:41:35 +0000171 if (!is_hw_feature_supported(child, HwFeature::Watchpoint)) {
172 GTEST_LOG_(INFO) << "Skipping test because hardware support is not available.\n";
173 return;
174 }
Pavel Labath1faca6c2016-04-21 15:13:22 +0100175
Pavel Labath3dad8d52017-02-22 18:22:46 +0000176 set_watchpoint(child, uintptr_t(&data) + offset, size);
Pavel Labath1faca6c2016-04-21 15:13:22 +0100177
178 ASSERT_EQ(0, ptrace(PTRACE_CONT, child, nullptr, nullptr)) << strerror(errno);
179 ASSERT_EQ(child, waitpid(child, &status, __WALL)) << strerror(errno);
180 ASSERT_TRUE(WIFSTOPPED(status)) << "Status was: " << status;
181 ASSERT_EQ(SIGTRAP, WSTOPSIG(status)) << "Status was: " << status;
182
183 siginfo_t siginfo;
184 ASSERT_EQ(0, ptrace(PTRACE_GETSIGINFO, child, nullptr, &siginfo)) << strerror(errno);
185 ASSERT_EQ(TRAP_HWBKPT, siginfo.si_code);
186#if defined(__arm__) || defined(__aarch64__)
Pavel Labath3dad8d52017-02-22 18:22:46 +0000187 ASSERT_LE(&data, siginfo.si_addr);
188 ASSERT_GT((&data) + 1, siginfo.si_addr);
Pavel Labath1faca6c2016-04-21 15:13:22 +0100189#endif
190}
191
Pavel Labath3dad8d52017-02-22 18:22:46 +0000192template <typename T>
193static void watchpoint_stress_child(unsigned cpu, T& data) {
194 cpu_set_t cpus;
195 CPU_ZERO(&cpus);
196 CPU_SET(cpu, &cpus);
197 if (sched_setaffinity(0, sizeof cpus, &cpus) == -1) {
198 perror("sched_setaffinity");
199 _exit(3);
200 }
201 raise(SIGSTOP); // Synchronize with the tracer, let it set the watchpoint.
202
203 data = 1; // Now trigger the watchpoint.
204}
205
206template <typename T>
207static void run_watchpoint_stress(size_t cpu) {
208 run_watchpoint_test<T>(std::bind(watchpoint_stress_child<T>, cpu, std::placeholders::_1), 0,
209 sizeof(T));
Pavel Labath1faca6c2016-04-21 15:13:22 +0100210}
211
212// Test watchpoint API. The test is considered successful if our watchpoints get hit OR the
213// system reports that watchpoint support is not present. We run the test for different
214// watchpoint sizes, while pinning the process to each cpu in turn, for better coverage.
Pavel Labathfb082ee2017-01-23 15:41:35 +0000215TEST(sys_ptrace, watchpoint_stress) {
Pavel Labath1faca6c2016-04-21 15:13:22 +0100216 cpu_set_t available_cpus;
217 ASSERT_EQ(0, sched_getaffinity(0, sizeof available_cpus, &available_cpus));
218
219 for (size_t cpu = 0; cpu < CPU_SETSIZE; ++cpu) {
220 if (!CPU_ISSET(cpu, &available_cpus)) continue;
Pavel Labath3dad8d52017-02-22 18:22:46 +0000221
222 run_watchpoint_stress<uint8_t>(cpu);
223 run_watchpoint_stress<uint16_t>(cpu);
224 run_watchpoint_stress<uint32_t>(cpu);
225#if defined(__LP64__)
226 run_watchpoint_stress<uint64_t>(cpu);
227#endif
Pavel Labath1faca6c2016-04-21 15:13:22 +0100228 }
229}
Pavel Labathfb082ee2017-01-23 15:41:35 +0000230
Pavel Labath3dad8d52017-02-22 18:22:46 +0000231struct Uint128_t {
232 uint64_t data[2];
233};
234static void watchpoint_imprecise_child(Uint128_t& data) {
235 raise(SIGSTOP); // Synchronize with the tracer, let it set the watchpoint.
236
237#if defined(__i386__) || defined(__x86_64__)
238 asm volatile("movdqa %%xmm0, %0" : : "m"(data));
239#elif defined(__arm__)
240 asm volatile("stm %0, { r0, r1, r2, r3 }" : : "r"(&data));
241#elif defined(__aarch64__)
242 asm volatile("stp x0, x1, %0" : : "m"(data));
243#elif defined(__mips__)
244// TODO
245#endif
246}
247
248// Test that the kernel is able to handle the case when the instruction writes
249// to a larger block of memory than the one we are watching. If you see this
250// test fail on arm64, you will likely need to cherry-pick fdfeff0f into your
251// kernel.
252TEST(sys_ptrace, watchpoint_imprecise) {
253 // Make sure we get interrupted in case a buggy kernel does not report the
254 // watchpoint hit correctly.
255 struct sigaction action, oldaction;
256 action.sa_handler = [](int) {};
257 sigemptyset(&action.sa_mask);
258 action.sa_flags = 0;
259 ASSERT_EQ(0, sigaction(SIGALRM, &action, &oldaction)) << strerror(errno);
260 alarm(5);
261
262 run_watchpoint_test<Uint128_t>(watchpoint_imprecise_child, 8, 8);
263
264 ASSERT_EQ(0, sigaction(SIGALRM, &oldaction, nullptr)) << strerror(errno);
265}
266
Pavel Labathfb082ee2017-01-23 15:41:35 +0000267static void __attribute__((noinline)) breakpoint_func() {
268 asm volatile("");
269}
270
271static void __attribute__((noreturn)) breakpoint_fork_child() {
272 // Extra precaution: make sure we go away if anything happens to our parent.
273 if (prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0) == -1) {
274 perror("prctl(PR_SET_PDEATHSIG)");
275 _exit(1);
276 }
277
278 if (ptrace(PTRACE_TRACEME, 0, nullptr, nullptr) == -1) {
279 perror("ptrace(PTRACE_TRACEME)");
280 _exit(2);
281 }
282
283 raise(SIGSTOP); // Synchronize with the tracer, let it set the breakpoint.
284
285 breakpoint_func(); // Now trigger the breakpoint.
286
287 _exit(0);
288}
289
290static void set_breakpoint(pid_t child) {
291 uintptr_t address = uintptr_t(breakpoint_func);
292#if defined(__arm__) || defined(__aarch64__)
293 address &= ~3;
294 const unsigned byte_mask = 0xf;
295 const unsigned enable = 1;
296 const unsigned control = byte_mask << 5 | enable;
297
298#ifdef __arm__
299 ASSERT_EQ(0, ptrace(PTRACE_SETHBPREGS, child, 1, &address)) << strerror(errno);
300 ASSERT_EQ(0, ptrace(PTRACE_SETHBPREGS, child, 2, &control)) << strerror(errno);
301#else // aarch64
302 user_hwdebug_state dreg_state;
303 memset(&dreg_state, 0, sizeof dreg_state);
304 dreg_state.dbg_regs[0].addr = reinterpret_cast<uintptr_t>(address);
305 dreg_state.dbg_regs[0].ctrl = control;
306
307 iovec iov;
308 iov.iov_base = &dreg_state;
309 iov.iov_len = offsetof(user_hwdebug_state, dbg_regs) + sizeof(dreg_state.dbg_regs[0]);
310
311 ASSERT_EQ(0, ptrace(PTRACE_SETREGSET, child, NT_ARM_HW_BREAK, &iov)) << strerror(errno);
312#endif
313#elif defined(__i386__) || defined(__x86_64__)
314 ASSERT_EQ(0, ptrace(PTRACE_POKEUSER, child, offsetof(user, u_debugreg[0]), address))
315 << strerror(errno);
316 errno = 0;
317 unsigned data = ptrace(PTRACE_PEEKUSER, child, offsetof(user, u_debugreg[7]), nullptr);
318 ASSERT_EQ(0, errno);
319
320 const unsigned size = 0;
321 const unsigned enable = 1;
322 const unsigned type = 0; // Execute
323
324 const unsigned mask = 3 << 18 | 3 << 16 | 1;
325 const unsigned value = size << 18 | type << 16 | enable;
326 data &= mask;
327 data |= value;
328 ASSERT_EQ(0, ptrace(PTRACE_POKEUSER, child, offsetof(user, u_debugreg[7]), data))
329 << strerror(errno);
330#else
Pavel Labath3dad8d52017-02-22 18:22:46 +0000331 UNUSED(child);
332 UNUSED(address);
Pavel Labathfb082ee2017-01-23 15:41:35 +0000333#endif
334}
335
336// Test hardware breakpoint API. The test is considered successful if the breakpoints get hit OR the
337// system reports that hardware breakpoint support is not present.
338TEST(sys_ptrace, hardware_breakpoint) {
339 pid_t child = fork();
340 ASSERT_NE(-1, child) << strerror(errno);
341 if (child == 0) breakpoint_fork_child();
342
343 ChildGuard guard(child);
344
345 int status;
346 ASSERT_EQ(child, waitpid(child, &status, __WALL)) << strerror(errno);
347 ASSERT_TRUE(WIFSTOPPED(status)) << "Status was: " << status;
348 ASSERT_EQ(SIGSTOP, WSTOPSIG(status)) << "Status was: " << status;
349
350 if (!is_hw_feature_supported(child, HwFeature::Breakpoint)) {
351 GTEST_LOG_(INFO) << "Skipping test because hardware support is not available.\n";
352 return;
353 }
354
355 set_breakpoint(child);
356
357 ASSERT_EQ(0, ptrace(PTRACE_CONT, child, nullptr, nullptr)) << strerror(errno);
358 ASSERT_EQ(child, waitpid(child, &status, __WALL)) << strerror(errno);
359 ASSERT_TRUE(WIFSTOPPED(status)) << "Status was: " << status;
360 ASSERT_EQ(SIGTRAP, WSTOPSIG(status)) << "Status was: " << status;
361
362 siginfo_t siginfo;
363 ASSERT_EQ(0, ptrace(PTRACE_GETSIGINFO, child, nullptr, &siginfo)) << strerror(errno);
364 ASSERT_EQ(TRAP_HWBKPT, siginfo.si_code);
365}
Josh Gao5e3fe952017-02-16 14:12:41 -0800366
367class PtraceResumptionTest : public ::testing::Test {
368 public:
369 pid_t worker = -1;
370 PtraceResumptionTest() {
371 }
372
373 ~PtraceResumptionTest() {
374 }
375
376 void AssertDeath(int signo);
377 void Start(std::function<void()> f) {
378 unique_fd worker_pipe_read, worker_pipe_write;
379 int pipefd[2];
380 ASSERT_EQ(0, pipe2(pipefd, O_CLOEXEC));
381 worker_pipe_read.reset(pipefd[0]);
382 worker_pipe_write.reset(pipefd[1]);
383
384 worker = fork();
385 ASSERT_NE(-1, worker);
386 if (worker == 0) {
387 char buf;
388 worker_pipe_write.reset();
389 TEMP_FAILURE_RETRY(read(worker_pipe_read.get(), &buf, sizeof(buf)));
390 exit(0);
391 }
392
393 pid_t tracer = fork();
394 ASSERT_NE(-1, tracer);
395 if (tracer == 0) {
396 f();
397 if (HasFatalFailure()) {
398 exit(1);
399 }
400 exit(0);
401 }
402
403 int result;
404 pid_t rc = waitpid(tracer, &result, 0);
405 ASSERT_EQ(tracer, rc);
406 EXPECT_TRUE(WIFEXITED(result) || WIFSIGNALED(result));
407 if (WIFEXITED(result)) {
408 if (WEXITSTATUS(result) != 0) {
409 FAIL() << "tracer failed";
410 }
411 }
412
413 rc = waitpid(worker, &result, WNOHANG);
414 ASSERT_EQ(0, rc);
415
416 worker_pipe_write.reset();
417
418 rc = waitpid(worker, &result, 0);
419 ASSERT_EQ(worker, rc);
420 EXPECT_TRUE(WIFEXITED(result));
421 EXPECT_EQ(WEXITSTATUS(result), 0);
422 }
423};
424
425static void wait_for_ptrace_stop(pid_t pid) {
426 while (true) {
427 int status;
428 pid_t rc = TEMP_FAILURE_RETRY(waitpid(pid, &status, __WALL));
429 if (rc != pid) {
430 abort();
431 }
432 if (WIFSTOPPED(status)) {
433 return;
434 }
435 }
436}
437
438TEST_F(PtraceResumptionTest, seize) {
439 Start([this]() { ASSERT_EQ(0, ptrace(PTRACE_SEIZE, worker, 0, 0)) << strerror(errno); });
440}
441
442TEST_F(PtraceResumptionTest, seize_interrupt) {
443 Start([this]() {
444 ASSERT_EQ(0, ptrace(PTRACE_SEIZE, worker, 0, 0)) << strerror(errno);
445 ASSERT_EQ(0, ptrace(PTRACE_INTERRUPT, worker, 0, 0)) << strerror(errno);
446 });
447}
448
449TEST_F(PtraceResumptionTest, seize_interrupt_cont) {
450 Start([this]() {
451 ASSERT_EQ(0, ptrace(PTRACE_SEIZE, worker, 0, 0)) << strerror(errno);
452 ASSERT_EQ(0, ptrace(PTRACE_INTERRUPT, worker, 0, 0)) << strerror(errno);
453 wait_for_ptrace_stop(worker);
454 ASSERT_EQ(0, ptrace(PTRACE_CONT, worker, 0, 0)) << strerror(errno);
455 });
456}