8000 bpo-42143: Ensure PyFunction_NewWithQualName() can't fail after creat… · python/cpython@3505261 · GitHub
[go: up one dir, main page]

Skip to content

Commit 3505261

Browse files
authored
bpo-42143: Ensure PyFunction_NewWithQualName() can't fail after creating the func object (GH-22953)
func_dealloc() does not handle partially-created objects. Best not to give it any.
1 parent df59273 commit 3505261

File tree

2 files changed

+18
-13
lines changed

2 files changed

+18
-13
lines changed
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix handling of errors during creation of ``PyFunctionObject``, which resulted
2+
in operations on uninitialized memory. Patch by Yonatan Goldschmidt.

Objects/funcobject.c

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,23 @@ PyFunction_NewWithQualName(PyObject *code, PyObject *globals, PyObject *qualname
1919
return NULL;
2020
}
2121

22+
/* __module__: If module name is in globals, use it.
23+
Otherwise, use None. */
24+
module = PyDict_GetItemWithError(globals, __name__);
25+
if (module) {
26+
Py_INCREF(module);
27+
}
28+
else if (PyErr_Occurred()) {
29+
return NULL;
30+
}
31+
2232
op = PyObject_GC_New(PyFunctionObject, &PyFunction_Type);
23-
if (op == NULL)
33+
if (op == NULL) {
34+
Py_XDECREF(module);
2435
return NULL;
36+
}
37+
/* Note: No failures from this point on, since func_dealloc() does not
38+
expect a partially-created object. */
2539

2640
op->func_weakreflist = NULL;
2741
Py_INCREF(code);
@@ -34,6 +48,7 @@ PyFunction_NewWithQualName(PyObject *code, PyObject *globals, PyObject *qualname
3448
op->func_kwdefaults = NULL; /* No keyword only defaults */
3549
op->func_closure = NULL;
3650
op->vectorcall = _PyFunction_Vectorcall;
51+
op->func_module = module;
3752

3853
consts = ((PyCodeObject *)code)->co_consts;
3954
if (PyTuple_Size(consts) >= 1) {
@@ -47,20 +62,8 @@ PyFunction_NewWithQualName(PyObject *code, PyObject *globals, PyObject *qualname
4762
op->func_doc = doc;
4863

4964
op->func_dict = NULL;
50-
op->func_module = NULL;
5165
op->func_annotations = NULL;
5266

53-
/* __module__: If module name is in globals, use it.
54-
Otherwise, use None. */
55-
module = PyDict_GetItemWithError(globals, __name__);
56-
if (module) {
57-
Py_INCREF(module);
58-
op->func_module = module;
59-
}
60-
else if (PyErr_Occurred()) {
61-
Py_DECREF(op);
62-
return NULL;
63-
}
6467
if (qualname)
6568
op->func_qualname = qualname;
6669
else

0 commit comments

Comments
 (0)
0