【发布时间】:2021-02-12 05:31:19
【问题描述】:
我想使用 ptrace 跟踪程序的寄存器和指令。为了更好地理解我的代码,我将其减少到只计算“/bin/ls”的指令数量的程度。
这是我的代码(忽略不必要的包含):
#include <stdio.h>
#include <sys/ptrace.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <sys/user.h>
#include <sys/reg.h>
#include <sys/syscall.h>
int main()
{
pid_t child;
child = fork(); //create child
if(child == 0) {
ptrace(PTRACE_TRACEME, 0, NULL, NULL);
char* child_argv[] = {"/bin/ls", NULL};
execv("/bin/ls", child_argv);
}
else {
int status;
long long ins_count = 0;
while(1)
{
//stop tracing if child terminated successfully
wait(&status);
if(WIFEXITED(status))
break;
ins_count++;
ptrace(PTRACE_SINGLESTEP, child, NULL, NULL);
}
printf("\n%lld Instructions executed.\n", ins_count);
}
return 0;
}
当我运行此代码时,我得到“484252 指令已执行”,我对此表示怀疑。我搜索了一下,发现这些指令大部分来自在执行实际程序(/bin/ls)之前加载库。
如何跳过单步执行到 /bin/ls 的第一条实际指令并从那里开始计数?
【问题讨论】:
标签: c linux exec system-calls ptrace