【发布时间】:2018-07-31 13:10:12
【问题描述】:
我正在尝试在 Python 3 中实现调试器。主要思想非常简单:用 ctypes 包装系统调用“process_vm_readv”,然后在其他进程上调用它。
我还创建了一个小的虚拟 C++ 程序供我使用此工具进行调试。以下是两者的来源:
调试器
#!/usr/bin/python3
import typing
import ctypes
import os
libc = ctypes.cdll.LoadLibrary("libc.so.6")
def _error_checker(result, function, arguments):
if result == -1:
errno = ctypes.get_errno()
raise OSError(errno, os.strerror(errno))
class IOBuffer(ctypes.Structure): # iovec struct
_fields_ = [("base", ctypes.c_void_p),
("size", ctypes.c_size_t)]
_read_process_memory = libc.process_vm_readv
_read_process_memory.restype = ctypes.c_ssize_t
_read_process_memory.errcheck = _error_checker
_read_process_memory.args = [ctypes.c_ulong, ctypes.POINTER(IOBuffer),
ctypes.c_ulong, ctypes.POINTER(IOBuffer),
ctypes.c_ulong, ctypes.c_ulong]
def read_process_memory(pid: int, base: int, size: int) -> typing.Tuple[int, bytes]:
buffer = (ctypes.c_char * size)()
local = IOBuffer(ctypes.addressof(buffer), size)
remote = IOBuffer(base, size)
return _read_process_memory(pid, local, 1, remote, 1, 0), buffer.raw
虚拟程序
#include <iostream>
#include <stdio.h>
using namespace std;
int main(void){
int a = 99;
int c;
while((c = getchar()) != EOF)
cout << "int a=" << a << ";\t&a=" << &a << endl;
return 0;
}
我的问题在于,每当我用我的虚拟程序的 pid 调用“read_process_memory”时,它提供给我的内存地址和数字 4(int 的大小)作为参数 - 这应该可以工作 - 包装系统调用返回 -1(错误)。发生这种情况时,errcheck 会报告该操作的 errno,它始终最终为零。 “错误成功”。由于这个无用的错误消息,我不知道如何解决这个问题。你们有什么想法可以解决这个问题吗?
【问题讨论】:
标签: python-3.x debugging system-calls ctypes