Skip to content

Commit 6a33529

Browse files
[3.11] gh-109521: Fix obscure cases handling in PyImport_GetImporter() (GH-109522) (GH-109781)
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 62c7015)
1 parent 3d5aa7e commit 6a33529

File tree

2 files changed

+18
-2
lines changed

2 files changed

+18
-2
lines changed
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
:c:func:`PyImport_GetImporter` now sets RuntimeError if it fails to get
2+
:data:`sys.path_hooks` or :data:`sys.path_importer_cache` or they are not
3+
list and dict correspondingly. Previously it could return NULL without
4+
setting error in obscure cases, crash or raise SystemError if these
5+
attributes have wrong type.

Python/import.c

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -951,11 +951,22 @@ PyImport_GetImporter(PyObject *path)
951951
{
952952
PyThreadState *tstate = _PyThreadState_GET();
953953
PyObject *path_importer_cache = PySys_GetObject("path_importer_cache");
954+
if (path_importer_cache == NULL) {
955+
PyErr_SetString(PyExc_RuntimeError, "lost sys.path_importer_cache");
956+
return NULL;
957+
}
958+
Py_INCREF(path_importer_cache);
954959
PyObject *path_hooks = PySys_GetObject("path_hooks");
955-
if (path_importer_cache == NULL || path_hooks == NULL) {
960+
if (path_hooks == NULL) {
961+
PyErr_SetString(PyExc_RuntimeError, "lost sys.path_hooks");
962+
Py_DECREF(path_importer_cache);
956963
return NULL;
957964
}
958-
return get_path_importer(tstate, path_importer_cache, path_hooks, path);
965+
Py_INCREF(path_hooks);
966+
PyObject *importer = get_path_importer(tstate, path_importer_cache, path_hooks, path);
967+
Py_DECREF(path_hooks);
968+
Py_DECREF(path_importer_cache);
969+
return importer;
959970
}
960971

961972
#if defined(__EMSCRIPTEN__) && defined(PY_CALL_TRAMPOLINE)

0 commit comments

Comments
 (0)