1

因此,我已经阅读了这篇文章Counting machine instructions of a process using PTRACE_SINGLESTEP,并且我知道将 testprogram 动态链接到我的 ptrace 程序将返回一个指令计数,该指令计数也计算运行时库的初始化。但是,我正在尝试为我的测试程序获取有效计数,即:

int main(){
    return 0;
}

我的 ptrace 程序首先也返回了 90k+ 个值,所以我将其更改为静态链接使用的测试程序。柜台现在少了,但仍然超过 12k。我用来计算指令的程序是:

#include <sys/ptrace.h>
#include <unistd.h>
#include <stdio.h>

int main() {
long long counter = 1;          // machine instruction counter
int wait_val;           // child's return value
int pid;                    // child's process id
int dat;    

switch (pid = fork()) {     // copy entire parent space in child
case -1:    perror("fork");
        break;

case 0:         // child process starts
        ptrace(PTRACE_TRACEME,0,NULL,NULL);     
        /* 
           must be called in order to allow the
           control over the child process and trace me (child)
           0 refers to the parent pid
        */

        execl("./returntestprog","returntestprog",NULL);    
        /* 
           executes the testprogram and causes
           the child to stop and send a signal
           to the parent, the parent can now
           switch to PTRACE_SINGLESTEP
        */
        break;
        // child process ends
default:    // parent process starts
        wait(&wait_val);                
        if (ptrace(PTRACE_SINGLESTEP, pid, 0, 0) != 0)
                            perror("ptrace");
                        /* 
                            switch to singlestep tracing and 
                            release child
                            if unable call error.
                         */
                    wait(&wait_val);
                // parent waits for child to stop at next 
                // instruction (execl()) 
                while (wait_val == 1407) {
                        counter++;
                        if (ptrace(PTRACE_SINGLESTEP, pid, 0, 0) != 0)
                                perror("ptrace");
                        /* 
                            switch to singlestep tracing and 
                            release child
                            if unable call error.
                         */
                        wait(&wait_val);
                        // wait for next instruction to complete  */
                }
        /*
          continue to stop, wait and release until
          the child is finished; wait_val != 1407
          Low=0177L and High=05 (SIGTRAP)
        */
        }
    printf("Number of machine instructions : %lld\n", counter);
    return 0;
}   // end of switch

任何帮助将不胜感激,因为我不太确定它是否正常工作,或者根本不工作。一旦我开始做这件事,我想用 ptrace 进行时序分析,但首先要尝试计算执行指令的数量

谢谢!

4

1 回答 1

0

我现在有点想通了。因此,即使在静态链接您的代码时,您也会尝试阻止库动态链接到您的程序,从而也包含在您的计数中。然而,另一方面是执行你的文件,或者基本上在操作系统下调用也需要大量的指令。所以基本上,只要指令计数是恒定的并且在相同的条件下相同,您可以从原始程序中减去这个计数(例如使用 return 0 程序时),以计算实际的指令数。

于 2013-04-02T15:02:56.267 回答