Debian Codegraph @

debian/rust-vendor/nix/test/sys/test_ptrace.rs

raw
1 #[cfg(all(
2 target_os = "linux",
3 target_env = "gnu",
4 any(target_arch = "x86_64", target_arch = "x86")
5 ))]
6 use memoffset::offset_of;
7 use nix::errno::Errno;
8 use nix::sys::ptrace;
9 #[cfg(linux_android)]
10 use nix::sys::ptrace::Options;
11 use nix::unistd::getpid;
12
13 #[cfg(linux_android)]
14 use std::mem;
15
16 use crate::*;
17
18 #[test]
19 fn test_ptrace() {
20 // Just make sure ptrace can be called at all, for now.
21 // FIXME: qemu-user doesn't implement ptrace on all arches, so permit ENOSYS
22 require_capability!("test_ptrace", CAP_SYS_PTRACE);
23 let err = ptrace::attach(getpid()).unwrap_err();
24 assert!(
25 err == Errno::EPERM || err == Errno::EINVAL || err == Errno::ENOSYS
26 );
27 }
28
29 // Just make sure ptrace_setoptions can be called at all, for now.
30 #[test]
31 #[cfg(linux_android)]
32 fn test_ptrace_setoptions() {
33 require_capability!("test_ptrace_setoptions", CAP_SYS_PTRACE);
34 let err = ptrace::setoptions(getpid(), Options::PTRACE_O_TRACESYSGOOD)
35 .unwrap_err();
36 assert_ne!(err, Errno::EOPNOTSUPP);
37 }
38
39 // Just make sure ptrace_getevent can be called at all, for now.
40 #[test]
41 #[cfg(linux_android)]
42 fn test_ptrace_getevent() {
43 require_capability!("test_ptrace_getevent", CAP_SYS_PTRACE);
44 let err = ptrace::getevent(getpid()).unwrap_err();
45 assert_ne!(err, Errno::EOPNOTSUPP);
46 }
47
48 // Just make sure ptrace_getsiginfo can be called at all, for now.
49 #[test]
50 #[cfg(linux_android)]
51 fn test_ptrace_getsiginfo() {
52 require_capability!("test_ptrace_getsiginfo", CAP_SYS_PTRACE);
53 if let Err(Errno::EOPNOTSUPP) = ptrace::getsiginfo(getpid()) {
54 panic!("ptrace_getsiginfo returns Errno::EOPNOTSUPP!");
55 }
56 }
57
58 // Just make sure ptrace_setsiginfo can be called at all, for now.
59 #[test]
60 #[cfg(linux_android)]
61 fn test_ptrace_setsiginfo() {
62 require_capability!("test_ptrace_setsiginfo", CAP_SYS_PTRACE);
63 let siginfo = unsafe { mem::zeroed() };
64 if let Err(Errno::EOPNOTSUPP) = ptrace::setsiginfo(getpid(), &siginfo) {
65 panic!("ptrace_setsiginfo returns Errno::EOPNOTSUPP!");
66 }
67 }
68
69 #[test]
70 fn test_ptrace_cont() {
71 use nix::sys::ptrace;
72 use nix::sys::signal::{raise, Signal};
73 use nix::sys::wait::{waitpid, WaitPidFlag, WaitStatus};
74 use nix::unistd::fork;
75 use nix::unistd::ForkResult::*;
76
77 require_capability!("test_ptrace_cont", CAP_SYS_PTRACE);
78
79 let _m = crate::FORK_MTX.lock();
80
81 // FIXME: qemu-user doesn't implement ptrace on all architectures
82 // and returns ENOSYS in this case.
83 // We (ab)use this behavior to detect the affected platforms
84 // and skip the test then.
85 // On valid platforms the ptrace call should return Errno::EPERM, this
86 // is already tested by `test_ptrace`.
87 let err = ptrace::attach(getpid()).unwrap_err();
88 if err == Errno::ENOSYS {
89 return;
90 }
91
92 match unsafe { fork() }.expect("Error: Fork Failed") {
93 Child => {
94 ptrace::traceme().unwrap();
95 // As recommended by ptrace(2), raise SIGTRAP to pause the child
96 // until the parent is ready to continue
97 loop {
98 raise(Signal::SIGTRAP).unwrap();
99 }
100 }
101 Parent { child } => {
102 assert_eq!(
103 waitpid(child, None),
104 Ok(WaitStatus::Stopped(child, Signal::SIGTRAP))
105 );
106 ptrace::cont(child, None).unwrap();
107 assert_eq!(
108 waitpid(child, None),
109 Ok(WaitStatus::Stopped(child, Signal::SIGTRAP))
110 );
111 ptrace::cont(child, Some(Signal::SIGKILL)).unwrap();
112 match waitpid(child, None) {
113 Ok(WaitStatus::Signaled(pid, Signal::SIGKILL, _))
114 if pid == child =>
115 {
116 // FIXME It's been observed on some systems (apple) the
117 // tracee may not be killed but remain as a zombie process
118 // affecting other wait based tests. Add an extra kill just
119 // to make sure there are no zombies.
120 let _ = waitpid(child, Some(WaitPidFlag::WNOHANG));
121 while ptrace::cont(child, Some(Signal::SIGKILL)).is_ok() {
122 let _ = waitpid(child, Some(WaitPidFlag::WNOHANG));
123 }
124 }
125 _ => panic!("The process should have been killed"),
126 }
127 }
128 }
129 }
130
131 #[cfg(target_os = "linux")]
132 #[test]
133 fn test_ptrace_interrupt() {
134 use nix::sys::ptrace;
135 use nix::sys::signal::Signal;
136 use nix::sys::wait::{waitpid, WaitPidFlag, WaitStatus};
137 use nix::unistd::fork;
138 use nix::unistd::ForkResult::*;
139 use std::thread::sleep;
140 use std::time::Duration;
141
142 require_capability!("test_ptrace_interrupt", CAP_SYS_PTRACE);
143
144 let _m = crate::FORK_MTX.lock();
145
146 match unsafe { fork() }.expect("Error: Fork Failed") {
147 Child => loop {
148 sleep(Duration::from_millis(1000));
149 },
150 Parent { child } => {
151 ptrace::seize(child, ptrace::Options::PTRACE_O_TRACESYSGOOD)
152 .unwrap();
153 ptrace::interrupt(child).unwrap();
154 assert_eq!(
155 waitpid(child, None),
156 Ok(WaitStatus::PtraceEvent(child, Signal::SIGTRAP, 128))
157 );
158 ptrace::syscall(child, None).unwrap();
159 assert_eq!(
160 waitpid(child, None),
161 Ok(WaitStatus::PtraceSyscall(child))
162 );
163 ptrace::detach(child, Some(Signal::SIGKILL)).unwrap();
164 match waitpid(child, None) {
165 Ok(WaitStatus::Signaled(pid, Signal::SIGKILL, _))
166 if pid == child =>
167 {
168 let _ = waitpid(child, Some(WaitPidFlag::WNOHANG));
169 while ptrace::cont(child, Some(Signal::SIGKILL)).is_ok() {
170 let _ = waitpid(child, Some(WaitPidFlag::WNOHANG));
171 }
172 }
173 _ => panic!("The process should have been killed"),
174 }
175 }
176 }
177 }
178
179 // ptrace::{setoptions, getregs} are only available in these platforms
180 #[cfg(all(
181 target_os = "linux",
182 any(
183 all(
184 target_env = "gnu",
185 any(
186 target_arch = "x86_64",
187 target_arch = "x86",
188 target_arch = "aarch64",
189 target_arch = "riscv64"
190 )
191 ),
192 all(target_env = "musl", target_arch = "aarch64")
193 )
194 ))]
195 #[test]
196 fn test_ptrace_syscall() {
197 use nix::sys::ptrace;
198 use nix::sys::signal::kill;
199 use nix::sys::signal::Signal;
200 use nix::sys::wait::{waitpid, WaitStatus};
201 use nix::unistd::fork;
202 use nix::unistd::getpid;
203 use nix::unistd::ForkResult::*;
204
205 require_capability!("test_ptrace_syscall", CAP_SYS_PTRACE);
206
207 let _m = crate::FORK_MTX.lock();
208
209 match unsafe { fork() }.expect("Error: Fork Failed") {
210 Child => {
211 ptrace::traceme().unwrap();
212 // first sigstop until parent is ready to continue
213 let pid = getpid();
214 kill(pid, Signal::SIGSTOP).unwrap();
215 kill(pid, Signal::SIGTERM).unwrap();
216 unsafe {
217 ::libc::_exit(0);
218 }
219 }
220
221 Parent { child } => {
222 assert_eq!(
223 waitpid(child, None),
224 Ok(WaitStatus::Stopped(child, Signal::SIGSTOP))
225 );
226
227 // set this option to recognize syscall-stops
228 ptrace::setoptions(child, ptrace::Options::PTRACE_O_TRACESYSGOOD)
229 .unwrap();
230
231 #[cfg(target_arch = "x86_64")]
232 let get_syscall_id =
233 || ptrace::getregs(child).unwrap().orig_rax as libc::c_long;
234
235 #[cfg(target_arch = "x86")]
236 let get_syscall_id =
237 || ptrace::getregs(child).unwrap().orig_eax as libc::c_long;
238
239 #[cfg(target_arch = "aarch64")]
240 let get_syscall_id =
241 || ptrace::getregs(child).unwrap().regs[8] as libc::c_long;
242
243 #[cfg(target_arch = "riscv64")]
244 let get_syscall_id =
245 || ptrace::getregs(child).unwrap().a7 as libc::c_long;
246
247 // this duplicates `get_syscall_id` for the purpose of testing `ptrace::read_user`.
248 #[cfg(target_arch = "x86_64")]
249 let rax_offset = offset_of!(libc::user_regs_struct, orig_rax);
250 #[cfg(target_arch = "x86")]
251 let rax_offset = offset_of!(libc::user_regs_struct, orig_eax);
252
253 #[cfg(any(target_arch = "x86_64", target_arch = "x86"))]
254 let get_syscall_from_user_area = || {
255 // Find the offset of `user.regs.rax` (or `user.regs.eax` for x86)
256 let rax_offset = offset_of!(libc::user, regs) + rax_offset;
257 ptrace::read_user(child, rax_offset as _).unwrap()
258 as libc::c_long
259 };
260
261 // kill entry
262 ptrace::syscall(child, None).unwrap();
263 assert_eq!(
264 waitpid(child, None),
265 Ok(WaitStatus::PtraceSyscall(child))
266 );
267 assert_eq!(get_syscall_id(), ::libc::SYS_kill);
268 #[cfg(any(target_arch = "x86_64", target_arch = "x86"))]
269 assert_eq!(get_syscall_from_user_area(), ::libc::SYS_kill);
270
271 // kill exit
272 ptrace::syscall(child, None).unwrap();
273 assert_eq!(
274 waitpid(child, None),
275 Ok(WaitStatus::PtraceSyscall(child))
276 );
277 assert_eq!(get_syscall_id(), ::libc::SYS_kill);
278 #[cfg(any(target_arch = "x86_64", target_arch = "x86"))]
279 assert_eq!(get_syscall_from_user_area(), ::libc::SYS_kill);
280
281 // receive signal
282 ptrace::syscall(child, None).unwrap();
283 assert_eq!(
284 waitpid(child, None),
285 Ok(WaitStatus::Stopped(child, Signal::SIGTERM))
286 );
287
288 // inject signal
289 ptrace::syscall(child, Signal::SIGTERM).unwrap();
290 assert_eq!(
291 waitpid(child, None),
292 Ok(WaitStatus::Signaled(child, Signal::SIGTERM, false))
293 );
294 }
295 }
296 }
297
298 #[cfg(all(
299 target_os = "linux",
300 any(
301 all(
302 target_env = "gnu",
303 any(
304 target_arch = "x86_64",
305 target_arch = "x86",
306 target_arch = "aarch64",
307 target_arch = "riscv64"
308 )
309 ),
310 all(target_env = "musl", target_arch = "aarch64")
311 )
312 ))]
313 #[test]
314 fn test_ptrace_regsets() {
315 use nix::sys::ptrace::{self, getregset, regset, setregset};
316 use nix::sys::signal::*;
317 use nix::sys::wait::{waitpid, WaitStatus};
318 use nix::unistd::fork;
319 use nix::unistd::ForkResult::*;
320
321 require_capability!("test_ptrace_regsets", CAP_SYS_PTRACE);
322
323 let _m = crate::FORK_MTX.lock();
324
325 match unsafe { fork() }.expect("Error: Fork Failed") {
326 Child => {
327 ptrace::traceme().unwrap();
328 // As recommended by ptrace(2), raise SIGTRAP to pause the child
329 // until the parent is ready to continue
330 loop {
331 raise(Signal::SIGTRAP).unwrap();
332 }
333 }
334
335 Parent { child } => {
336 assert_eq!(
337 waitpid(child, None),
338 Ok(WaitStatus::Stopped(child, Signal::SIGTRAP))
339 );
340 let mut regstruct =
341 getregset::<regset::NT_PRSTATUS>(child).unwrap();
342 let mut fpregstruct =
343 getregset::<regset::NT_PRFPREG>(child).unwrap();
344
345 #[cfg(target_arch = "x86_64")]
346 let (reg, fpreg) =
347 (&mut regstruct.r15, &mut fpregstruct.st_space[5]);
348 #[cfg(target_arch = "x86")]
349 let (reg, fpreg) =
350 (&mut regstruct.edx, &mut fpregstruct.st_space[5]);
351 #[cfg(target_arch = "aarch64")]
352 let (reg, fpreg) =
353 (&mut regstruct.regs[16], &mut fpregstruct.vregs[5]);
354 #[cfg(target_arch = "riscv64")]
355 let (reg, fpreg) = (&mut regstruct.t1, &mut fpregstruct.__f[5]);
356
357 *reg = 0xdeadbeefu32 as _;
358 *fpreg = 0xfeedfaceu32 as _;
359 let _ = setregset::<regset::NT_PRSTATUS>(child, regstruct);
360 regstruct = getregset::<regset::NT_PRSTATUS>(child).unwrap();
361 let _ = setregset::<regset::NT_PRFPREG>(child, fpregstruct);
362 fpregstruct = getregset::<regset::NT_PRFPREG>(child).unwrap();
363
364 #[cfg(target_arch = "x86_64")]
365 let (reg, fpreg) = (regstruct.r15, fpregstruct.st_space[5]);
366 #[cfg(target_arch = "x86")]
367 let (reg, fpreg) = (regstruct.edx, fpregstruct.st_space[5]);
368 #[cfg(target_arch = "aarch64")]
369 let (reg, fpreg) = (regstruct.regs[16], fpregstruct.vregs[5]);
370 #[cfg(target_arch = "riscv64")]
371 let (reg, fpreg) = (regstruct.t1, fpregstruct.__f[5]);
372 assert_eq!(reg, 0xdeadbeefu32 as _);
373 assert_eq!(fpreg, 0xfeedfaceu32 as _);
374
375 ptrace::cont(child, Some(Signal::SIGKILL)).unwrap();
376 match waitpid(child, None) {
377 Ok(WaitStatus::Signaled(pid, Signal::SIGKILL, _))
378 if pid == child => {}
379 _ => panic!("The process should have been killed"),
380 }
381 }
382 }
383 }
384
385 #[cfg(all(target_os = "linux", target_env = "gnu"))]
386 #[test]
387 fn test_ptrace_syscall_info() {
388 use nix::sys::ptrace;
389 use nix::sys::wait::{waitpid, WaitStatus};
390 use nix::unistd::fork;
391 use nix::unistd::ForkResult::*;
392
393 require_capability!("test_ptrace_syscall_info", CAP_SYS_PTRACE);
394
395 let _m = crate::FORK_MTX.lock();
396 match unsafe { fork() }.expect("Error: Fork Failed") {
397 Child => {
398 ptrace::traceme().unwrap();
399 std::thread::sleep(std::time::Duration::from_millis(1000));
400 unsafe {
401 ::libc::_exit(0);
402 }
403 }
404 Parent { child } => loop {
405 if let Ok(WaitStatus::Exited(_, 0)) = waitpid(child, None) {
406 break;
407 }
408 let si = ptrace::syscall_info(child).unwrap();
409 assert!(si.op >= libc::PTRACE_SYSCALL_INFO_ENTRY);
410 },
411 }
412 }