我正在尝试从 Linux 上的纯 Python 代码调用内联机器代码。为此,我将代码嵌入到字节文字中
code = b"\x55\x89\xe5\x5d\xc3"
然后打电话mprotect() http://www.kernel.org/doc/man-pages/online/pages/man2/mprotect.2.html via ctypes
允许执行包含代码的页面。最后,我尝试使用ctypes
调用代码。这是我的完整代码:
#!/usr/bin/python3
from ctypes import *
# Initialise ctypes prototype for mprotect().
# According to the manpage:
# int mprotect(const void *addr, size_t len, int prot);
libc = CDLL("libc.so.6")
mprotect = libc.mprotect
mprotect.restype = c_int
mprotect.argtypes = [c_void_p, c_size_t, c_int]
# PROT_xxxx constants
# Output of gcc -E -dM -x c /usr/include/sys/mman.h | grep PROT_
# #define PROT_NONE 0x0
# #define PROT_READ 0x1
# #define PROT_WRITE 0x2
# #define PROT_EXEC 0x4
# #define PROT_GROWSDOWN 0x01000000
# #define PROT_GROWSUP 0x02000000
PROT_NONE = 0x0
PROT_READ = 0x1
PROT_WRITE = 0x2
PROT_EXEC = 0x4
# Machine code of an empty C function, generated with gcc
# Disassembly:
# 55 push %ebp
# 89 e5 mov %esp,%ebp
# 5d pop %ebp
# c3 ret
code = b"\x55\x89\xe5\x5d\xc3"
# Get the address of the code
addr = addressof(c_char_p(code))
# Get the start of the page containing the code and set the permissions
pagesize = 0x1000
pagestart = addr & ~(pagesize - 1)
if mprotect(pagestart, pagesize, PROT_READ|PROT_WRITE|PROT_EXEC):
raise RuntimeError("Failed to set permissions using mprotect()")
# Generate ctypes function object from code
functype = CFUNCTYPE(None)
f = functype(addr)
# Call the function
print("Calling f()")
f()
该代码在最后一行出现段错误。
为什么我会出现段错误?这mprotect()
调用表示成功,因此应该允许我执行页面中的代码。
有办法修复代码吗?我真的可以在当前进程中用纯 Python 调用机器代码吗?
(一些进一步的评论:我并不是真的想实现一个目标——我只是想了解事情是如何运作的。我还尝试使用2*pagesize
代替pagesize
in the mprotect()
调用以排除我的 5 字节代码落在页面边界上的情况——无论如何,这应该是不可能的。我使用Python 3.1.3进行测试。我的机器是 32 位 i386 机器。我知道一种可能的解决方案是从纯 Python 代码创建一个 ELF 共享对象并通过ctypes
,但这不是我正在寻找的答案:)
Edit:以下 C 版本的代码工作正常:
#include <sys/mman.h>
char code[] = "\x55\x89\xe5\x5d\xc3";
const int pagesize = 0x1000;
int main()
{
mprotect((int)code & ~(pagesize - 1), pagesize,
PROT_READ|PROT_WRITE|PROT_EXEC);
((void(*)())code)();
}
Edit 2: 我发现我的代码有错误。线路
addr = addressof(c_char_p(code))
首先创建一个ctypeschar*
指向开头的bytes
实例code
. addressof()
应用于此指针不会返回此指针指向的地址,而是返回指针本身的地址。
我设法找出实际获取代码开头地址的最简单方法是
addr = addressof(cast(c_char_p(code), POINTER(c_char)).contents)
如果有更简单的解决方案的提示,我们将不胜感激:)
修复这一行使得上面的代码“工作”(意味着它什么也不做,而不是出现段错误......)。