2 * Copyright (C) 2016 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #include <sys/ptrace.h>
22 #include <sys/prctl.h>
23 #include <sys/ptrace.h>
29 #include <gtest/gtest.h>
31 #include <android-base/macros.h>
32 #include <android-base/unique_fd.h>
34 using android::base::unique_fd;
36 // Host libc does not define this.
43 explicit ChildGuard(pid_t pid) : pid(pid) {}
48 waitpid(pid, &status, 0);
55 enum class HwFeature { Watchpoint, Breakpoint };
57 static bool is_hw_feature_supported(pid_t child, HwFeature feature) {
60 long result = ptrace(PTRACE_GETHBPREGS, child, 0, &capabilities);
62 EXPECT_EQ(EIO, errno);
66 case HwFeature::Watchpoint:
67 return ((capabilities >> 8) & 0xff) > 0;
68 case HwFeature::Breakpoint:
69 return (capabilities & 0xff) > 0;
71 #elif defined(__aarch64__)
72 user_hwdebug_state dreg_state;
74 iov.iov_base = &dreg_state;
75 iov.iov_len = sizeof(dreg_state);
77 long result = ptrace(PTRACE_GETREGSET, child,
78 feature == HwFeature::Watchpoint ? NT_ARM_HW_WATCH : NT_ARM_HW_BREAK, &iov);
80 EXPECT_EQ(EINVAL, errno);
83 return (dreg_state.dbg_info & 0xff) > 0;
84 #elif defined(__i386__) || defined(__x86_64__)
85 // We assume watchpoints and breakpoints are always supported on x86.
90 // TODO: mips support.
97 static void set_watchpoint(pid_t child, uintptr_t address, size_t size) {
98 ASSERT_EQ(0u, address & 0x7) << "address: " << address;
99 #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;
106 ASSERT_EQ(0, ptrace(PTRACE_SETHBPREGS, child, -1, &address)) << strerror(errno);
107 ASSERT_EQ(0, ptrace(PTRACE_SETHBPREGS, child, -2, &control)) << strerror(errno);
109 user_hwdebug_state dreg_state;
110 memset(&dreg_state, 0, sizeof dreg_state);
111 dreg_state.dbg_regs[0].addr = address;
112 dreg_state.dbg_regs[0].ctrl = control;
115 iov.iov_base = &dreg_state;
116 iov.iov_len = offsetof(user_hwdebug_state, dbg_regs) + sizeof(dreg_state.dbg_regs[0]);
118 ASSERT_EQ(0, ptrace(PTRACE_SETREGSET, child, NT_ARM_HW_WATCH, &iov)) << strerror(errno);
120 #elif defined(__i386__) || defined(__x86_64__)
121 ASSERT_EQ(0, ptrace(PTRACE_POKEUSER, child, offsetof(user, u_debugreg[0]), address)) << strerror(errno);
123 unsigned data = ptrace(PTRACE_PEEKUSER, child, offsetof(user, u_debugreg[7]), nullptr);
126 const unsigned size_flag = (size == 8) ? 2 : size - 1;
127 const unsigned enable = 1;
128 const unsigned type = 1; // Write.
130 const unsigned mask = 3 << 18 | 3 << 16 | 1;
131 const unsigned value = size_flag << 18 | type << 16 | enable;
134 ASSERT_EQ(0, ptrace(PTRACE_POKEUSER, child, offsetof(user, u_debugreg[7]), data)) << strerror(errno);
142 template <typename T>
143 static void run_watchpoint_test(std::function<void(T&)> child_func, size_t offset, size_t size) {
144 alignas(16) T data{};
146 pid_t child = fork();
147 ASSERT_NE(-1, child) << strerror(errno);
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)");
155 if (ptrace(PTRACE_TRACEME, 0, nullptr, nullptr) == -1) {
156 perror("ptrace(PTRACE_TRACEME)");
164 ChildGuard guard(child);
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;
171 if (!is_hw_feature_supported(child, HwFeature::Watchpoint)) {
172 GTEST_LOG_(INFO) << "Skipping test because hardware support is not available.\n";
176 set_watchpoint(child, uintptr_t(&data) + offset, size);
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;
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__)
187 ASSERT_LE(&data, siginfo.si_addr);
188 ASSERT_GT((&data) + 1, siginfo.si_addr);
192 template <typename T>
193 static void watchpoint_stress_child(unsigned cpu, T& data) {
197 if (sched_setaffinity(0, sizeof cpus, &cpus) == -1) {
198 perror("sched_setaffinity");
201 raise(SIGSTOP); // Synchronize with the tracer, let it set the watchpoint.
203 data = 1; // Now trigger the watchpoint.
206 template <typename T>
207 static void run_watchpoint_stress(size_t cpu) {
208 run_watchpoint_test<T>(std::bind(watchpoint_stress_child<T>, cpu, std::placeholders::_1), 0,
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.
215 TEST(sys_ptrace, watchpoint_stress) {
216 cpu_set_t available_cpus;
217 ASSERT_EQ(0, sched_getaffinity(0, sizeof available_cpus, &available_cpus));
219 for (size_t cpu = 0; cpu < CPU_SETSIZE; ++cpu) {
220 if (!CPU_ISSET(cpu, &available_cpus)) continue;
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);
234 static void watchpoint_imprecise_child(Uint128_t& data) {
235 raise(SIGSTOP); // Synchronize with the tracer, let it set the watchpoint.
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__)
249 // Test that the kernel is able to handle the case when the instruction writes
250 // to a larger block of memory than the one we are watching. If you see this
251 // test fail on arm64, you will likely need to cherry-pick fdfeff0f into your
253 TEST(sys_ptrace, watchpoint_imprecise) {
254 // Make sure we get interrupted in case a buggy kernel does not report the
255 // watchpoint hit correctly.
256 struct sigaction action, oldaction;
257 action.sa_handler = [](int) {};
258 sigemptyset(&action.sa_mask);
260 ASSERT_EQ(0, sigaction(SIGALRM, &action, &oldaction)) << strerror(errno);
263 run_watchpoint_test<Uint128_t>(watchpoint_imprecise_child, 8, 8);
265 ASSERT_EQ(0, sigaction(SIGALRM, &oldaction, nullptr)) << strerror(errno);
268 static void __attribute__((noinline)) breakpoint_func() {
272 static void __attribute__((noreturn)) breakpoint_fork_child() {
273 // Extra precaution: make sure we go away if anything happens to our parent.
274 if (prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0) == -1) {
275 perror("prctl(PR_SET_PDEATHSIG)");
279 if (ptrace(PTRACE_TRACEME, 0, nullptr, nullptr) == -1) {
280 perror("ptrace(PTRACE_TRACEME)");
284 raise(SIGSTOP); // Synchronize with the tracer, let it set the breakpoint.
286 breakpoint_func(); // Now trigger the breakpoint.
291 static void set_breakpoint(pid_t child) {
292 uintptr_t address = uintptr_t(breakpoint_func);
293 #if defined(__arm__) || defined(__aarch64__)
295 const unsigned byte_mask = 0xf;
296 const unsigned enable = 1;
297 const unsigned control = byte_mask << 5 | enable;
300 ASSERT_EQ(0, ptrace(PTRACE_SETHBPREGS, child, 1, &address)) << strerror(errno);
301 ASSERT_EQ(0, ptrace(PTRACE_SETHBPREGS, child, 2, &control)) << strerror(errno);
303 user_hwdebug_state dreg_state;
304 memset(&dreg_state, 0, sizeof dreg_state);
305 dreg_state.dbg_regs[0].addr = reinterpret_cast<uintptr_t>(address);
306 dreg_state.dbg_regs[0].ctrl = control;
309 iov.iov_base = &dreg_state;
310 iov.iov_len = offsetof(user_hwdebug_state, dbg_regs) + sizeof(dreg_state.dbg_regs[0]);
312 ASSERT_EQ(0, ptrace(PTRACE_SETREGSET, child, NT_ARM_HW_BREAK, &iov)) << strerror(errno);
314 #elif defined(__i386__) || defined(__x86_64__)
315 ASSERT_EQ(0, ptrace(PTRACE_POKEUSER, child, offsetof(user, u_debugreg[0]), address))
318 unsigned data = ptrace(PTRACE_PEEKUSER, child, offsetof(user, u_debugreg[7]), nullptr);
321 const unsigned size = 0;
322 const unsigned enable = 1;
323 const unsigned type = 0; // Execute
325 const unsigned mask = 3 << 18 | 3 << 16 | 1;
326 const unsigned value = size << 18 | type << 16 | enable;
329 ASSERT_EQ(0, ptrace(PTRACE_POKEUSER, child, offsetof(user, u_debugreg[7]), data))
337 // Test hardware breakpoint API. The test is considered successful if the breakpoints get hit OR the
338 // system reports that hardware breakpoint support is not present.
339 TEST(sys_ptrace, hardware_breakpoint) {
340 pid_t child = fork();
341 ASSERT_NE(-1, child) << strerror(errno);
342 if (child == 0) breakpoint_fork_child();
344 ChildGuard guard(child);
347 ASSERT_EQ(child, waitpid(child, &status, __WALL)) << strerror(errno);
348 ASSERT_TRUE(WIFSTOPPED(status)) << "Status was: " << status;
349 ASSERT_EQ(SIGSTOP, WSTOPSIG(status)) << "Status was: " << status;
351 if (!is_hw_feature_supported(child, HwFeature::Breakpoint)) {
352 GTEST_LOG_(INFO) << "Skipping test because hardware support is not available.\n";
356 set_breakpoint(child);
358 ASSERT_EQ(0, ptrace(PTRACE_CONT, child, nullptr, nullptr)) << strerror(errno);
359 ASSERT_EQ(child, waitpid(child, &status, __WALL)) << strerror(errno);
360 ASSERT_TRUE(WIFSTOPPED(status)) << "Status was: " << status;
361 ASSERT_EQ(SIGTRAP, WSTOPSIG(status)) << "Status was: " << status;
364 ASSERT_EQ(0, ptrace(PTRACE_GETSIGINFO, child, nullptr, &siginfo)) << strerror(errno);
365 ASSERT_EQ(TRAP_HWBKPT, siginfo.si_code);
368 class PtraceResumptionTest : public ::testing::Test {
371 PtraceResumptionTest() {
374 ~PtraceResumptionTest() {
377 void AssertDeath(int signo);
378 void Start(std::function<void()> f) {
379 unique_fd worker_pipe_read, worker_pipe_write;
381 ASSERT_EQ(0, pipe2(pipefd, O_CLOEXEC));
382 worker_pipe_read.reset(pipefd[0]);
383 worker_pipe_write.reset(pipefd[1]);
386 ASSERT_NE(-1, worker);
389 worker_pipe_write.reset();
390 TEMP_FAILURE_RETRY(read(worker_pipe_read.get(), &buf, sizeof(buf)));
394 pid_t tracer = fork();
395 ASSERT_NE(-1, tracer);
398 if (HasFatalFailure()) {
405 pid_t rc = waitpid(tracer, &result, 0);
406 ASSERT_EQ(tracer, rc);
407 EXPECT_TRUE(WIFEXITED(result) || WIFSIGNALED(result));
408 if (WIFEXITED(result)) {
409 if (WEXITSTATUS(result) != 0) {
410 FAIL() << "tracer failed";
414 rc = waitpid(worker, &result, WNOHANG);
417 worker_pipe_write.reset();
419 rc = waitpid(worker, &result, 0);
420 ASSERT_EQ(worker, rc);
421 EXPECT_TRUE(WIFEXITED(result));
422 EXPECT_EQ(WEXITSTATUS(result), 0);
426 static void wait_for_ptrace_stop(pid_t pid) {
429 pid_t rc = TEMP_FAILURE_RETRY(waitpid(pid, &status, __WALL));
433 if (WIFSTOPPED(status)) {
439 TEST_F(PtraceResumptionTest, seize) {
440 Start([this]() { ASSERT_EQ(0, ptrace(PTRACE_SEIZE, worker, 0, 0)) << strerror(errno); });
443 TEST_F(PtraceResumptionTest, seize_interrupt) {
445 ASSERT_EQ(0, ptrace(PTRACE_SEIZE, worker, 0, 0)) << strerror(errno);
446 ASSERT_EQ(0, ptrace(PTRACE_INTERRUPT, worker, 0, 0)) << strerror(errno);
450 TEST_F(PtraceResumptionTest, seize_interrupt_cont) {
452 ASSERT_EQ(0, ptrace(PTRACE_SEIZE, worker, 0, 0)) << strerror(errno);
453 ASSERT_EQ(0, ptrace(PTRACE_INTERRUPT, worker, 0, 0)) << strerror(errno);
454 wait_for_ptrace_stop(worker);
455 ASSERT_EQ(0, ptrace(PTRACE_CONT, worker, 0, 0)) << strerror(errno);