2011-10-08 12 views
2

我想跟蹤一個使用ptrace API的小程序。我發現每次追蹤器運行時都會產生不好的結果。這是我想跟蹤短節目的拆卸:爲什麼ptrace SINGLESTEP不能正常工作?

$ objdump -d -M intel inc_reg16 
inc_reg16:  file format elf32-i386 

Disassembly of section .text: 

08048060 <.text>: 
8048060: b8 00 00 00 00   mov eax,0x0 
8048065: 66 40     inc ax 
8048067: 75 fc     jne 0x8048065 
8048069: 89 c3     mov ebx,eax 
804806b: b8 01 00 00 00   mov eax,0x1 
8048070: cd 80     int 0x80 

,這裏是示蹤劑本身的代碼:

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

int main() { 
    pid_t child; 
    child = fork(); 
    if (child == 0) { 
     ptrace(PTRACE_TRACEME, 0, NULL, NULL); 
     execv("inc_reg16", NULL); 
    } 
    else { 

     int status; 
     wait(&status); 
     struct user_regs_struct regs; 
     while (1) { 
      ptrace(PTRACE_GETREGS, child, NULL, &regs); 
      printf("eip: %x\n", (unsigned int) regs.eip); 
      ptrace(PTRACE_SINGLESTEP, child, NULL, NULL); 
      waitpid(child, &status, 0); 
      if(WIFEXITED(status)) break; 
     } 
     printf("end\n"); 
    } 
    return 0; 
} 

示蹤劑的工作是單步inc_reg16程序和登錄的地址每個遇到處理器指令。當我運行,並檢查了多少次指令「INC斧」已經遇到了,它發生了數分別不同的示蹤劑運行時間:

$ gcc ezptrace.c -Wall -o ezptrace 
$ ./ezptrace > inc_reg16.log 
$ grep '8048065' inc_reg16.log | wc -l 
65498 

第二次檢查:

$ ./ezptrace > inc_reg16.log 
$ grep '8048065' inc_reg16.log | wc -l 
65494 

問題是上面的結果應該是65536,因爲指令'inc ax'正好執行65536次。現在的問題是:在我的代碼中是否有錯誤,或者是ptrace中的一些錯誤?非常感謝您的幫助。

+0

'./ezptrace | grep 8048065 | wc -l'在我的機器上給出65536。 (順便說一句,你調用無效參數execv,它應該是像'char * argv [] = {「inc_reg16」,NULL}; execv(argv [0],argv);') – user786653

+0

這非常有趣。由於我在虛擬化環境中運行示蹤器(Debian on VirtualBox),可能會收到不好的結果嗎? – krzysiekb

+0

剛剛在32位ubuntu 11.04下運行,在qemu下運行(在Ubuntu 11.04 x86_64上託管,我運行了其他測試),而且我仍然獲得了65536。 – user786653

回答

0

eip是用戶空間中「當前指令」的地址。您需要一個ptrace(... PEEKDATA,...),即跟在ptrace(... GETREGS,...)之後,才能獲得實際的指令。另外請記住,使用ptrace(... PEEKDATA,...)總是會獲得一個機器字,實際的操作碼通常只佔用它的低16/32位。

2

我試過virtualbox和vmware下的同一個程序,似乎只有vmware有正確的結果,而virtualbox和你有同樣的問題。我使用了virtualbox 4.2.1。