Skip to content

Commit ab955f1

Browse files
authored
Fix refcount bug involving trampoline functions with PyObject * return type. (#5156)
* Transfer diff from pybind11k fork as-is. New tests are still missing. * Add `PYBIND11_WARNING_DISABLE_MSVC(4127)` into `PYBIND11_OVERRIDE_IMPL` macro. * Add test_trampoline_with_pyobject_ptr_return() * Resolve clang-tidy error: use auto when initializing with a template cast to avoid duplicating the type name [modernize-use-auto,-warnings-as-errors] * Disabled checking refcount when building with PyPy. * Clang 3.6, 3.7, 3.9 compatibility. ``` /__w/pybind11/pybind11/tests/test_type_caster_pyobject_ptr.cpp:23:13: error: definition of implicit copy constructor for 'WithPyObjectPtrReturn' is deprecated because it has a user-declared destructor [-Werror,-Wdeprecated] virtual ~WithPyObjectPtrReturn() = default; ^ ``` * Minor clean-up of production code changes. * Add missing `override` (to resolve clang-tidy error). * Move PYBIND11_WARNING_POP for a better clang-format outcome.
1 parent 35ff42b commit ab955f1

File tree

4 files changed

+73
-5
lines changed

4 files changed

+73
-5
lines changed

include/pybind11/cast.h

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1339,13 +1339,24 @@ enable_if_t<!cast_is_temporary_value_reference<T>::value, T> cast_ref(object &&,
13391339
// static_assert, even though if it's in dead code, so we provide a "trampoline" to pybind11::cast
13401340
// that only does anything in cases where pybind11::cast is valid.
13411341
template <typename T>
1342-
enable_if_t<cast_is_temporary_value_reference<T>::value, T> cast_safe(object &&) {
1342+
enable_if_t<cast_is_temporary_value_reference<T>::value
1343+
&& !detail::is_same_ignoring_cvref<T, PyObject *>::value,
1344+
T>
1345+
cast_safe(object &&) {
13431346
pybind11_fail("Internal error: cast_safe fallback invoked");
13441347
}
13451348
template <typename T>
13461349
enable_if_t<std::is_void<T>::value, void> cast_safe(object &&) {}
13471350
template <typename T>
1348-
enable_if_t<detail::none_of<cast_is_temporary_value_reference<T>, std::is_void<T>>::value, T>
1351+
enable_if_t<detail::is_same_ignoring_cvref<T, PyObject *>::value, PyObject *>
1352+
cast_safe(object &&o) {
1353+
return o.release().ptr();
1354+
}
1355+
template <typename T>
1356+
enable_if_t<detail::none_of<cast_is_temporary_value_reference<T>,
1357+
detail::is_same_ignoring_cvref<T, PyObject *>,
1358+
std::is_void<T>>::value,
1359+
T>
13491360
cast_safe(object &&o) {
13501361
return pybind11::cast<T>(std::move(o));
13511362
}

include/pybind11/pybind11.h

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2868,10 +2868,14 @@ function get_override(const T *this_ptr, const char *name) {
28682868
= pybind11::get_override(static_cast<const cname *>(this), name); \
28692869
if (override) { \
28702870
auto o = override(__VA_ARGS__); \
2871-
if (pybind11::detail::cast_is_temporary_value_reference<ret_type>::value) { \
2871+
PYBIND11_WARNING_PUSH \
2872+
PYBIND11_WARNING_DISABLE_MSVC(4127) \
2873+
if (pybind11::detail::cast_is_temporary_value_reference<ret_type>::value \
2874+
&& !pybind11::detail::is_same_ignoring_cvref<ret_type, PyObject *>::value) { \
28722875
static pybind11::detail::override_caster_t<ret_type> caster; \
28732876
return pybind11::detail::cast_ref<ret_type>(std::move(o), caster); \
28742877
} \
2878+
PYBIND11_WARNING_POP \
28752879
return pybind11::detail::cast_safe<ret_type>(std::move(o)); \
28762880
} \
28772881
} while (false)

tests/test_type_caster_pyobject_ptr.cpp

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,10 @@
55
#include "pybind11_tests.h"
66

77
#include <cstddef>
8+
#include <string>
89
#include <vector>
910

10-
namespace {
11+
namespace test_type_caster_pyobject_ptr {
1112

1213
std::vector<PyObject *> make_vector_pyobject_ptr(const py::object &ValueHolder) {
1314
std::vector<PyObject *> vec_obj;
@@ -18,9 +19,39 @@ std::vector<PyObject *> make_vector_pyobject_ptr(const py::object &ValueHolder)
1819
return vec_obj;
1920
}
2021

21-
} // namespace
22+
struct WithPyObjectPtrReturn {
23+
#if defined(__clang_major__) && __clang_major__ < 4
24+
WithPyObjectPtrReturn() = default;
25+
WithPyObjectPtrReturn(const WithPyObjectPtrReturn &) = default;
26+
#endif
27+
virtual ~WithPyObjectPtrReturn() = default;
28+
virtual PyObject *return_pyobject_ptr() const = 0;
29+
};
30+
31+
struct WithPyObjectPtrReturnTrampoline : WithPyObjectPtrReturn {
32+
PyObject *return_pyobject_ptr() const override {
33+
PYBIND11_OVERRIDE_PURE(PyObject *, WithPyObjectPtrReturn, return_pyobject_ptr,
34+
/* no arguments */);
35+
}
36+
};
37+
38+
std::string call_return_pyobject_ptr(const WithPyObjectPtrReturn *base_class_ptr) {
39+
PyObject *returned_obj = base_class_ptr->return_pyobject_ptr();
40+
#if !defined(PYPY_VERSION) // It is not worth the trouble doing something special for PyPy.
41+
if (Py_REFCNT(returned_obj) != 1) {
42+
py::pybind11_fail(__FILE__ ":" PYBIND11_TOSTRING(__LINE__));
43+
}
44+
#endif
45+
auto ret_val = py::repr(returned_obj).cast<std::string>();
46+
Py_DECREF(returned_obj);
47+
return ret_val;
48+
}
49+
50+
} // namespace test_type_caster_pyobject_ptr
2251

2352
TEST_SUBMODULE(type_caster_pyobject_ptr, m) {
53+
using namespace test_type_caster_pyobject_ptr;
54+
2455
m.def("cast_from_pyobject_ptr", []() {
2556
PyObject *ptr = PyLong_FromLongLong(6758L);
2657
return py::cast(ptr, py::return_value_policy::take_ownership);
@@ -127,4 +158,10 @@ TEST_SUBMODULE(type_caster_pyobject_ptr, m) {
127158
(void) py::cast(*ptr);
128159
}
129160
#endif
161+
162+
py::class_<WithPyObjectPtrReturn, WithPyObjectPtrReturnTrampoline>(m, "WithPyObjectPtrReturn")
163+
.def(py::init<>())
164+
.def("return_pyobject_ptr", &WithPyObjectPtrReturn::return_pyobject_ptr);
165+
166+
m.def("call_return_pyobject_ptr", call_return_pyobject_ptr);
130167
}

tests/test_type_caster_pyobject_ptr.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,3 +102,19 @@ def test_return_list_pyobject_ptr_reference():
102102
def test_type_caster_name_via_incompatible_function_arguments_type_error():
103103
with pytest.raises(TypeError, match=r"1\. \(arg0: object, arg1: int\) -> None"):
104104
m.pass_pyobject_ptr_and_int(ValueHolder(101), ValueHolder(202))
105+
106+
107+
def test_trampoline_with_pyobject_ptr_return():
108+
class Drvd(m.WithPyObjectPtrReturn):
109+
def return_pyobject_ptr(self):
110+
return ["11", "22", "33"]
111+
112+
# Basic health check: First make sure this works as expected.
113+
d = Drvd()
114+
assert d.return_pyobject_ptr() == ["11", "22", "33"]
115+
116+
while True:
117+
# This failed before PR #5156: AddressSanitizer: heap-use-after-free ... in Py_DECREF
118+
d_repr = m.call_return_pyobject_ptr(d)
119+
assert d_repr == repr(["11", "22", "33"])
120+
break # Comment out for manual leak checking.

0 commit comments

Comments
 (0)