https://github.com/python/cpython/commit/ab4199b493040ac10335151dfee252e35c4ebfa9
commit: ab4199b493040ac10335151dfee252e35c4ebfa9
branch: 3.14
author: Miss Islington (bot) <[email protected]>
committer: vstinner <[email protected]>
date: 2026-11-09T16:41:33+01:00
summary:

[3.14] gh-161407: Allocate audit hook entries with malloc() (GH-161409) 
(#161673)

gh-161407: Allocate audit hook entries with malloc() (GH-161409)

A hook added with PySys_AddAuditHook() before Py_Initialize() was
allocated with PyMem_RawMalloc() before the startup configuration was
applied, and freed with PyMem_RawFree() at finalization. When
PYTHONMALLOC=mimalloc, -X dev or a debug allocator changed the raw
allocator in between, the entry was freed with a different allocator
and the process crashed at exit.

Allocate and free the entries with plain malloc() and free(), which
nothing replaces at startup.
(cherry picked from commit c7fd6522bf37a362cd4a433b4d99295b9683f600)

Co-authored-by: Maik Schulze <[email protected]>

files:
A Misc/NEWS.d/next/C_API/2026-11-05-10-51-17.gh-issue-161407.rVoqaQ.rst
M Python/sysmodule.c

diff --git 
a/Misc/NEWS.d/next/C_API/2026-11-05-10-51-17.gh-issue-161407.rVoqaQ.rst 
b/Misc/NEWS.d/next/C_API/2026-11-05-10-51-17.gh-issue-161407.rVoqaQ.rst
new file mode 100644
index 000000000000000..421329930f961a7
--- /dev/null
+++ b/Misc/NEWS.d/next/C_API/2026-11-05-10-51-17.gh-issue-161407.rVoqaQ.rst
@@ -0,0 +1,3 @@
+Fix a crash at exit when an audit hook was added with 
:c:func:`PySys_AddAuditHook`
+before :c:func:`Py_Initialize` and the raw memory allocator changed during 
startup, for
+example with ``PYTHONMALLOC=mimalloc`` or in the :ref:`Python Development Mode 
<devmode>`.
diff --git a/Python/sysmodule.c b/Python/sysmodule.c
index eeb9ef2fbffd64a..ec1fc6141093f20 100644
--- a/Python/sysmodule.c
+++ b/Python/sysmodule.c
@@ -443,7 +443,7 @@ _PySys_ClearAuditHooks(PyThreadState *ts)
     runtime->audit_hooks.head = NULL;
     while (e) {
         n = e->next;
-        PyMem_RawFree(e);
+        free(e);
         e = n;
     }
 }
@@ -491,7 +491,11 @@ PySys_AddAuditHook(Py_AuditHookFunction hook, void 
*userData)
         }
     }
 
-    _Py_AuditHookEntry *e = (_Py_AuditHookEntry*)PyMem_RawMalloc(
+    /* Use malloc(), not PyMem_RawMalloc(): a hook can be added before
+       Py_Initialize(), and the entry is freed during finalization, after
+       PYTHONMALLOC may have changed the raw allocator (and, in debug builds,
+       the allocator under the debug hooks). */
+    _Py_AuditHookEntry *e = (_Py_AuditHookEntry*)malloc(
             sizeof(_Py_AuditHookEntry));
     if (!e) {
         if (tstate != NULL) {

_______________________________________________
Python-checkins mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3//lists/python-checkins.python.org
Member address: [email protected]

Reply via email to