1 /*
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>
20 #include <fcntl.h>
21 #include <sched.h>
22 #include <sys/prctl.h>
23 #include <sys/ptrace.h>
24 #include <sys/uio.h>
25 #include <sys/user.h>
26 #include <sys/wait.h>
27 #include <unistd.h>
28
29 #include <gtest/gtest.h>
30
31 #include <android-base/macros.h>
32 #include <android-base/unique_fd.h>
33
34 using android::base::unique_fd;
35
36 // Host libc does not define this.
37 #ifndef TRAP_HWBKPT
38 #define TRAP_HWBKPT 4
39 #endif
40
41 class ChildGuard {
42 public:
ChildGuard(pid_t pid)43 explicit ChildGuard(pid_t pid) : pid(pid) {}
44
~ChildGuard()45 ~ChildGuard() {
46 kill(pid, SIGKILL);
47 int status;
48 waitpid(pid, &status, 0);
49 }
50
51 private:
52 pid_t pid;
53 };
54
55 enum class HwFeature { Watchpoint, Breakpoint };
56
is_hw_feature_supported(pid_t child,HwFeature feature)57 static bool is_hw_feature_supported(pid_t child, HwFeature feature) {
58 #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 }
65 switch (feature) {
66 case HwFeature::Watchpoint:
67 return ((capabilities >> 8) & 0xff) > 0;
68 case HwFeature::Breakpoint:
69 return (capabilities & 0xff) > 0;
70 }
71 #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
77 long result = ptrace(PTRACE_GETREGSET, child,
78 feature == HwFeature::Watchpoint ? NT_ARM_HW_WATCH : NT_ARM_HW_BREAK, &iov);
79 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__)
85 // We assume watchpoints and breakpoints are always supported on x86.
86 UNUSED(child);
87 UNUSED(feature);
88 return true;
89 #else
90 // TODO: mips support.
91 UNUSED(child);
92 UNUSED(feature);
93 return false;
94 #endif
95 }
96
set_watchpoint(pid_t child,uintptr_t address,size_t size)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;
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);
111 dreg_state.dbg_regs[0].addr = address;
112 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
136 UNUSED(child);
137 UNUSED(address);
138 UNUSED(size);
139 #endif
140 }
141
142 template <typename T>
run_watchpoint_test(std::function<void (T &)> child_func,size_t offset,size_t size)143 static void run_watchpoint_test(std::function<void(T&)> child_func, size_t offset, size_t size) {
144 alignas(16) T data{};
145
146 pid_t child = fork();
147 ASSERT_NE(-1, child) << strerror(errno);
148 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 }
163
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
171 if (!is_hw_feature_supported(child, HwFeature::Watchpoint)) {
172 GTEST_LOG_(INFO) << "Skipping test because hardware support is not available.\n";
173 return;
174 }
175
176 set_watchpoint(child, uintptr_t(&data) + offset, size);
177
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__)
187 ASSERT_LE(&data, siginfo.si_addr);
188 ASSERT_GT((&data) + 1, siginfo.si_addr);
189 #endif
190 }
191
192 template <typename T>
watchpoint_stress_child(unsigned cpu,T & data)193 static 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
206 template <typename T>
run_watchpoint_stress(size_t cpu)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,
209 sizeof(T));
210 }
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.
TEST(sys_ptrace,watchpoint_stress)215 TEST(sys_ptrace, watchpoint_stress) {
216 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;
221
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
228 }
229 }
230
231 struct Uint128_t {
232 uint64_t data[2];
233 };
watchpoint_imprecise_child(Uint128_t & data)234 static 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 UNUSED(data);
246 #endif
247 }
248
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
252 // kernel.
TEST(sys_ptrace,watchpoint_imprecise)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);
259 action.sa_flags = 0;
260 ASSERT_EQ(0, sigaction(SIGALRM, &action, &oldaction)) << strerror(errno);
261 alarm(5);
262
263 run_watchpoint_test<Uint128_t>(watchpoint_imprecise_child, 8, sizeof(void*));
264
265 ASSERT_EQ(0, sigaction(SIGALRM, &oldaction, nullptr)) << strerror(errno);
266 }
267
breakpoint_func()268 static void __attribute__((noinline)) breakpoint_func() {
269 asm volatile("");
270 }
271
breakpoint_fork_child()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)");
276 _exit(1);
277 }
278
279 if (ptrace(PTRACE_TRACEME, 0, nullptr, nullptr) == -1) {
280 perror("ptrace(PTRACE_TRACEME)");
281 _exit(2);
282 }
283
284 raise(SIGSTOP); // Synchronize with the tracer, let it set the breakpoint.
285
286 breakpoint_func(); // Now trigger the breakpoint.
287
288 _exit(0);
289 }
290
set_breakpoint(pid_t child)291 static void set_breakpoint(pid_t child) {
292 uintptr_t address = uintptr_t(breakpoint_func);
293 #if defined(__arm__) || defined(__aarch64__)
294 address &= ~3;
295 const unsigned byte_mask = 0xf;
296 const unsigned enable = 1;
297 const unsigned control = byte_mask << 5 | enable;
298
299 #ifdef __arm__
300 ASSERT_EQ(0, ptrace(PTRACE_SETHBPREGS, child, 1, &address)) << strerror(errno);
301 ASSERT_EQ(0, ptrace(PTRACE_SETHBPREGS, child, 2, &control)) << strerror(errno);
302 #else // aarch64
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;
307
308 iovec iov;
309 iov.iov_base = &dreg_state;
310 iov.iov_len = offsetof(user_hwdebug_state, dbg_regs) + sizeof(dreg_state.dbg_regs[0]);
311
312 ASSERT_EQ(0, ptrace(PTRACE_SETREGSET, child, NT_ARM_HW_BREAK, &iov)) << strerror(errno);
313 #endif
314 #elif defined(__i386__) || defined(__x86_64__)
315 ASSERT_EQ(0, ptrace(PTRACE_POKEUSER, child, offsetof(user, u_debugreg[0]), address))
316 << strerror(errno);
317 errno = 0;
318 unsigned data = ptrace(PTRACE_PEEKUSER, child, offsetof(user, u_debugreg[7]), nullptr);
319 ASSERT_EQ(0, errno);
320
321 const unsigned size = 0;
322 const unsigned enable = 1;
323 const unsigned type = 0; // Execute
324
325 const unsigned mask = 3 << 18 | 3 << 16 | 1;
326 const unsigned value = size << 18 | type << 16 | enable;
327 data &= mask;
328 data |= value;
329 ASSERT_EQ(0, ptrace(PTRACE_POKEUSER, child, offsetof(user, u_debugreg[7]), data))
330 << strerror(errno);
331 #else
332 UNUSED(child);
333 UNUSED(address);
334 #endif
335 }
336
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.
TEST(sys_ptrace,hardware_breakpoint)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();
343
344 ChildGuard guard(child);
345
346 int status;
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;
350
351 if (!is_hw_feature_supported(child, HwFeature::Breakpoint)) {
352 GTEST_LOG_(INFO) << "Skipping test because hardware support is not available.\n";
353 return;
354 }
355
356 set_breakpoint(child);
357
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;
362
363 siginfo_t siginfo;
364 ASSERT_EQ(0, ptrace(PTRACE_GETSIGINFO, child, nullptr, &siginfo)) << strerror(errno);
365 ASSERT_EQ(TRAP_HWBKPT, siginfo.si_code);
366 }
367
368 class PtraceResumptionTest : public ::testing::Test {
369 public:
370 pid_t worker = -1;
PtraceResumptionTest()371 PtraceResumptionTest() {
372 }
373
~PtraceResumptionTest()374 ~PtraceResumptionTest() {
375 }
376
377 void AssertDeath(int signo);
Start(std::function<void ()> f)378 void Start(std::function<void()> f) {
379 unique_fd worker_pipe_read, worker_pipe_write;
380 int pipefd[2];
381 ASSERT_EQ(0, pipe2(pipefd, O_CLOEXEC));
382 worker_pipe_read.reset(pipefd[0]);
383 worker_pipe_write.reset(pipefd[1]);
384
385 worker = fork();
386 ASSERT_NE(-1, worker);
387 if (worker == 0) {
388 char buf;
389 worker_pipe_write.reset();
390 TEMP_FAILURE_RETRY(read(worker_pipe_read.get(), &buf, sizeof(buf)));
391 exit(0);
392 }
393
394 pid_t tracer = fork();
395 ASSERT_NE(-1, tracer);
396 if (tracer == 0) {
397 f();
398 if (HasFatalFailure()) {
399 exit(1);
400 }
401 exit(0);
402 }
403
404 int result;
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";
411 }
412 }
413
414 rc = waitpid(worker, &result, WNOHANG);
415 ASSERT_EQ(0, rc);
416
417 worker_pipe_write.reset();
418
419 rc = waitpid(worker, &result, 0);
420 ASSERT_EQ(worker, rc);
421 EXPECT_TRUE(WIFEXITED(result));
422 EXPECT_EQ(WEXITSTATUS(result), 0);
423 }
424 };
425
wait_for_ptrace_stop(pid_t pid)426 static void wait_for_ptrace_stop(pid_t pid) {
427 while (true) {
428 int status;
429 pid_t rc = TEMP_FAILURE_RETRY(waitpid(pid, &status, __WALL));
430 if (rc != pid) {
431 abort();
432 }
433 if (WIFSTOPPED(status)) {
434 return;
435 }
436 }
437 }
438
TEST_F(PtraceResumptionTest,seize)439 TEST_F(PtraceResumptionTest, seize) {
440 Start([this]() { ASSERT_EQ(0, ptrace(PTRACE_SEIZE, worker, 0, 0)) << strerror(errno); });
441 }
442
TEST_F(PtraceResumptionTest,seize_interrupt)443 TEST_F(PtraceResumptionTest, seize_interrupt) {
444 Start([this]() {
445 ASSERT_EQ(0, ptrace(PTRACE_SEIZE, worker, 0, 0)) << strerror(errno);
446 ASSERT_EQ(0, ptrace(PTRACE_INTERRUPT, worker, 0, 0)) << strerror(errno);
447 });
448 }
449
TEST_F(PtraceResumptionTest,seize_interrupt_cont)450 TEST_F(PtraceResumptionTest, seize_interrupt_cont) {
451 Start([this]() {
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);
456 });
457 }
458