对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
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
#include
#include
#include
#include
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