ptrace的小例子

#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;


    pid = fork();
    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, &regs);
            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 *)&regs;
                printf("reg:%llx\n",p[i]);
            }
#endif
            regs.rip = (unsigned long long int)break_addr;
            err = ptrace(PTRACE_SETREGS, pid, NULL, &regs);
            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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值