Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

bpo-42143: Ensure PyFunction_NewWithQualName() can't fail after creating the func object #22953

Merged
merged 5 commits into from
Oct 29, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix handling of errors during creation of ``PyFunctionObject``, which resulted
in operations on uninitialized memory. Patch by Yonatan Goldschmidt.
29 changes: 16 additions & 13 deletions Objects/funcobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,23 @@ PyFunction_NewWithQualName(PyObject *code, PyObject *globals, PyObject *qualname
return NULL;
}

/* __module__: If module name is in globals, use it.
Otherwise, use None. */
module = PyDict_GetItemWithError(globals, __name__);
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This now runs before Py_INCREF(globals), not sure if relevant (because our caller should hold a reference to globals, right?)

Can put Py_INCREF(globals) before this call.

if (module) {
Py_INCREF(module);
}
else if (PyErr_Occurred()) {
return NULL;
}

op = PyObject_GC_New(PyFunctionObject, &PyFunction_Type);
if (op == NULL)
if (op == NULL) {
Py_XDECREF(module);
return NULL;
}
/* Note: No failures from this point on, since func_dealloc() does not
expect a partially-created object. */

op->func_weakreflist = NULL;
Py_INCREF(code);
Expand All @@ -34,6 +48,7 @@ PyFunction_NewWithQualName(PyObject *code, PyObject *globals, PyObject *qualname
op->func_kwdefaults = NULL; /* No keyword only defaults */
op->func_closure = NULL;
op->vectorcall = _PyFunction_Vectorcall;
op->func_module = module;

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

op->func_dict = NULL;
op->func_module = NULL;
op->func_annotations = NULL;

/* __module__: If module name is in globals, use it.
Otherwise, use None. */
module = PyDict_GetItemWithError(globals, __name__);
if (module) {
Py_INCREF(module);
op->func_module = module;
}
else if (PyErr_Occurred()) {
Py_DECREF(op);
return NULL;
}
if (qualname)
op->func_qualname = qualname;
else
Expand Down