Skip to content

Commit 6d97e52

Browse files
gh-83004: Harden winsound init (#103385)
1 parent f65fdbb commit 6d97e52

File tree

1 file changed

+14
-16
lines changed

1 file changed

+14
-16
lines changed

PC/winsound.c

+14-16
Original file line numberDiff line numberDiff line change
@@ -202,19 +202,11 @@ static struct PyMethodDef sound_methods[] =
202202
{NULL, NULL}
203203
};
204204

205-
static void
206-
add_define(PyObject *dict, const char *key, long value)
207-
{
208-
PyObject *k = PyUnicode_FromString(key);
209-
PyObject *v = PyLong_FromLong(value);
210-
if (v && k) {
211-
PyDict_SetItem(dict, k, v);
212-
}
213-
Py_XDECREF(k);
214-
Py_XDECREF(v);
215-
}
216-
217-
#define ADD_DEFINE(tok) add_define(dict,#tok,tok)
205+
#define ADD_DEFINE(CONST) do { \
206+
if (PyModule_AddIntConstant(module, #CONST, CONST) < 0) { \
207+
goto error; \
208+
} \
209+
} while (0)
218210

219211

220212
static struct PyModuleDef winsoundmodule = {
@@ -232,11 +224,10 @@ static struct PyModuleDef winsoundmodule = {
232224
PyMODINIT_FUNC
233225
PyInit_winsound(void)
234226
{
235-
PyObject *dict;
236227
PyObject *module = PyModule_Create(&winsoundmodule);
237-
if (module == NULL)
228+
if (module == NULL) {
238229
return NULL;
239-
dict = PyModule_GetDict(module);
230+
}
240231

241232
ADD_DEFINE(SND_ASYNC);
242233
ADD_DEFINE(SND_NODEFAULT);
@@ -254,5 +245,12 @@ PyInit_winsound(void)
254245
ADD_DEFINE(MB_ICONEXCLAMATION);
255246
ADD_DEFINE(MB_ICONHAND);
256247
ADD_DEFINE(MB_ICONQUESTION);
248+
249+
#undef ADD_DEFINE
250+
257251
return module;
252+
253+
error:
254+
Py_DECREF(module);
255+
return NULL;
258256
}

0 commit comments

Comments
 (0)