Skip to content

Commit d4d2c53

Browse files
[3.15] gh-159739: Preserve ctypes base metadata when cloning fails (GH-160174) (#160293)
When creating a ctypes structure subclass, cloning its layout initially copied pointers to buffers owned by the base class. If a later allocation failed, cleaning up the subclass could free those buffers, leaving the base with invalid metadata and potentially causing a crash. Detach the owned pointers until their copies have been allocated. Backport to 3.15 and 3.14. (cherry picked from commit 7c87319) Co-authored-by: Jelle Zijlstra <jelle@openai.com>
1 parent 9986943 commit d4d2c53

2 files changed

Lines changed: 6 additions & 0 deletions

File tree

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix a crash when a :mod:`ctypes` structure subclass cannot be created due
2+
to an allocation failure.

‎Modules/_ctypes/stgdict.c‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,10 @@ PyCStgInfo_clone(StgInfo *dst_info, StgInfo *src_info)
2828
ctype_free_stginfo_members(dst_info);
2929

3030
memcpy(dst_info, src_info, sizeof(StgInfo));
31+
/* Owned buffers must not be shared if a subsequent allocation fails. */
32+
dst_info->format = NULL;
33+
dst_info->shape = NULL;
34+
dst_info->ffi_type_pointer.elements = NULL;
3135
#ifdef Py_GIL_DISABLED
3236
dst_info->mutex = (PyMutex){0};
3337
#endif

0 commit comments

Comments
 (0)