Mercurial > cpython-lru_cache-weakref
diff Python/import.c @ 41128:45ce388ec59a legacy-trunk
Bug #742342: make Python stop segfaulting on infinitely-recursive reload()s. Fixed by patch #922167.
Will backport.
| author | Collin Winter <collinw@gmail.com> |
|---|---|
| date | Mon, 12 Mar 2007 16:11:39 +0000 |
| parents | d3a35fe13838 |
| children | 9db3e325dd88 |
line wrap: on
line diff
--- a/Python/import.c Mon Mar 12 15:57:19 2007 +0000 +++ b/Python/import.c Mon Mar 12 16:11:39 2007 +0000 @@ -340,6 +340,25 @@ return Py_None; } +PyObject * +PyImport_GetModulesReloading(void) +{ + PyInterpreterState *interp = PyThreadState_Get()->interp; + if (interp->modules_reloading == NULL) + Py_FatalError("PyImport_GetModuleDict: no modules_reloading dictionary!"); + return interp->modules_reloading; +} + +static void +imp_modules_reloading_clear (void) +{ + PyInterpreterState *interp = PyThreadState_Get()->interp; + if (interp->modules_reloading == NULL) + return; + PyDict_Clear(interp->modules_reloading); + return; +} + /* Helper for sys */ PyObject * @@ -499,6 +518,7 @@ PyDict_Clear(modules); interp->modules = NULL; Py_DECREF(modules); + Py_CLEAR(interp->modules_reloading); } @@ -2401,8 +2421,9 @@ PyObject * PyImport_ReloadModule(PyObject *m) { + PyObject *modules_reloading = PyImport_GetModulesReloading(); PyObject *modules = PyImport_GetModuleDict(); - PyObject *path = NULL, *loader = NULL; + PyObject *path = NULL, *loader = NULL, *existing_m = NULL; char *name, *subname; char buf[MAXPATHLEN+1]; struct filedescr *fdp; @@ -2423,20 +2444,30 @@ name); return NULL; } + if ((existing_m = PyDict_GetItemString(modules_reloading, name)) != NULL) { + /* Due to a recursive reload, this module is already being reloaded. */ + Py_INCREF(existing_m); + return existing_m; + } + PyDict_SetItemString(modules_reloading, name, m); + subname = strrchr(name, '.'); if (subname == NULL) subname = name; else { PyObject *parentname, *parent; parentname = PyString_FromStringAndSize(name, (subname-name)); - if (parentname == NULL) + if (parentname == NULL) { + imp_modules_reloading_clear(); return NULL; + } parent = PyDict_GetItem(modules, parentname); if (parent == NULL) { PyErr_Format(PyExc_ImportError, "reload(): parent %.200s not in sys.modules", PyString_AS_STRING(parentname)); Py_DECREF(parentname); + imp_modules_reloading_clear(); return NULL; } Py_DECREF(parentname); @@ -2451,6 +2482,7 @@ if (fdp == NULL) { Py_XDECREF(loader); + imp_modules_reloading_clear(); return NULL; } @@ -2467,6 +2499,7 @@ */ PyDict_SetItemString(modules, name, m); } + imp_modules_reloading_clear (); return newm; }
