I want to attach myself to a process and intercept all printf calls from that process.
main.c
int main()
{
int i;
for(i = 0; i < 10; i++)
{
printf("HelloWorld\n");
sleep(5);
}
return 0;
}
Then to attach I have this code, and I want to do an infinite loop or until the main.c finishes -- infinite loop will work this is only Hello World with ptrace for testing, nothing fancy.
#include <sys/ptrace.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <sys/user.h> // For user_regs_struct
int main(int argc, char *argv[])
{
struct user_regs_struct regs;
pid_t traced_process = atoi(argv[1]);
long t = ptrace(PTRACE_ATTACH, traced_process, NULL, NULL);
wait(NULL);
ptrace(PTRACE_GETREGS, traced_process, NULL, ®s);
long ins = ptrace(PTRACE_PEEKTEXT, traced_process, regs.eip, NULL);
printf("EIP: %lx Instruction executed: %lx\n", regs.eip, ins);
char *c = &ins;
printf("%c\n",c);
ptrace(PTRACE_DETACH, traced_process, NULL, NULL);
return 0;
}
I tried to put while(1) after attaching but that will actually just loop on the first printf executed in main.c.
I am really struggling with this, every example I run into is literally a copy paste of the other with huge amounts of code that is not even related to what I'm trying to do. I do know for sure that printf is a write() in the kernel, so that's what I should be looking for.
So again I want to get a reference to the string that printf is trying to print to the screen in the other terminal. How do I do this?