Skip to content

Commit

Permalink
pythongh-83004: Harden winreg init
Browse files Browse the repository at this point in the history
  • Loading branch information
erlend-aasland committed Apr 8, 2023
1 parent 3516704 commit 25a07f8
Showing 1 changed file with 29 additions and 18 deletions.
47 changes: 29 additions & 18 deletions PC/winreg.c
Original file line number Diff line number Diff line change
Expand Up @@ -2070,16 +2070,23 @@ insint(PyObject * d, char * name, long value)

#define ADD_INT(val) insint(d, #val, val)

static void
inskey(PyObject * d, char * name, HKEY key)
static int
inskey(PyObject *mod, char *name, HKEY key)
{
PyObject *v = PyLong_FromVoidPtr(key);
if (!v || PyDict_SetItemString(d, name, v))
PyErr_Clear();
Py_XDECREF(v);
if (v == NULL) {
return -1;
}
int rc = PyModule_AddObjectRef(name, v);
Py_DECREF(v);
return rc;
}

#define ADD_KEY(val) inskey(d, #val, val)
#define ADD_KEY(VAL) do { \
if (inskey(m, #VAL, VAL) < 0) { \
goto error; \
} \
} while (0)


static struct PyModuleDef winregmodule = {
Expand All @@ -2096,20 +2103,20 @@ static struct PyModuleDef winregmodule = {

PyMODINIT_FUNC PyInit_winreg(void)
{
PyObject *m, *d;
m = PyModule_Create(&winregmodule);
if (m == NULL)
PyObject *m = PyModule_Create(&winregmodule);
if (m == NULL) {
return NULL;
d = PyModule_GetDict(m);
}
PyHKEY_Type.tp_doc = PyHKEY_doc;
if (PyType_Ready(&PyHKEY_Type) < 0)
return NULL;
if (PyDict_SetItemString(d, "HKEYType",
(PyObject *)&PyHKEY_Type) != 0)
return NULL;
if (PyDict_SetItemString(d, "error",
PyExc_OSError) != 0)
return NULL;
if (PyType_Ready(&PyHKEY_Type) < 0) {
goto error;
}
if (PyModule_AddObjectRef(m, "HKEYType", (PyObject *)&PyHKEY_Type) < 0) {
goto error;
}
if (PyModule_AddObjectRef(m, "error", PyExc_OSError) < 0) {
goto error;
}

/* Add the relevant constants */
ADD_KEY(HKEY_CLASSES_ROOT);
Expand Down Expand Up @@ -2171,6 +2178,10 @@ PyMODINIT_FUNC PyInit_winreg(void)
ADD_INT(REG_FULL_RESOURCE_DESCRIPTOR);
ADD_INT(REG_RESOURCE_REQUIREMENTS_LIST);
return m;

error:
Py_DECREF(m);
return NULL;
}

#endif /* MS_WINDOWS_DESKTOP || MS_WINDOWS_SYSTEM || MS_WINDOWS_GAMES */

0 comments on commit 25a07f8

Please sign in to comment.