Skip to content

bpo-40217: Clean code in PyType_FromSpec_Alloc and add NEWS entry #19733

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

Merged
merged 2 commits into from
Apr 27, 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,5 @@
Ensure that instances of types created with
:c:func:`PyType_FromSpecWithBases` will visit its class object when
traversing references in the garbage collector (implemented as an extension
of the provided :c:member:`~PyTypeObject.tp_traverse`). Patch by Pablo
Galindo.
26 changes: 17 additions & 9 deletions Objects/typeobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -1031,25 +1031,29 @@ PyType_FromSpec_Alloc(PyTypeObject *type, Py_ssize_t nitems)
/* note that we need to add one, for the sentinel and space for the
provided tp-traverse: See bpo-40217 for more details */

if (PyType_IS_GC(type))
if (PyType_IS_GC(type)) {
obj = _PyObject_GC_Malloc(size);
else
}
else {
obj = (PyObject *)PyObject_MALLOC(size);
}

if (obj == NULL)
if (obj == NULL) {
return PyErr_NoMemory();

obj = obj;
Copy link
Member

Choose a reason for hiding this comment

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

Would you mind to keep this instruction? I love it :-D (I'm kidding you, please remove it!)

Copy link
Member Author

Choose a reason for hiding this comment

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

Maybe we should add some volatile 😉

}

memset(obj, '\0', size);

if (type->tp_itemsize == 0)
if (type->tp_itemsize == 0) {
(void)PyObject_INIT(obj, type);
else
}
else {
(void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
}

if (PyType_IS_GC(type))
if (PyType_IS_GC(type)) {
_PyObject_GC_TRACK(obj);
}
return obj;
}

Expand Down Expand Up @@ -3066,7 +3070,11 @@ PyType_FromSpecWithBases(PyType_Spec *spec, PyObject *bases)
*
* We store the user-provided traverse function at the end of the type
* (we have allocated space for it) so we can call it from our
* PyType_FromSpec_tp_traverse wrapper. */
* PyType_FromSpec_tp_traverse wrapper.
*
* Check bpo-40217 for more information and rationale about this issue.
*
* */

type->tp_traverse = PyType_FromSpec_tp_traverse;
size_t _offset = _PyObject_VAR_SIZE(&PyType_Type, nmembers+1);
Expand Down