Skip to content

gh-148573: correct allocation of complex types in the ctypes#148579

Open
skirpichev wants to merge 4 commits intopython:mainfrom
skirpichev:fix-148573
Open

gh-148573: correct allocation of complex types in the ctypes#148579
skirpichev wants to merge 4 commits intopython:mainfrom
skirpichev:fix-148573

Conversation

@skirpichev
Copy link
Copy Markdown
Member

@skirpichev skirpichev commented Apr 14, 2026

Old code relying on implementation detail, that elements[1] for the FFI_TYPE_COMPLEX was never read.

But this type actually shares same assumption as the FFI_TYPE_STRUCT: the elements field is a NULL-terminated array of pointers to ffi_type objects. So far for primitive types - only complex types have this struct field as non-NULL (two element array).

Old code relying on implementation detail, that elements[1] for
the FFI_TYPE_COMPLEX was never read.

But this type actually shares same assumption as the FFI_TYPE_STRUCT:
the elements field is a NULL-terminated array of pointers to ffi_type
objects.  So far for primitive types - only complex types have this
struct field as non-NULL (two element array).
Comment thread Modules/_ctypes/_ctypes.c Outdated
Co-authored-by: sunmy2019 <59365878+sunmy2019@users.noreply.github.com>
@skirpichev skirpichev requested a review from sunmy2019 April 15, 2026 10:11
@sunmy2019
Copy link
Copy Markdown
Member

Should we add news for this?

@skirpichev
Copy link
Copy Markdown
Member Author

Should we add news for this?

I don't think it's a user-visible change.

Comment thread Modules/_ctypes/_ctypes.c
Comment on lines +2370 to +2372
/* From primitive types - only complex types have the elements
struct field as non-NULL (two element array). */
assert(fmt->pffi_type->type == FFI_TYPE_COMPLEX);
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks! There's one more check we can do here.

Suggested change
/* From primitive types - only complex types have the elements
struct field as non-NULL (two element array). */
assert(fmt->pffi_type->type == FFI_TYPE_COMPLEX);
/* From primitive types - only complex types have the elements struct
field as non-NULL (two element array, including final NULL). */
assert(fmt->pffi_type->type == FFI_TYPE_COMPLEX);
assert(fmt->pffi_type->elements[1] == NULL);

Copy link
Copy Markdown
Member

@sunmy2019 sunmy2019 Apr 16, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If that's needed, how about using the same check in libffi, i.e.

a->elements != NULL && a->elements[0] != NULL && a->elements[1] == NULL

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants