Skip to content

Commit 8fea252

Browse files
committed
Issue #18520: fix reference leak in _PySys_Init()
1 parent 22da967 commit 8fea252

File tree

1 file changed

+18
-7
lines changed

1 file changed

+18
-7
lines changed

Python/sysmodule.c

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1573,15 +1573,26 @@ _PySys_Init(void)
15731573
if (m == NULL)
15741574
return NULL;
15751575
sysdict = PyModule_GetDict(m);
1576+
#define SET_SYS_FROM_STRING_BORROW(key, value) \
1577+
do { \
1578+
int res; \
1579+
PyObject *v = (value); \
1580+
if (v == NULL) \
1581+
return NULL; \
1582+
res = PyDict_SetItemString(sysdict, key, v); \
1583+
if (res < 0) { \
1584+
return NULL; \
1585+
} \
1586+
} while (0)
15761587
#define SET_SYS_FROM_STRING(key, value) \
15771588
do { \
15781589
int res; \
15791590
PyObject *v = (value); \
15801591
if (v == NULL) \
15811592
return NULL; \
15821593
res = PyDict_SetItemString(sysdict, key, v); \
1594+
Py_DECREF(v); \
15831595
if (res < 0) { \
1584-
Py_DECREF(v); \
15851596
return NULL; \
15861597
} \
15871598
} while (0)
@@ -1606,10 +1617,10 @@ _PySys_Init(void)
16061617

16071618
/* stdin/stdout/stderr are now set by pythonrun.c */
16081619

1609-
SET_SYS_FROM_STRING("__displayhook__",
1610-
PyDict_GetItemString(sysdict, "displayhook"));
1611-
SET_SYS_FROM_STRING("__excepthook__",
1612-
PyDict_GetItemString(sysdict, "excepthook"));
1620+
SET_SYS_FROM_STRING_BORROW("__displayhook__",
1621+
PyDict_GetItemString(sysdict, "displayhook"));
1622+
SET_SYS_FROM_STRING_BORROW("__excepthook__",
1623+
PyDict_GetItemString(sysdict, "excepthook"));
16131624
SET_SYS_FROM_STRING("version",
16141625
PyUnicode_FromString(Py_GetVersion()));
16151626
SET_SYS_FROM_STRING("hexversion",
@@ -1679,9 +1690,9 @@ _PySys_Init(void)
16791690
else {
16801691
Py_INCREF(warnoptions);
16811692
}
1682-
SET_SYS_FROM_STRING("warnoptions", warnoptions);
1693+
SET_SYS_FROM_STRING_BORROW("warnoptions", warnoptions);
16831694

1684-
SET_SYS_FROM_STRING("_xoptions", get_xoptions());
1695+
SET_SYS_FROM_STRING_BORROW("_xoptions", get_xoptions());
16851696

16861697
/* version_info */
16871698
if (VersionInfoType.tp_name == NULL) {

0 commit comments

Comments
 (0)