Skip to content

Commit b8e03d9

Browse files
serhiy-storchakaGlyphack
authored andcommitted
pythongh-109521: Fix obscure cases handling in PyImport_GetImporter() (pythonGH-109522)
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.
1 parent d610b6b commit b8e03d9

File tree

2 files changed

+26
-5
lines changed

2 files changed

+26
-5
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: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2363,9 +2363,14 @@ get_path_importer(PyThreadState *tstate, PyObject *path_importer_cache,
23632363
PyObject *importer;
23642364
Py_ssize_t j, nhooks;
23652365

2366-
/* These conditions are the caller's responsibility: */
2367-
assert(PyList_Check(path_hooks));
2368-
assert(PyDict_Check(path_importer_cache));
2366+
if (!PyList_Check(path_hooks)) {
2367+
PyErr_SetString(PyExc_RuntimeError, "sys.path_hooks is not a list");
2368+
return NULL;
2369+
}
2370+
if (!PyDict_Check(path_importer_cache)) {
2371+
PyErr_SetString(PyExc_RuntimeError, "sys.path_importer_cache is not a dict");
2372+
return NULL;
2373+
}
23692374

23702375
nhooks = PyList_Size(path_hooks);
23712376
if (nhooks < 0)
@@ -2408,11 +2413,22 @@ PyImport_GetImporter(PyObject *path)
24082413
{
24092414
PyThreadState *tstate = _PyThreadState_GET();
24102415
PyObject *path_importer_cache = PySys_GetObject("path_importer_cache");
2416+
if (path_importer_cache == NULL) {
2417+
PyErr_SetString(PyExc_RuntimeError, "lost sys.path_importer_cache");
2418+
return NULL;
2419+
}
2420+
Py_INCREF(path_importer_cache);
24112421
PyObject *path_hooks = PySys_GetObject("path_hooks");
2412-
if (path_importer_cache == NULL || path_hooks == NULL) {
2422+
if (path_hooks == NULL) {
2423+
PyErr_SetString(PyExc_RuntimeError, "lost sys.path_hooks");
2424+
Py_DECREF(path_importer_cache);
24132425
return NULL;
24142426
}
2415-
return get_path_importer(tstate, path_importer_cache, path_hooks, path);
2427+
Py_INCREF(path_hooks);
2428+
PyObject *importer = get_path_importer(tstate, path_importer_cache, path_hooks, path);
2429+
Py_DECREF(path_hooks);
2430+
Py_DECREF(path_importer_cache);
2431+
return importer;
24162432
}
24172433

24182434

0 commit comments

Comments
 (0)