]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-118746: Fix crash in frame_getlocals and _PyFrame_GetLocals (#118748)
authorTian Gao <gaogaotiantian@hotmail.com>
Wed, 8 May 2024 00:48:05 +0000 (17:48 -0700)
committerGitHub <noreply@github.com>
Wed, 8 May 2024 00:48:05 +0000 (17:48 -0700)
We don't know how to create an unoptimized frame with f_locals == NULL,
but they are seen in the wild, and this fixes the crash.

Objects/frameobject.c

index 26a04cbeea90bf7e2b757b56a5a2fe6c2e12e13c..d7fcb1925d286c77e77aa42d1d1774fe049201ba 100644 (file)
@@ -742,6 +742,15 @@ frame_getlocals(PyFrameObject *f, void *closure)
     PyCodeObject *co = _PyFrame_GetCode(f->f_frame);
 
     if (!(co->co_flags & CO_OPTIMIZED) && !_PyFrame_HasHiddenLocals(f->f_frame)) {
+        if (f->f_frame->f_locals == NULL) {
+            // We found cases when f_locals is NULL for non-optimized code.
+            // We fill the f_locals with an empty dict to avoid crash until
+            // we find the root cause.
+            f->f_frame->f_locals = PyDict_New();
+            if (f->f_frame->f_locals == NULL) {
+                return NULL;
+            }
+        }
         return Py_NewRef(f->f_frame->f_locals);
     }
 
@@ -1937,6 +1946,15 @@ _PyFrame_GetLocals(_PyInterpreterFrame *frame)
     PyCodeObject *co = _PyFrame_GetCode(frame);
 
     if (!(co->co_flags & CO_OPTIMIZED) && !_PyFrame_HasHiddenLocals(frame)) {
+        if (frame->f_locals == NULL) {
+            // We found cases when f_locals is NULL for non-optimized code.
+            // We fill the f_locals with an empty dict to avoid crash until
+            // we find the root cause.
+            frame->f_locals = PyDict_New();
+            if (frame->f_locals == NULL) {
+                return NULL;
+            }
+        }
         return Py_NewRef(frame->f_locals);
     }