Skip to content

Commit e612043

Browse files
Fix invalid access when reinterpret_casting a non-pybind11 PyObject* to instance* (found by Valgrind in #2746) (#2755)
1 parent 2110d2d commit e612043

File tree

1 file changed

+5
-5
lines changed

1 file changed

+5
-5
lines changed

include/pybind11/pybind11.h

+5-5
Original file line numberDiff line numberDiff line change
@@ -504,15 +504,15 @@ class cpp_function : public function {
504504

505505
auto self_value_and_holder = value_and_holder();
506506
if (overloads->is_constructor) {
507-
const auto tinfo = get_type_info((PyTypeObject *) overloads->scope.ptr());
508-
const auto pi = reinterpret_cast<instance *>(parent.ptr());
509-
self_value_and_holder = pi->get_value_and_holder(tinfo, false);
510-
511-
if (!self_value_and_holder.type || !self_value_and_holder.inst) {
507+
if (!PyObject_TypeCheck(parent.ptr(), (PyTypeObject *) overloads->scope.ptr())) {
512508
PyErr_SetString(PyExc_TypeError, "__init__(self, ...) called with invalid `self` argument");
513509
return nullptr;
514510
}
515511

512+
const auto tinfo = get_type_info((PyTypeObject *) overloads->scope.ptr());
513+
const auto pi = reinterpret_cast<instance *>(parent.ptr());
514+
self_value_and_holder = pi->get_value_and_holder(tinfo, true);
515+
516516
// If this value is already registered it must mean __init__ is invoked multiple times;
517517
// we really can't support that in C++, so just ignore the second __init__.
518518
if (self_value_and_holder.instance_registered())

0 commit comments

Comments
 (0)