Are there any guides or examples (especially ARM ones) or libraries of using ptrace
to affect execution of other process? For example, to make it believe that some data is appeared on file descriptor (i.e. release select/poll with some result and "answer" the following read syscall before the kernel). Expecting something involving PTRACE_SYSEMU.
Can it be done in portable way? I want something like libc-overriding LD_PRELOAD trick, but which can be attached at runtime.
Can it be done with some gdb commands?
Ideal variant would be if there is some library where I can easily and portably hook into syscalls and edit them before of after the actual call is made (or emulate them), like when doing it using LD_PRELOAD.
You can use the PTRACE_SYSCALL request: it restarts the child process (just like PTRACE_CONT) but arranges for it to stop at the next entry to or exit from a system call. For example (assume a kernel built for x86):
The child prints its PID and delivers a signal to itself. Because of the prior call to
ptrace()
this means it will be stopped.The parent waits for this to happen and restarts the child with PTRACE_SYSCALL, then waits. Next, the child invokes the
getpid
system call and it is stopped once again. The parent process uses the PTRACE_GETREGS invocation to peek into the child's registers, whereeax
holds the system call number. The parent changes this to the system call number ofgetppid
, then once again allows the child to continue. Because the system call number has changed prior to the invocation of the system call, the child will now invokegetppid
instead ofgetpid
.Using
ptrace
for this purpose may be portable, but I have not tested it. In gdb, you can also use thecatch syscall
command.