From 1bb6edbd867495c404eb6326eec8da3dbd51c240 Mon Sep 17 00:00:00 2001 From: Nate Kent Date: Thu, 26 Jan 2023 11:21:20 -0800 Subject: [PATCH] Check to see if object is `None` before traversing Closes #2915 When using the C API directly, the intended way to call `visitproc` is via the `Py_VISIT` macro, which checks to see that the provided pointer is not null before passing it along to `visitproc`. Because PyO3 isn't using the macro, it needs to manually check that the pointer isn't null. Without this check, calling `visit.call(&obj)` where `let obj = None;` will segfault. --- src/pyclass/gc.rs | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/src/pyclass/gc.rs b/src/pyclass/gc.rs index 8203af0789a..900027f7bfb 100644 --- a/src/pyclass/gc.rs +++ b/src/pyclass/gc.rs @@ -23,11 +23,16 @@ impl<'p> PyVisit<'p> { where T: AsPyPointer, { - let r = unsafe { (self.visit)(obj.as_ptr(), self.arg) }; - if r == 0 { - Ok(()) + let ptr = obj.as_ptr(); + if !ptr.is_null() { + let r = unsafe { (self.visit)(ptr, self.arg) }; + if r == 0 { + Ok(()) + } else { + Err(PyTraverseError(r)) + } } else { - Err(PyTraverseError(r)) + Ok(()) } }