本文主要分析ptrace的單步調試功能
單步調試的含義相信大家已經非常清楚了,PTRACE_SINGLESTEP參數就能夠使被跟蹤的程式逐步執行。
PTRACE_SINGLESTEP重新啟動被停止的程式,讓其執行一條指令之後又停止。我們用下面的代碼加以驗證。
list11.c
#include "ptrace.h"void main(int argc,char *argv[]){ pid_t child; int status,data; int trace_process; trace_process=atoi(argv[1]); //對目標進程進行跟蹤,ATTACH使得被跟蹤進程停止(stopped)
ptrace(PTRACE_ATTACH,trace_process,0,0); wait(&status);
//列印出使得被跟蹤進程停止的訊號資訊 if(WIFSTOPPED(status)){ printf("the child is stopped by the attach!\n"); fprintf(stderr,"%s\n",strsignal(WSTOPSIG(status))); }
//以單步模式喚醒被跟蹤進程,即被跟蹤進程執行一條指令之後又停止。 ptrace(PTRACE_SINGLESTEP,trace_process,0,0); while(1){ //printf("just to see 1!\n");
//被跟蹤進程單步運行時,被跟蹤進程停止,該wait被喚醒 wait(&status);
//被跟蹤進程退出時,跳出迴圈 if(WIFEXITED(status)){ fprintf(stderr,"%s",strsignal(WEXITSTATUS(status))); printf("the child is exit!\n"); break; } else{
//逐步執行,知道i=10這條語句執行,然後將i換成245. data=ptrace(PTRACE_PEEKDATA,trace_process,0x08049764,0); if(data==10){ printf("the data now is %d\n",data); data=245; ptrace(PTRACE_POKEDATA,trace_process,0x08049764,data); ptrace(PTRACE_CONT,trace_process,0,0); break; } } ptrace(PTRACE_SINGLESTEP,trace_process,0,0); }
//子進程結束時該wait喚醒。 wait(&status); if(WIFEXITED(status)){ printf("the child is over!\n"); }}
#include "ptrace.h"int i;void main(){ sleep(20); printf("the child is start!\n"); i=10; printf("child5:i=%d\n",i);}
1、編譯兩個源檔案
2、在一個終端運行child5.o
3、在另一個終端運行list11.o(也可以在同一個終端上)
運行結果如下