[issue26628] Segfault in cffi with ctypes.union argument

Thomas report at bugs.python.org
Wed Mar 23 16:52:16 EDT 2016


New submission from Thomas:

Passing ctypes.Union types as arguments crashes python.

Attached is a minimal example to reproduce. Due to undefined behavior, you may have to increase the union _fields_ to reproduce. I tested with 3.5.1 and 2.7.11.

It seems that cffi treats the union as a normal struct. In classify_argument, it loops through the type->elements. The byte_offset increases for each union element until pos exceeds enum x86_64_reg_class classes[MAX_CLASSES], causing an invalid write here:

size_t pos = byte_offset / 8;
classes[i + pos] = merge_classes (subclasses[i], classes[i + pos]);

I am quite scared considering the lack of any index checks in this code. At this point I'm not yet sure whether this is a bug in ctypes or libffi.

#0  classify_argument (type=0xce41b8, classes=0x7fffffffb4e0, byte_offset=8) at Python-3.5.1/Modules/_ctypes/libffi/src/x86/ffi64.c:248
#1  0x00007ffff6bc6409 in examine_argument (type=0xce41b8, classes=0x7fffffffb4e0, in_return=false, pngpr=0x7fffffffb4dc, pnsse=0x7fffffffb4d8)
    at Python-3.5.1/Modules/_ctypes/libffi/src/x86/ffi64.c:318
#2  0x00007ffff6bc68ce in ffi_call (cif=0x7fffffffb590, fn=0x7ffff751d5a0, rvalue=0x7fffffffb660, avalue=0x7fffffffb640) at Python-3.5.1/Modules/_ctypes/libffi/src/x86/ffi64.c:462
#3  0x00007ffff6bb589e in _call_function_pointer (flags=4353, pProc=0x7ffff751d5a0, avalues=0x7fffffffb640, atypes=0x7fffffffb620, restype=0xcdd488, resmem=0x7fffffffb660, argcount=1)
    at Python-3.5.1/Modules/_ctypes/callproc.c:811
#4  0x00007ffff6bb6593 in _ctypes_callproc (pProc=0x7ffff751d5a0, argtuple=0xc8b3e8, flags=4353, argtypes=0xcb2098, restype=0xcdcd38, checker=0x0)
    at Python-3.5.1/Modules/_ctypes/callproc.c:1149
#5  0x00007ffff6baf84f in PyCFuncPtr_call (self=0xcf3708, inargs=0xc8b3e8, kwds=0x0) at Python-3.5.1/Modules/_ctypes/_ctypes.c:3869
#6  0x000000000043b66a in PyObject_Call (func=0xcf3708, arg=0xc8b3e8, kw=0x0) at ../../Python-3.5.1/Objects/abstract.c:2165

----------
components: ctypes
files: unioncrash.py
messages: 262307
nosy: tilsche
priority: normal
severity: normal
status: open
title: Segfault in cffi with ctypes.union argument
type: crash
versions: Python 2.7, Python 3.5
Added file: http://bugs.python.org/file42263/unioncrash.py

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue26628>
_______________________________________


More information about the Python-bugs-list mailing list