#include <sys/ptrace.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <sys/user.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
#include <stddef.h>
static void* const break_addr = (void*)0x40074d;
static long text;
int main(int argc, char *argv[])
{pid_t pid;
long err;
struct user_regs_struct regs;
if (pid == 0)
{
int i =0;
sleep(1);
printf("hello=%d\n",i++);
printf("world=%d\n",i++);
}
else if (pid > 0)
{
err = ptrace(PTRACE_ATTACH, pid, NULL, NULL);
if (err == -1)
{
printf("attach err due to %d\n",errno);
}
waitpid(pid, NULL, 0);
// set trap at breakpoint
{
text = ptrace(PTRACE_PEEKTEXT, pid, break_addr, NULL);
if (text == -1)
{
printf("peek text err due to %d\n",errno);
}
long trap = (text & (~0xff)) | 0xcc;
err = ptrace(PTRACE_POKETEXT, pid, break_addr, (void*)trap);
if (err == -1)
{
printf("poke text err due to %d\n",errno);
}
ptrace(PTRACE_CONT, pid, NULL, NULL);
waitpid(pid,NULL,0);
}
// restore at breakpoint
{
sleep(5);
err = ptrace(PTRACE_GETREGS, pid, NULL, ®s);
if (err == -1)
{
printf("get regs err due to %d\n",errno);
}
#if 0
for(i=0;i<sizeof(regs)/sizeof(unsigned long long int);i++)
{
unsigned long long int *p = (unsigned long long int *)®s;
printf("reg:%llx\n",p[i]);
}
#endif
regs.rip = (unsigned long long int)break_addr;
err = ptrace(PTRACE_SETREGS, pid, NULL, ®s);
if (err == -1)
{
printf("restore regs err due to %d\n",errno);
}
err = ptrace(PTRACE_POKETEXT, pid, break_addr, (void*)text);
if (err == -1)
{
printf("restore text err due to %d\n",errno);
}
ptrace(PTRACE_CONT, pid, NULL, NULL);
}
waitpid(pid,NULL,0);
printf("exit\n");
}
return 0;
}