[3.13] gh-130163: Fix crashes related to PySys_GetObject() (GH-130503) (GH-130556)

The use of PySys_GetObject() and _PySys_GetAttr(), which return a borrowed
reference, has been replaced by using one of the following functions, which
return a strong reference and distinguish a missing attribute from an error:
_PySys_GetOptionalAttr(), _PySys_GetOptionalAttrString(),
_PySys_GetRequiredAttr(), and _PySys_GetRequiredAttrString().
(cherry picked from commit 0ef4ffeefd)
This commit is contained in:
Serhiy Storchaka 2025-02-26 00:50:26 +02:00 committed by GitHub
parent b0d3f49195
commit 7c1b76fce8
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
23 changed files with 505 additions and 180 deletions

View file

@ -10,6 +10,7 @@
#include "pycore_pymem.h" // _PyMem_SetDefaultAllocator()
#include "pycore_pystate.h" // _PyThreadState_GET()
#include "pycore_pystats.h" // _Py_StatsOn()
#include "pycore_sysmodule.h" // _PySys_GetOptionalAttrString()
#include "osdefs.h" // DELIM
@ -3232,10 +3233,13 @@ _Py_DumpPathConfig(PyThreadState *tstate)
#define DUMP_SYS(NAME) \
do { \
obj = PySys_GetObject(#NAME); \
PySys_FormatStderr(" sys.%s = ", #NAME); \
if (_PySys_GetOptionalAttrString(#NAME, &obj) < 0) { \
PyErr_Clear(); \
} \
if (obj != NULL) { \
PySys_FormatStderr("%A", obj); \
Py_DECREF(obj); \
} \
else { \
PySys_WriteStderr("(not set)"); \
@ -3253,7 +3257,8 @@ _Py_DumpPathConfig(PyThreadState *tstate)
DUMP_SYS(exec_prefix);
#undef DUMP_SYS
PyObject *sys_path = PySys_GetObject("path"); /* borrowed reference */
PyObject *sys_path;
(void) _PySys_GetOptionalAttrString("path", &sys_path);
if (sys_path != NULL && PyList_Check(sys_path)) {
PySys_WriteStderr(" sys.path = [\n");
Py_ssize_t len = PyList_GET_SIZE(sys_path);
@ -3263,6 +3268,7 @@ _Py_DumpPathConfig(PyThreadState *tstate)
}
PySys_WriteStderr(" ]\n");
}
Py_XDECREF(sys_path);
_PyErr_SetRaisedException(tstate, exc);
}