之前写过博文《自己写调试器 软断点》,但其是基于windows 32位的环境下的,现在自己的笔记本加了内存,顺便让电脑升级到64位的ubuntu,所以就把原来的代码移植到x84_64 Linux下。
在linux中,我们需要用到ptrace 这个系统调用来实现对进程的控制。同时为了获取系统库中的函数地址,我们需要dlsym等在libdl中的相关函数帮助。
ptrace 的原型如下:
long ptrace(enum __ptrace_request request, pid_t pid,
void *addr, void *data);
我们需要用到下面的 ptrace request,由于用 Python,我们不能直接包含 <sys/ptrace.h>,所以我们就在系统中找到相应的头文件,然后将这个转换到我们的 Python 文件中。64位的 Linux 是在 /usr/include/x86_64-linux-gnu/sys/ptrace.h 中。
在<sys/ptrace.h>文件中,其 ptrace request 参数是枚举变量,而在 python 中我们无需转换成 python ctypes 库对应的类型即可使用。
''' Indicate that the process making this request should be traced.
All signals received by this process can be intercepted by its
parent and its parent can use the other `ptrace' requests. '''
PTRACE_TRACEME = 0
''' Return the word in the process's text space at address ADDR. '''
PTRACE_PEEKTEXT = 1
''' Return the word in the process's data space at address ADDR. '''
PTRACE_PEEKDATA = 2
''' Return the word in the process's user area at offset ADDR. '''
PTRACE_PEEKUSER = 3
''' Write the word DATA into the process's text space at address ADDR. '''
PTRACE_POKETEXT = 4
''' Write the word DATA into the process's data space at address ADDR. '''
PTRACE_POKEDATA = 5
''' Write the word DATA into the process's user area at offset ADDR. '''
PTRACE_POKEUSER = 6
''' Continue the process. '''
PTRACE_CONT = 7
''' Get all general purpose registers used by a processes