Skip to content

Commit

Permalink
pythongh-108240: _PyCapsule_SetTraverse() rejects NULL callbacks
Browse files Browse the repository at this point in the history
  • Loading branch information
vstinner committed Aug 24, 2023
1 parent c163d7f commit 9941183
Showing 1 changed file with 19 additions and 15 deletions.
34 changes: 19 additions & 15 deletions Objects/capsule.c
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ PyCapsule_New(void *pointer, const char *name, PyCapsule_Destructor destructor)
capsule->destructor = destructor;
capsule->traverse_func = NULL;
capsule->clear_func = NULL;
// Only track the capsule if _PyCapsule_SetTraverse() is called
// Only track the object by the GC when _PyCapsule_SetTraverse() is called

return (PyObject *)capsule;
}
Expand Down Expand Up @@ -204,8 +204,14 @@ _PyCapsule_SetTraverse(PyObject *op, traverseproc traverse_func, inquiry clear_f
}
PyCapsule *capsule = (PyCapsule *)op;

if (!PyObject_GC_IsTracked(op)) {
PyObject_GC_Track(op);
if (traverse_func == NULL || clear_func == NULL) {
PyErr_SetString(PyExc_ValueError,
"_PyCapsule_SetTraverse() called with NULL callback");
return -1;
}

if (!_PyObject_GC_IS_TRACKED(op)) {
_PyObject_GC_TRACK(op);
}

capsule->traverse_func = traverse_func;
Expand Down Expand Up @@ -306,24 +312,22 @@ capsule_repr(PyObject *o)
static int
capsule_traverse(PyCapsule *capsule, visitproc visit, void *arg)
{
if (capsule->traverse_func) {
return capsule->traverse_func((PyObject*)capsule, visit, arg);
}
else {
return 0;
}
// Capsule object is only tracked by the GC
// if _PyCapsule_SetTraverse() is called
assert(capsule->traverse_func != NULL);

return capsule->traverse_func((PyObject*)capsule, visit, arg);
}


static int
capsule_clear(PyCapsule *capsule)
{
if (capsule->clear_func) {
return capsule->clear_func((PyObject*)capsule);
}
else {
return 0;
}
// Capsule object is only tracked by the GC
// if _PyCapsule_SetTraverse() is called
assert(capsule->clear_func != NULL);

return capsule->clear_func((PyObject*)capsule);
}


Expand Down

0 comments on commit 9941183

Please sign in to comment.