Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Comment thread
godlygeek marked this conversation as resolved.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix an invalid pointer dereference that could occur when calling :c:func:`PyObject_Realloc` with a NULL pointer in :term:`free-threaded builds <free-threaded build>` or with :envvar:`PYTHONMALLOC` set to ``mimalloc``.
47 changes: 47 additions & 0 deletions Modules/_testcapi/mem.c
Original file line number Diff line number Diff line change
Expand Up @@ -345,6 +345,53 @@ test_setallocators(PyMemAllocatorDomain domain)
goto fail;
}

/* realloc(NULL, size) should behave like malloc(size) */
size_t size3 = 100;
void *ptr3;
switch(domain) {
case PYMEM_DOMAIN_RAW:
ptr3 = PyMem_RawRealloc(NULL, size3);
break;
case PYMEM_DOMAIN_MEM:
ptr3 = PyMem_Realloc(NULL, size3);
break;
case PYMEM_DOMAIN_OBJ:
ptr3 = PyObject_Realloc(NULL, size3);
break;
default:
ptr3 = NULL;
break;
}

CHECK_CTX("realloc(NULL, size)");
if (ptr3 == NULL) {
error_msg = "realloc(NULL, size) failed";
goto fail;
}
if (hook.realloc_ptr != NULL || hook.realloc_new_size != size3) {
error_msg = "realloc(NULL, size) invalid parameters";
goto fail;
}

hook.free_ptr = NULL;
switch(domain) {
case PYMEM_DOMAIN_RAW:
PyMem_RawFree(ptr3);
break;
case PYMEM_DOMAIN_MEM:
PyMem_Free(ptr3);
break;
case PYMEM_DOMAIN_OBJ:
PyObject_Free(ptr3);
break;
}

CHECK_CTX("realloc(NULL, size) free");
if (hook.free_ptr != ptr3) {
error_msg = "unexpected pointer passed to free";
goto fail;
}

res = Py_NewRef(Py_None);
goto finally;

Expand Down
5 changes: 4 additions & 1 deletion Objects/obmalloc.c
Original file line number Diff line number Diff line change
Expand Up @@ -363,7 +363,10 @@ _PyObject_MiRealloc(void *ctx, void *ptr, size_t nbytes)
_mi_memcpy((char*)newp + offset, (char*)ptr + offset, copy_size - offset);
}
else {
_mi_memcpy(newp, ptr, copy_size);
// memcpy(dst, NULL, 0) is undefined behavior. See gh-151297.
if mi_likely(ptr) {
_mi_memcpy(newp, ptr, copy_size);
Comment thread
godlygeek marked this conversation as resolved.
}
}
mi_free(ptr);
return newp;
Expand Down
Loading