|
13 | 13 | #include "pycore_moduleobject.h" // _PyModule_GetState() |
14 | 14 | #include "pycore_runtime.h" // _Py_ID() |
15 | 15 | #include "pycore_pystate.h" // _PyThreadState_GET() |
| 16 | +#include "pycore_sysmodule.h" // _PySys_GetRequiredAttr() |
16 | 17 | #include "structmember.h" // PyMemberDef |
17 | 18 |
|
18 | 19 | #include <stdlib.h> // strtol() |
@@ -1984,49 +1985,54 @@ whichmodule(PyObject *global, PyObject *dotted_path) |
1984 | 1985 | assert(module_name == NULL); |
1985 | 1986 |
|
1986 | 1987 | /* Fallback on walking sys.modules */ |
1987 | | - PyThreadState *tstate = _PyThreadState_GET(); |
1988 | | - modules = _PySys_GetAttr(tstate, &_Py_ID(modules)); |
| 1988 | + modules = _PySys_GetRequiredAttr(&_Py_ID(modules)); |
1989 | 1989 | if (modules == NULL) { |
1990 | | - PyErr_SetString(PyExc_RuntimeError, "unable to get sys.modules"); |
1991 | 1990 | return NULL; |
1992 | 1991 | } |
1993 | 1992 | if (PyDict_CheckExact(modules)) { |
1994 | 1993 | i = 0; |
1995 | 1994 | while (PyDict_Next(modules, &i, &module_name, &module)) { |
1996 | 1995 | if (_checkmodule(module_name, module, global, dotted_path) == 0) { |
| 1996 | + Py_DECREF(modules); |
1997 | 1997 | return Py_NewRef(module_name); |
1998 | 1998 | } |
1999 | 1999 | if (PyErr_Occurred()) { |
| 2000 | + Py_DECREF(modules); |
2000 | 2001 | return NULL; |
2001 | 2002 | } |
2002 | 2003 | } |
2003 | 2004 | } |
2004 | 2005 | else { |
2005 | 2006 | PyObject *iterator = PyObject_GetIter(modules); |
2006 | 2007 | if (iterator == NULL) { |
| 2008 | + Py_DECREF(modules); |
2007 | 2009 | return NULL; |
2008 | 2010 | } |
2009 | 2011 | while ((module_name = PyIter_Next(iterator))) { |
2010 | 2012 | module = PyObject_GetItem(modules, module_name); |
2011 | 2013 | if (module == NULL) { |
2012 | 2014 | Py_DECREF(module_name); |
2013 | 2015 | Py_DECREF(iterator); |
| 2016 | + Py_DECREF(modules); |
2014 | 2017 | return NULL; |
2015 | 2018 | } |
2016 | 2019 | if (_checkmodule(module_name, module, global, dotted_path) == 0) { |
2017 | 2020 | Py_DECREF(module); |
2018 | 2021 | Py_DECREF(iterator); |
| 2022 | + Py_DECREF(modules); |
2019 | 2023 | return module_name; |
2020 | 2024 | } |
2021 | 2025 | Py_DECREF(module); |
2022 | 2026 | Py_DECREF(module_name); |
2023 | 2027 | if (PyErr_Occurred()) { |
2024 | 2028 | Py_DECREF(iterator); |
| 2029 | + Py_DECREF(modules); |
2025 | 2030 | return NULL; |
2026 | 2031 | } |
2027 | 2032 | } |
2028 | 2033 | Py_DECREF(iterator); |
2029 | 2034 | } |
| 2035 | + Py_DECREF(modules); |
2030 | 2036 |
|
2031 | 2037 | /* If no module is found, use __main__. */ |
2032 | 2038 | module_name = &_Py_ID(__main__); |
|
0 commit comments