python中的邪恶ctypes hack [英] Evil ctypes hack in python

查看:59
本文介绍了python中的邪恶ctypes hack的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我首先要说的是,这个问题纯粹是出于兴趣而提出的,我绝不打算在任何严肃的项目中使用如此难以置信的邪恶.(是的,这是一个问题)

I'd like to start by saying that this question is asked purely out of interest, and I by no means intend to use something so incredibly evil in any serious project. (yes, it's that kind of a question)

我一直在尝试在CPython的内部工作中汇总一些信息,据我所知,应该有可能操纵小整数的实际值,这样(对于实例)1 + 2的计算结果可能不是3.我几乎没有这种低级黑客方面的专家,而我所能实现的就是段错误.这是到目前为止我得到的:

I've been trying to piece together some information in the inner workings of CPython, and as far as I've been able to work out, it should be possible to manipulate the actual values for small ints, so that (for instance) 1 + 2 could evaluate to something other than 3. I'm hardly on expert on this kind of low-level hacking, and all i've been able to achieve is segfaults. This is what I've got so far:

import ctypes
ctypes.c_int8.from_address(id(1) + 8).value = 2

我以为这可以解决问题,但是这只会导致任何试图评估1的语句因段错误而崩溃.虽然那是一个有趣的成就,但这并不是我一直在寻找的东西.我想念什么吗?那行中的c_int8和+ 8只能在某些平台上工作吗?如果我确切知道要查找的内容,我会很高兴地进行查找,尽管我认为答案可能隐藏在CPython源代码中的某个地方.

I was under the impression that that would do the trick, but this just causes any statement that tries to evaluate 1 to blow up with a segfault. While that was an amusing achievement, that was hardly what I was looking for. Am I missing something? Could it be that the c_int8 and the + 8 in that line only work on certain platforms? I'd happily look this up if I knew exactly what to look for, though I'd imagine the answer might hide somewhere in the CPython source.

推荐答案

8 在32位平台上是正确的",其中 ob_refcnt ob_type分别是4个字节;在64位平台上,情况会有所不同.本质上,您试图将 PyObject_HEAD 移到整数对象的其余部分,因此请尝试在编译器或调试器中检查 PyObject 的大小.

8 would be "correct" on a 32-bit platform where ob_refcnt and ob_type are 4 bytes each; on a 64-bit platform this will be different. Essentially you're trying to go past PyObject_HEAD to the rest of the integer object, so try checking the size of PyObject in a compiler or debugger.

显然,这在Python 3上会有所不同,在Python 3中,只有 long 类型,因此即使小整数也是可变长度的;在这种情况下,您需要的是 PyObject_VAR_HEAD (和 PyVarObject ),而不是 PyObject_HEAD .

Obviously this will be different on Python 3, where there is only the long type so even small integers are variable-length; in that case you'll want PyObject_VAR_HEAD (and PyVarObject) instead of PyObject_HEAD.

一个很好的起点是 object.h ,也可以在

A good place to start looking at this is the documentation inside object.h, also readable in the C API reference manual at https://docs.python.org/2/c-api/structures.html, and then at intobject.h, or longintrepr.h for Python 3.

注意:更改 1 的值仍会出现段错误,但是出于不同的原因.不过,更改较大的小整数(例如 10 )的值应该是安全的.

Note: changing the value of 1 will still segfault, but for different reasons. Changing the value of a larger small integer such as 10 should be safe, though.

这篇关于python中的邪恶ctypes hack的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆