Skip to content
Open
Show file tree
Hide file tree
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
8 changes: 6 additions & 2 deletions docs/classes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -292,8 +292,12 @@ Alternatively, we can also assign a name to the previously bound ``Pet``
.def(py::init<const std::string &>())
.def("bark", &Dog::bark);

Functionality-wise, both approaches are equivalent. Afterwards, instances will
expose fields and methods of both types:
Functionality-wise, both approaches are equivalent, with one exception. Method 2
gives pybind11 no C++ type for the parent, so pybind11 uses the same pointer for
both classes. Use method 1 when the parent subobject is not at the start of the
child, for example when the child has virtual functions and the parent has none.

Afterwards, instances will expose fields and methods of both types:

.. code-block:: pycon

Expand Down
1 change: 1 addition & 0 deletions include/pybind11/attr.h
Original file line number Diff line number Diff line change
Expand Up @@ -354,6 +354,7 @@ struct type_record {
bool release_gil_before_calling_cpp_dtor : 1;

holder_enum_t holder_enum_v = holder_enum_t::undefined;
const char *cpp_polymorphism = nullptr;

void add_base(const std::type_info &base, void *(*caster)(void *) );
};
Expand Down
17 changes: 7 additions & 10 deletions include/pybind11/detail/class-inl.h
Original file line number Diff line number Diff line change
Expand Up @@ -383,17 +383,14 @@ PYBIND11_INLINE void traverse_offset_bases(void *valueptr,
instance *self,
bool (*f)(void * /*parentptr*/, instance * /*self*/)) {
for (handle h : get_bases(tinfo->type)) {
if (auto *parent_tinfo = get_type_info(reinterpret_cast<PyTypeObject *>(h.ptr()))) {
for (auto &c : parent_tinfo->implicit_casts) {
if (c.first == tinfo->cpptype) {
auto *parentptr = c.second(valueptr);
if (parentptr != valueptr) {
f(parentptr, self);
}
traverse_offset_bases(parentptr, parent_tinfo, self, f);
break;
}
auto *parent_tinfo = get_type_info(reinterpret_cast<PyTypeObject *>(h.ptr()));
auto cast = parent_tinfo ? get_implicit_base_cast(tinfo, parent_tinfo) : nullptr;
if (cast) {
auto *parentptr = cast(valueptr);
if (parentptr != valueptr) {
f(parentptr, self);
}
traverse_offset_bases(parentptr, parent_tinfo, self, f);
}
}
}
Expand Down
40 changes: 40 additions & 0 deletions include/pybind11/detail/type_caster_base-inl.h
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,46 @@ PYBIND11_NOINLINE_ATTR PYBIND11_INLINE detail::type_info *get_type_info(PyTypeOb
return bases.front();
}

PYBIND11_INLINE bool has_cpp_polymorphism(const type_info *type, const char *capsule_name) {
auto marker = getattr(
handle(reinterpret_cast<PyObject *>(type->type)), cpp_polymorphism_attribute, none());
return PyCapsule_IsValid(marker.ptr(), capsule_name)
&& PyCapsule_GetPointer(marker.ptr(), capsule_name) == type->type;
}

PYBIND11_NOINLINE_ATTR PYBIND11_INLINE bool is_zero_offset_base(const value_and_holder &source,
const type_info *target) {
const auto *derived = source.type;
if (PyType_IsSubtype(derived->type, target->type) == 0) {
return false;
}
while (derived != target) {
auto bases = get_bases(derived->type);
if (bases.size() != 1) {
return false;
}
auto *base_type = reinterpret_cast<PyTypeObject *>(bases[0].ptr());
const auto &base_infos = all_type_info(base_type);
if (base_infos.size() != 1) {
return false;
}
auto *base = base_infos.front();
if (auto cast = get_implicit_base_cast(derived, base)) {
// Virtual base casts require a live C++ object.
if (!source.instance_registered() || !source
|| cast(source.value_ptr()) != source.value_ptr()) {
return false;
}
} else if (!has_cpp_polymorphism(derived, cpp_nonpolymorphic_capsule)
&& !has_cpp_polymorphism(base, cpp_polymorphic_capsule)) {
// A handle supplies no upcast. A polymorphic child can offset a non-polymorphic base.
return false;
}
derived = base;
}
return true;
}

PYBIND11_INLINE detail::type_info *get_local_type_info_lock_held(const std::type_info &tp) {
const auto &locals = get_local_internals().registered_types_cpp;
auto it = locals.find(&tp);
Expand Down
47 changes: 40 additions & 7 deletions include/pybind11/detail/type_caster_base.h
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,22 @@ const std::vector<detail::type_info *> &all_type_info(PyTypeObject *type);
*/
detail::type_info *get_type_info(PyTypeObject *type);

inline auto get_implicit_base_cast(const type_info *derived, const type_info *base)
-> void *(*)(void *) {
for (const auto &cast : base->implicit_casts) {
if (cast.first == derived->cpptype) {
return cast.second;
}
}
return nullptr;
}

bool is_zero_offset_base(const value_and_holder &source, const type_info *target);

constexpr const char *cpp_polymorphism_attribute = "__pybind11_cpp_polymorphism__";
constexpr const char *cpp_polymorphic_capsule = "pybind11.cpp_polymorphic";
constexpr const char *cpp_nonpolymorphic_capsule = "pybind11.cpp_nonpolymorphic";

detail::type_info *get_local_type_info_lock_held(const std::type_info &tp);

detail::type_info *get_local_type_info(const std::type_info &tp);
Expand Down Expand Up @@ -840,9 +856,9 @@ class type_caster_generic {
// Implementation of `load`; this takes the type of `this` so that it can dispatch the relevant
// bits of code between here and copyable_holder_caster where the two classes need different
// logic (without having to resort to virtual inheritance).
template <typename ThisT>
template <typename Caster>
PYBIND11_NOINLINE bool load_impl(handle src, bool convert) {
auto &this_ = static_cast<ThisT &>(*this);
auto &this_ = static_cast<Caster &>(*this);
if (!src) {
return false;
}
Expand Down Expand Up @@ -888,19 +904,36 @@ class type_caster_generic {
}
}

// Case 2c: C++ multiple inheritance is involved and we couldn't find an exact type
// match in the registered bases, above, so try implicit casting (needed for proper C++
// casting when MI is involved).
// Case 2c: Follow the registered cast order when several C++ branches match.
if (this_.try_implicit_casts(src, convert)) {
return true;
}

// Case 2d: A different subclass can mark the target nonsimple. A zero-offset
// chain can still use the slot if its holder is compatible with the caster.
if (!no_cpp_mi) {
constexpr bool loads_holder = !std::is_same<Caster, type_caster_generic>::value;
for (auto &v_h : values_and_holders(src.ptr())) {
const auto *base = v_h.type;
bool reads_holder = loads_holder
|| base->holder_enum_v == holder_enum_t::smart_holder
|| typeinfo->holder_enum_v == holder_enum_t::smart_holder;
if ((!reads_holder
|| (base->holder_enum_v == typeinfo->holder_enum_v
&& base->holder_size_in_ptrs == typeinfo->holder_size_in_ptrs))
&& is_zero_offset_base(v_h, typeinfo)) {
this_.load_value(std::move(v_h));
return true;
}
}
}
}

// Perform an implicit conversion
if (convert) {
for (const auto &converter : typeinfo->implicit_conversions) {
auto temp = reinterpret_steal<object>(converter(src.ptr(), typeinfo->type));
if (load_impl<ThisT>(temp, false)) {
if (load_impl<Caster>(temp, false)) {
loader_life_support::add_patient(temp);
return true;
}
Expand All @@ -914,7 +947,7 @@ class type_caster_generic {
if (typeinfo->module_local) {
if (auto *gtype = get_global_type_info(*typeinfo->cpptype)) {
typeinfo = gtype;
return load_impl<ThisT>(src, false);
return load_impl<Caster>(src, false);
}
}

Expand Down
12 changes: 9 additions & 3 deletions include/pybind11/pybind11-inl.h
Original file line number Diff line number Diff line change
Expand Up @@ -1330,6 +1330,13 @@ PYBIND11_INLINE void generic_type::initialize(const type_record &rec) {

m_ptr = make_new_python_type(rec);

// Store the C++ trait on the Python type to preserve the shared type_info layout.
if (rec.cpp_polymorphism) {
setattr(m_ptr,
cpp_polymorphism_attribute,
capsule(static_cast<void *>(m_ptr), rec.cpp_polymorphism));
}

/* Register supplemental type information in C++ dict */
auto *tinfo = new detail::type_info();
tinfo->type = reinterpret_cast<PyTypeObject *>(m_ptr);
Expand Down Expand Up @@ -1360,10 +1367,9 @@ PYBIND11_INLINE void generic_type::initialize(const type_record &rec) {
} else if (rec.bases.size() == 1) {
auto *parent_tinfo = get_type_info(reinterpret_cast<PyTypeObject *>(rec.bases[0].ptr()));
assert(parent_tinfo != nullptr);
bool parent_simple_ancestors = parent_tinfo->simple_ancestors;
tinfo->simple_ancestors = parent_simple_ancestors;
tinfo->simple_ancestors = parent_tinfo->simple_ancestors;
// The parent can no longer be a simple type if it has MI and has a child
parent_tinfo->simple_type = parent_tinfo->simple_type && parent_simple_ancestors;
parent_tinfo->simple_type = parent_tinfo->simple_type && tinfo->simple_ancestors;
}

with_internals([&](internals &internals) {
Expand Down
15 changes: 10 additions & 5 deletions include/pybind11/pybind11.h
Original file line number Diff line number Diff line change
Expand Up @@ -1341,6 +1341,11 @@ class class_ : public detail::generic_type {
record.type_align = alignof(conditional_t<has_alias, type_alias, type> &);
record.holder_size = sizeof(holder_type);
record.init_instance = init_instance;
if (std::is_polymorphic<type>::value) {
record.cpp_polymorphism = cpp_polymorphic_capsule;
} else if (any_of<is_pyobject<Extra>...>::value) {
record.cpp_polymorphism = cpp_nonpolymorphic_capsule;
}

if (detail::is_instantiation<std::unique_ptr, holder_type>::value) {
record.holder_enum_v = detail::holder_enum_t::std_unique_ptr;
Expand Down Expand Up @@ -1402,11 +1407,11 @@ class class_ : public detail::generic_type {
rec.add_base(typeid(Base), [](void *src) -> void * {
return static_cast<Base *>(reinterpret_cast<type *>(src));
});
// Virtual inheritance means the base subobject is at a dynamic offset,
// so the reinterpret_cast shortcut in load_impl Case 2a is invalid.
// Force the MI path (implicit_casts) for correct pointer adjustment.
// Detection: static_cast<Derived*>(Base*) is ill-formed for virtual bases.
if PYBIND11_MAYBE_CONSTEXPR (!detail::is_static_downcastable<Base, type>::value) {
// Virtual bases and non-polymorphic bases of polymorphic types can need pointer
// adjustment.
if PYBIND11_MAYBE_CONSTEXPR (!detail::is_static_downcastable<Base, type>::value
|| (std::is_polymorphic<type>::value
&& !std::is_polymorphic<Base>::value)) {
rec.multiple_inheritance = true;
}
}
Expand Down
76 changes: 75 additions & 1 deletion tests/test_multiple_inheritance.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,11 @@ struct OffsetProbeDerived : OffsetProbeBase<Case> {
virtual ~OffsetProbeDerived() = default;
};

struct OffsetProbeSibling : OffsetProbeBase<2> {};
struct OffsetProbeHandleDerived : OffsetProbeBase<2> {
virtual ~OffsetProbeHandleDerived() = default;
};

template <int Case>
void bind_base_address_probe(py::module_ &fixture) {
using Base = OffsetProbeBase<Case>;
Expand All @@ -111,6 +116,23 @@ void bind_base_address_probe(py::module_ &fixture) {
py::arg("base").noconvert());
}

// Issue #1080: the vptr of a polymorphic derived class offsets a non-polymorphic base
struct I1080Base {
unsigned int a = 1;
unsigned int d = 4;
};
struct I1080Plain : I1080Base {};
struct I1080MixedHolder : I1080Base {};
struct I1080PythonBridge : I1080Base {};
struct I1080Derived : I1080Base {
I1080Derived() = default;
I1080Derived(const I1080Derived &) = default;
virtual ~I1080Derived() = default;
};
struct I1080Child : I1080Derived {};
struct I1080HandleChild : I1080Derived {};
struct I1080HandleGrandchild : I1080HandleChild {};

} // namespace

TEST_SUBMODULE(multiple_inheritance, m) {
Expand Down Expand Up @@ -396,9 +418,61 @@ TEST_SUBMODULE(multiple_inheritance, m) {
bind_base_address_probe<1>(handle);

auto opt_in = m.def_submodule("offset_opt_in");
py::class_<OffsetProbeBase<2>>(opt_in, "Base");
py::class_<OffsetProbeBase<2>> opt_in_base(opt_in, "Base", py::multiple_inheritance());
py::class_<OffsetProbeDerived<2>, OffsetProbeBase<2>>(
opt_in, "Derived", py::multiple_inheritance())
.def(py::init<>());
py::class_<OffsetProbeSibling, OffsetProbeBase<2>>(opt_in, "Sibling").def(py::init<>());
bind_base_address_probe<2>(opt_in);
py::class_<OffsetProbeHandleDerived>(opt_in, "HandleDerived", py::handle(opt_in_base))
.def(py::init<>());
opt_in.def("handle_addresses", [](const OffsetProbeHandleDerived *self) {
return py::make_tuple(
reinterpret_cast<std::uintptr_t>(self),
reinterpret_cast<std::uintptr_t>(static_cast<const OffsetProbeBase<2> *>(self)));
});

py::class_<I1080Base, std::shared_ptr<I1080Base>> base(m, "I1080Base");
base.def(py::init<>()).def_readwrite("a", &I1080Base::a).def_readwrite("d", &I1080Base::d);
py::class_<I1080Plain, std::shared_ptr<I1080Plain>>(m, "I1080Plain", py::handle(base))
.def(py::init<>());
py::class_<I1080MixedHolder>(m, "I1080MixedHolder", py::handle(base)).def(py::init<>());
auto python_bridge = py::module_::import("builtins")
.attr("type")("PythonBridge", py::make_tuple(base), py::dict());
py::class_<I1080PythonBridge, std::shared_ptr<I1080PythonBridge>>(
m, "I1080PythonBridge", py::handle(python_bridge))
.def(py::init<>());
py::class_<I1080Derived, I1080Base, std::shared_ptr<I1080Derived>> derived(m, "I1080Derived");
derived.def(py::init<>());
py::class_<I1080Child, I1080Derived, std::shared_ptr<I1080Child>>(m, "I1080Child")
.def(py::init<>());
py::class_<I1080HandleChild, std::shared_ptr<I1080HandleChild>> handle_child(
m, "I1080HandleChild", py::handle(derived));
handle_child.def(py::init<>());
py::class_<I1080HandleGrandchild, std::shared_ptr<I1080HandleGrandchild>>(
m, "I1080HandleGrandchild", py::handle(handle_child))
.def(py::init<>());
m.def("i1080_get_d", [](const I1080Base &b) { return b.d; });
m.def("i1080_get_d_shared", [](const std::shared_ptr<I1080Base> &b) { return b->d; });
m.def("i1080_derived_get_d", [](const I1080Derived &b) { return b.d; });
m.def(
"i1080_as_base",
[](I1080Derived &d) -> I1080Base * { return &d; },
py::return_value_policy::reference);
m.def("i1080_base_at_zero", [](I1080Derived &d) {
return static_cast<void *>(&d) == static_cast<void *>(static_cast<I1080Base *>(&d));
});
m.def("i1080_base_registered", [](py::handle wrapper, I1080Derived &child) {
auto *instance = py::detail::get_instance(wrapper.ptr());
auto *base = static_cast<I1080Base *>(&child);
return py::detail::with_instance_map(base, [&](const py::detail::instance_map &map) {
auto range = map.equal_range(base);
for (auto it = range.first; it != range.second; ++it) {
if (it->second == instance) {
return true;
}
}
return false;
});
});
}
Loading
Loading