Skip to content

Commit c3cd3d1

Browse files
gh-83004: Harden msvcrt init (#103383)
1 parent 8b1b171 commit c3cd3d1

File tree

1 file changed

+29
-12
lines changed

1 file changed

+29
-12
lines changed

PC/msvcrtmodule.c

+29-12
Original file line numberDiff line numberDiff line change
@@ -609,11 +609,11 @@ PyMODINIT_FUNC
609609
PyInit_msvcrt(void)
610610
{
611611
int st;
612-
PyObject *d, *version;
613612
PyObject *m = PyModule_Create(&msvcrtmodule);
614-
if (m == NULL)
613+
if (m == NULL) {
615614
return NULL;
616-
d = PyModule_GetDict(m);
615+
}
616+
PyObject *d = PyModule_GetDict(m); // Borrowed ref.
617617

618618
/* constants for the locking() function's mode argument */
619619
insertint(d, "LK_LOCK", _LK_LOCK);
@@ -644,30 +644,47 @@ PyInit_msvcrt(void)
644644
#ifdef _VC_ASSEMBLY_PUBLICKEYTOKEN
645645
st = PyModule_AddStringConstant(m, "VC_ASSEMBLY_PUBLICKEYTOKEN",
646646
_VC_ASSEMBLY_PUBLICKEYTOKEN);
647-
if (st < 0) return NULL;
647+
if (st < 0) {
648+
goto error;
649+
}
648650
#endif
649651
#ifdef _CRT_ASSEMBLY_VERSION
650652
st = PyModule_AddStringConstant(m, "CRT_ASSEMBLY_VERSION",
651653
_CRT_ASSEMBLY_VERSION);
652-
if (st < 0) return NULL;
654+
if (st < 0) {
655+
goto error;
656+
}
653657
#endif
654658
#ifdef __LIBRARIES_ASSEMBLY_NAME_PREFIX
655659
st = PyModule_AddStringConstant(m, "LIBRARIES_ASSEMBLY_NAME_PREFIX",
656660
__LIBRARIES_ASSEMBLY_NAME_PREFIX);
657-
if (st < 0) return NULL;
661+
if (st < 0) {
662+
goto error;
663+
}
658664
#endif
659665

660666
/* constants for the 2010 crt versions */
661667
#if defined(_VC_CRT_MAJOR_VERSION) && defined (_VC_CRT_MINOR_VERSION) && defined(_VC_CRT_BUILD_VERSION) && defined(_VC_CRT_RBUILD_VERSION)
662-
version = PyUnicode_FromFormat("%d.%d.%d.%d", _VC_CRT_MAJOR_VERSION,
663-
_VC_CRT_MINOR_VERSION,
664-
_VC_CRT_BUILD_VERSION,
665-
_VC_CRT_RBUILD_VERSION);
666-
st = PyModule_AddObject(m, "CRT_ASSEMBLY_VERSION", version);
667-
if (st < 0) return NULL;
668+
PyObject *version = PyUnicode_FromFormat("%d.%d.%d.%d",
669+
_VC_CRT_MAJOR_VERSION,
670+
_VC_CRT_MINOR_VERSION,
671+
_VC_CRT_BUILD_VERSION,
672+
_VC_CRT_RBUILD_VERSION);
673+
if (version == NULL) {
674+
goto error;
675+
}
676+
st = PyModule_AddObjectRef(m, "CRT_ASSEMBLY_VERSION", version);
677+
Py_DECREF(version);
678+
if (st < 0) {
679+
goto error;
680+
}
668681
#endif
669682
/* make compiler warning quiet if st is unused */
670683
(void)st;
671684

672685
return m;
686+
687+
error:
688+
Py_DECREF(m);
689+
return NULL;
673690
}

0 commit comments

Comments
 (0)