您的位置:首页 > 运维架构 > Linux

[Ptrace]Linux内存替换(二)信息获取

2015-07-30 10:55 351 查看
对ptrace有了初步了解后,到网上找了一个简单例程熟悉一下,实现效果为B程序附加到A程序上获取A程序EIP等相关信息后输出。

【环境】

CentOS 6.4 RC

Linux version 2.6.32-358.el6.i686

Gcc version 4.4.7 20120313

【A程序:counter.c】

#include <stdio.h>

int main()
{
int i;
for(i = 0;i < 20; ++i) {
printf("My counter: %d \n", i);
sleep(1);
}
return 0;
}


gcc -o counter counter.c

【B程序:attach.c】

#include <sys/ptrace.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/user.h>
#include <stdio.h>

int main(int argc, char *argv[])
{
pid_t traced_process;
struct user_regs_struct regs;
long ins;
if(argc != 2) {
printf("PID?");
return 1;
}
traced_process = atoi(argv[1]);
ptrace(PTRACE_ATTACH, traced_process,
NULL, NULL);
wait(NULL);
ptrace(PTRACE_GETREGS, traced_process,
NULL, ®s);
ins = ptrace(PTRACE_PEEKTEXT,
traced_process, regs.eip, NULL);
printf("EIP: %lx Instruction executed:
%lx ", regs.eip, ins);
ptrace(PTRACE_DETACH, traced_process,
NULL, NULL);
return 0;
}


gcc -o attach attach.c

【执行】

1. run counter

./counter

2. find pid of counter

ps aux | grep counter

3. run attach

./attach %pid%

【结果】

EIP:717424 Instruction executed: c3595a5d

【参考】

http://www.cnblogs.com/wangkangluo1/archive/2012/06/05/2535484.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: