c - 使用 ptrace 从结构中检索信息

标签 c struct ptrace

在这里,我解释一下我的问题,我是 ptrace 函数的初学者,我希望成功恢复结构的硬信息。 例如,使用此命令,我将有 strace -e trace = fstat ls 一行: fstat (3, {st_mode = ..., st_size = ...} 我想成功检索结构(st_mode)和(st_size)的内容。 我尝试了这个但没有成功:

int buffer(unsigned long long addr, pid_t child, size_t size, void *buffer)
{
    size_t byte = 0;
    size_t data;
    unsigned long tmp;

    while (byte < size) {
        tmp = ptrace(PTRACE_PEEKDATA, child, addr + byte);
        if ((size - byte) / sizeof(tmp))
            data = sizeof(tmp);
        else
          data = size % sizeof(tmp);
        memcpy((void *)(buffer + byte), &tmp, data);
        byte += data;
    }
}

并在参数中:

struct stat stat_i;
buffer(addr, pid, sizeof(stat_i), &stat_i);
printf("%lu", stat_i.st_size); -> fake value :/

谢谢!

最佳答案

来自man page ,

PTRACE_PEEKTEXT, PTRACE_PEEKDATA
      Read a word at the address addr in the tracee's memory,
      returning the word as the result of the ptrace() call.  Linux
      does not have separate text and data address spaces, so these
      two requests are currently equivalent.  (data is ignored; but
      see NOTES.)

因此您必须了解 tmp 将保存读取的实际值。

您的检查错误 - 您应该在调用之前设置errno = 0,然后检查它是否已更改。如果有 - 你就有错误了。如果没有 - 您可以放心 tmp 拥有来自远程进程的单词。

尝试这样的事情:

int buffer(unsigned long long addr, pid_t child, size_t size, void *buffer)
{
    size_t byte = 0;
    size_t data;
    unsigned long tmp;

    // support for word aligned sizes only
    if (size % sizeof(long) != 0)
        return -1;

    long * buffer_int = (long*) buffer;

    while (byte < size) {
        errno = 0;
        tmp = ptrace(PTRACE_PEEKDATA, child, addr + byte);
        if (errno)
            return -1;
        buffer_int[byte / sizeof(long)] = tmp;

        byte += sizeof(long);
    }
}

关于c - 使用 ptrace 从结构中检索信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49657361/

相关文章:

c++ - 在构建期间捕获所有编译器调用和命令行参数

c - 初始化指针时,字符串文字与 char 数组

c - 函数原型(prototype)是否转换您在 C 中的实际参数?

c - Linux termios 非规范 read() 超时不起作用

c - sizeof 运算符返回奇怪的结果

c - 如何在不使其成为全局的情况下共享硬件抽象结构

C:赋值、二元运算等的性能

ios - 类变量值未更新

c - ptrace在用户级还是内核级工作?

c - 使用 ptrace 停止或杀死进程中的线程?