]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
[3.11] gh-109521: Fix obscure cases handling in PyImport_GetImporter() (GH-109522...
authorSerhiy Storchaka <storchaka@gmail.com>
Sat, 7 Oct 2023 13:05:13 +0000 (16:05 +0300)
committerGitHub <noreply@github.com>
Sat, 7 Oct 2023 13:05:13 +0000 (16:05 +0300)
PyImport_GetImporter() now sets RuntimeError if it fails to get sys.path_hooks
or sys.path_importer_cache or they are not list and dict correspondingly.

Previously it could return NULL without setting error in obscure cases,
crash or raise SystemError if these attributes have wrong type.
(cherry picked from commit 62c7015e89cbdedb5218d4fedd45f971885f67a8)

Misc/NEWS.d/next/C API/2023-09-17-21-47-31.gh-issue-109521.JDF6i9.rst [new file with mode: 0644]
Python/import.c

diff --git a/Misc/NEWS.d/next/C API/2023-09-17-21-47-31.gh-issue-109521.JDF6i9.rst b/Misc/NEWS.d/next/C API/2023-09-17-21-47-31.gh-issue-109521.JDF6i9.rst
new file mode 100644 (file)
index 0000000..338650c
--- /dev/null
@@ -0,0 +1,5 @@
+:c:func:`PyImport_GetImporter` now sets RuntimeError if it fails to get
+:data:`sys.path_hooks` or :data:`sys.path_importer_cache` or they are not
+list and dict correspondingly. Previously it could return NULL without
+setting error in obscure cases, crash or raise SystemError if these
+attributes have wrong type.
index 38c23e02cec6a217f28da5ee374f597bf05ebb8e..39144d302193ac8bee16f0e95c7fd6820a00cd0c 100644 (file)
@@ -951,11 +951,22 @@ PyImport_GetImporter(PyObject *path)
 {
     PyThreadState *tstate = _PyThreadState_GET();
     PyObject *path_importer_cache = PySys_GetObject("path_importer_cache");
+    if (path_importer_cache == NULL) {
+        PyErr_SetString(PyExc_RuntimeError, "lost sys.path_importer_cache");
+        return NULL;
+    }
+    Py_INCREF(path_importer_cache);
     PyObject *path_hooks = PySys_GetObject("path_hooks");
-    if (path_importer_cache == NULL || path_hooks == NULL) {
+    if (path_hooks == NULL) {
+        PyErr_SetString(PyExc_RuntimeError, "lost sys.path_hooks");
+        Py_DECREF(path_importer_cache);
         return NULL;
     }
-    return get_path_importer(tstate, path_importer_cache, path_hooks, path);
+    Py_INCREF(path_hooks);
+    PyObject *importer = get_path_importer(tstate, path_importer_cache, path_hooks, path);
+    Py_DECREF(path_hooks);
+    Py_DECREF(path_importer_cache);
+    return importer;
 }
 
 #if defined(__EMSCRIPTEN__) && defined(PY_CALL_TRAMPOLINE)