From ecef2d99a5c1711753e1cd0ea6b3840b54e104c7 Mon Sep 17 00:00:00 2001 From: "Erlend E. Aasland" Date: Sat, 8 Apr 2023 22:15:26 +0200 Subject: [PATCH 1/3] gh-83004: Harden winsound init --- PC/winsound.c | 20 +++++--------------- 1 file changed, 5 insertions(+), 15 deletions(-) diff --git a/PC/winsound.c b/PC/winsound.c index 65025ddc5e1f51..e6e0d96368f058 100644 --- a/PC/winsound.c +++ b/PC/winsound.c @@ -202,19 +202,11 @@ static struct PyMethodDef sound_methods[] = {NULL, NULL} }; -static void -add_define(PyObject *dict, const char *key, long value) -{ - PyObject *k = PyUnicode_FromString(key); - PyObject *v = PyLong_FromLong(value); - if (v && k) { - PyDict_SetItem(dict, k, v); - } - Py_XDECREF(k); - Py_XDECREF(v); -} - -#define ADD_DEFINE(tok) add_define(dict,#tok,tok) +#define ADD_DEFINE(CONST) do { \ + if (PyModule_AddIntConstant(module, #CONST, CONST) < 0) { \ + return NULL; \ + } \ +} while (0) static struct PyModuleDef winsoundmodule = { @@ -232,11 +224,9 @@ static struct PyModuleDef winsoundmodule = { PyMODINIT_FUNC PyInit_winsound(void) { - PyObject *dict; PyObject *module = PyModule_Create(&winsoundmodule); if (module == NULL) return NULL; - dict = PyModule_GetDict(module); ADD_DEFINE(SND_ASYNC); ADD_DEFINE(SND_NODEFAULT); From aa5901e2a3af32f074c6a3c3cab89bcacc52022e Mon Sep 17 00:00:00 2001 From: "Erlend E. Aasland" Date: Sun, 9 Apr 2023 00:39:03 +0200 Subject: [PATCH 2/3] Don't leak module object on error --- PC/winsound.c | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/PC/winsound.c b/PC/winsound.c index e6e0d96368f058..18aefbab73645b 100644 --- a/PC/winsound.c +++ b/PC/winsound.c @@ -204,7 +204,7 @@ static struct PyMethodDef sound_methods[] = #define ADD_DEFINE(CONST) do { \ if (PyModule_AddIntConstant(module, #CONST, CONST) < 0) { \ - return NULL; \ + goto error; \ } \ } while (0) @@ -225,8 +225,9 @@ PyMODINIT_FUNC PyInit_winsound(void) { PyObject *module = PyModule_Create(&winsoundmodule); - if (module == NULL) + if (module == NULL) { return NULL; + } ADD_DEFINE(SND_ASYNC); ADD_DEFINE(SND_NODEFAULT); @@ -244,5 +245,10 @@ PyInit_winsound(void) ADD_DEFINE(MB_ICONEXCLAMATION); ADD_DEFINE(MB_ICONHAND); ADD_DEFINE(MB_ICONQUESTION); + return module; + +error: + Py_DECREF(module); + return NULL; } From df659472e94a0bfabbba0aeb775ba6d3b00a612f Mon Sep 17 00:00:00 2001 From: Kumar Aditya <59607654+kumaraditya303@users.noreply.github.com> Date: Sun, 9 Apr 2023 07:21:43 +0530 Subject: [PATCH 3/3] Update PC/winsound.c Co-authored-by: Erlend E. Aasland --- PC/winsound.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/PC/winsound.c b/PC/winsound.c index 18aefbab73645b..bae8e449795733 100644 --- a/PC/winsound.c +++ b/PC/winsound.c @@ -246,6 +246,8 @@ PyInit_winsound(void) ADD_DEFINE(MB_ICONHAND); ADD_DEFINE(MB_ICONQUESTION); +#undef ADD_DEFINE + return module; error: