如何在x86-64上使用ptrace?

时间:2011-09-14 14:48:31

标签: c linux x86-64 ptrace

我正在关注教程here,并对x86-64稍作修改(基本上将eax替换为rax等)以便编译:

#include <sys/ptrace.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <sys/user.h>
#include <sys/reg.h>
#include <unistd.h>


int main()
{   pid_t child;
    long orig_eax;
    child = fork();
    if(child == 0) {
        ptrace(PTRACE_TRACEME, 0, NULL, NULL);
        execl("/bin/ls", "ls", NULL);
    }
    else {
        wait(NULL);
        orig_eax = ptrace(PTRACE_PEEKUSER,
                          child, 4 * ORIG_RAX,
                          NULL);
        printf("The child made a "
               "system call %ld\n", orig_eax);
        ptrace(PTRACE_CONT, child, NULL, NULL);
    }
    return 0;
}

但它实际上并没有按预期工作,它总是说:

The child made a system call -1

代码中有什么问题?

2 个答案:

答案 0 :(得分:6)

ptrace使用errno EIO返回-1,因为您尝试读取的内容未正确对齐。取自ptrace手册页:

   PTRACE_PEEKUSER
          Reads a word at offset addr in  the  child's  USER  area,  which
          holds the registers and other information about the process (see
          <sys/user.h>).  The word  is  returned  as  the  result  of  the
          ptrace()  call.   Typically  the  offset  must  be word-aligned,
          though this might vary by architecture.  See  NOTES.   (data  is
          ignored.)

在我的64位系统中,4 * ORIG_RAX不是8字节对齐的。尝试使用0或8等值,它应该可以工作。

答案 1 :(得分:6)

在64位= 8 * ORIG_RAX

8 = sizeof(长)