问题
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)
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
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.
回答1:
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.
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
.
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.
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.
来源:https://stackoverflow.com/questions/24060991/evil-ctypes-hack-in-python