Thanks to visit codestin.com
Credit goes to github.com

Skip to content

gh-108240: _PyCapsule_SetTraverse() rejects NULL callbacks #108417

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 1 commit into from
Aug 24, 2023
Merged
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
37 changes: 22 additions & 15 deletions Objects/capsule.c
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
/* Wrap void * pointers to be passed between C modules */

#include "Python.h"
#include "pycore_gc.h" // _PyObject_GC_IS_TRACKED()
#include "pycore_object.h" // _PyObject_GC_TRACK()


/* Internal structure of PyCapsule */
typedef struct {
Expand Down Expand Up @@ -71,7 +74,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 +207,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 +315,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