Stack Walk on linux using ptrace
Following is my requirement.
while process A is running.
- attach Process A from B with PTRACE_ATTACH.
- Start a Loop
- Stop Process A
- read registers
- Resume Process A
- sleep(开发者_C百科1)
- end loop
- detach A
i am facing issue with Start and Resume Process A from the loop. i tried combination of kill(pid,SIGSTOP), kill(pid,SIGCONT), PTRACE_CONT. but didnt work.
any other solutions please?
Thanks in advance. Sandeep
Following code is working for me and seems to fulfill your requirements -
A.c
#include<stdio.h>
int main()
{
int i=0;
printf("My PID is - %ld\n",getpid());
while(i>=0)
{
}
return 0;
}
B.c - Tracing process
int main()
{
int pid;
int status;
struct user_regs_struct regs;
unsigned int eip;
printf("Enter pid to trace : \n");
scanf("%d",&pid);
printf("PID to be traced - %ld\n",pid);
ptrace(PTRACE_ATTACH,pid,0,0);
if(errno)
{
perror("attach");
return -1;
}
waitpid(pid,&status,WUNTRACED);
printf("Process Stopped\n");
while(1)
{
ptrace(PTRACE_GETREGS,pid,0,®s);
eip=ptrace(PTRACE_PEEKTEXT,pid,regs.eip,0);
printf("EIP - 0x%08x, instruction executed - 0x%08x\n",regs.eip,eip);
ptrace(PTRACE_CONT,pid,0,0);
waitpid(pid,&status,WUNTRACED);
}
return 0;
}
Signal passed -
kill -STOP 17779 kill -STOP 17779
Output of A -
xxxxx!xxxxx:~/myPer/stack_overflow [135]$ ./A
My PID is - 17779
Output of B -
XXXXX!xxxxx:~/myPer/stack_overflow [121]$ ./B
Enter pid to trace :
17779
PID to be traced - 17779
Process Stopped
EIP - 0x080483e1, instruction executed - 0x00f87d83
EIP - 0x080483e5, instruction executed - 0x00b8fa79
EIP - 0x080483e5, instruction executed - 0x00b8fa79
We see that B displays EIP value for each signal delivered to client. Basically signal is not getting delivered to A instead B wakes up and examines EIP and then continues in the loop. You can modify the code to deliver the signal if you want.
This is what i understood from your question. If i understood something else please let me know and i'll update answer accordingly
Sounds like a very challenging project to undertake from scratch. Have you considered leveraging the GNU debugger in any way? In particular there is an long running sub-project called libgdb2 which may suit your purposes even though it is far from finished or stable at this time.
You could try scripting/interfacing with gdb in the same way that a lot of IDE's do. See also http://www.redhat.com/docs/manuals/enterprise/RHEL-4-Manual/gdb/gdb-mi.html
精彩评论