Repository navigation
Description
Required prerequisites
- Make sure you've read the documentation. Your issue may be addressed there.
- Search the issue tracker and Discussions to verify that this hasn't already been reported. +1 or comment there if it has.
- Consider asking first in the Gitter chat room or in a Discussion.
Problem description
Hi,
Recently I have encountered with the situation (segmentation fault issue) which is difficult for me to debug.
I have a diamond-like hierarchy of classes in C++, which I want to use in python. I have written pybind wrapper but
had some problems after compiling and trying to call one of my methods.
Here is the C++ source code (animal.hpp):
#include <string>
#include <iostream>
namespace example {
class Creature {
public:
virtual std::string typeName() const = 0;
virtual ~Creature() = default;
};
class Animal : public Creature {
public:
Animal() {
std::cout << "Animal created: " << this << std::endl;
}
Animal(const Animal& animal) : Creature(animal) {
std::cout << "Animal copied: from " << &animal << " to " << this << std::endl;
}
~Animal() {
std::cout << "Animal deleted: " << this << std::endl;
}
std::string typeName() const override {
return _typeName;
}
private:
std::string _typeName = "animal";
};
class TerrestrialAnimal : public virtual Animal {
public:
TerrestrialAnimal() {
std::cout << "TerrestrialAnimal created: " << this << std::endl;
}
TerrestrialAnimal(const TerrestrialAnimal& animal) : Animal(animal) {
std::cout << "TerrestrialAnimal copied: from " << &animal << " to " << this << std::endl;
}
~TerrestrialAnimal() {
std::cout << "TerrestrialAnimal deleted: " << this << std::endl;
}
std::string typeName() const override {
return _typeName;
}
private:
std::string _typeName = "terrestrial";
};
class AquaticAnimal : public virtual Animal {
public:
AquaticAnimal() {
std::cout << "AquaticAnimal created: " << this << std::endl;
}
AquaticAnimal(const AquaticAnimal& animal) : Animal(animal) {
std::cout << "AquaticAnimal copied: from " << &animal << " to " << this << std::endl;
}
~AquaticAnimal() {
std::cout << "AquaticAnimal deleted: " << this << std::endl;
}
std::string typeName() const override {
return _typeName;
}
private:
std::string _typeName = "aquatic";
};
class Frog : public TerrestrialAnimal, public AquaticAnimal {
public:
Frog() {
std::cout << "Frog created: " << this << std::endl;
}
Frog(const Frog& animal) : Animal(animal), TerrestrialAnimal(animal), AquaticAnimal(animal) {
std::cout << "Frog copied: from " << &animal << " to " << this << std::endl;
}
~Frog() {
std::cout << "Frog deleted: " << this << std::endl;
}
std::string typeName() const override {
return _typeName;
}
private:
std::string _typeName = "frog";
};
class AnimalUsage {
public:
AnimalUsage() {
std::cout << "AnimalUsage created: " << this << std::endl;
}
AnimalUsage(const AnimalUsage& u) {
std::cout << "AnimalUsage copied: from " << &u << " to " << this << std::endl;
}
~AnimalUsage() {
std::cout << "AnimalUsage deleted: " << this << std::endl;
}
const Animal& getAnimal() {
return frog;
}
const AquaticAnimal& getAquaticAnimal() {
return frog;
}
const Frog& getFrog() {
return frog;
}
private:
Frog frog;
};
}Corresponding pybind wrapper:
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/functional.h>
#include "animal.hpp"
namespace py = pybind11;
PYBIND11_MODULE(examples, m) {
using namespace example;
py::class_<example::Animal> animal(m, "Animal");
animal.def(py::init<>());
animal.def("type_name", &example::Animal::typeName);
py::class_<example::TerrestrialAnimal, example::Animal> terrestrialAnimal(m, "TerrestrialAnimal");
terrestrialAnimal.def(py::init<>());
terrestrialAnimal.def("type_name", &example::TerrestrialAnimal::typeName);
py::class_<example::AquaticAnimal, example::Animal> aquaticAnimal(m, "AquaticAnimal");
aquaticAnimal.def(py::init<>());
aquaticAnimal.def("type_name", &example::AquaticAnimal::typeName);
py::class_<example::Frog, example::TerrestrialAnimal, example::AquaticAnimal> frog(m, "Frog");
frog.def(py::init<>());
frog.def("type_name", &example::Frog::typeName);
py::class_<example::AnimalUsage> animalUsage(m, "AnimalUsage");
animalUsage.def(py::init<>());
animalUsage.def(py::init<const example::AnimalUsage &>(), py::arg("u"));
animalUsage.def("get_animal", &example::AnimalUsage::getAnimal);
animalUsage.def("get_aquatic_animal", &example::AnimalUsage::getAquaticAnimal);
animalUsage.def("get_frog", &example::AnimalUsage::getFrog);
}After compiling this file and generating the lib by the name examples, I imported AnimalUsage class in my test file and tried to call get_animal method:
from examples import AnimalUsage
usage = AnimalUsage()
usage.get_animal()This call ends with segmentation fault:
Animal created: 0x600000c800d8
TerrestrialAnimal created: 0x600000c80080
AquaticAnimal created: 0x600000c800a0
Frog created: 0x600000c80080
AnimalUsage created: 0x600000c80080
Animal copied: from 0x600000c80080 to 0x6000022804a0
[1] 12401 segmentation fault ./test.py
In my source C++ example I keep Frog instance in AnimalUsage class and return it from three different methods: getAnimal, getAquaticAnimal and getFrog. I know that I shouldn't expect polymorphism to work here since the default return value policy is copy policy for references (when I use reference_internal return value policy, everything is good), but I can't find out the cause of segmentation fault.
Except of segfault issue, from Animal copy constructor log I also noticed that object is being copied from address 0x600000c80080 which is not the address of Animal which has ben created. It corresponds to the Frog address of the initial object. It seems to me that the copy should have been done from 0x600000c800d8 address. It seems that pybind detects at the runtime that returned Animal& object type is Frog, goes to that object and uses it to call Animal copy constructor.
FYI: everything is ok when I return by value instead of returning by reference from getAnimal method.
Thanks,
Davit
Reproducible example code
No response
Activity
Skylion007 commentedon Jan 17, 2022
Okay, so I did some digging into this and it's probably because the return_value_policy is usually move for returns by value so that's why the return by value is wroking.
pybind11/include/pybind11/cast.h
Line 853 in 5194855
Skylion007 commentedon Jan 18, 2022
Potentially related to: #3217
NAThompson commentedon Jan 27, 2022
I have built a python interpreter with AddressSanitizer, and rerun this example, compiling with
-fsanitize=address -fsanitize=undefined -g:@davidhamb95 : Thanks for building this into a minimal reproducer; I was seeing this error over and over but couldn't figure out how to pare it down to something that would fit in a bug report. Hopefully the UBSan/Asan report helps crack this case.
rwgk commentedon Jan 27, 2022
I don't have the free bandwidth to understand the very large reproducer. But if you put it in a PR, and it passes the valgrind GHA (all existing tests pass obviously), it'll only take a few minutes of my time to run it through the Google-internal sanitizers. Please tag me on the PR.
Skylion007 commentedon Jan 28, 2022
Okay, so this bug is actually pretty subtle. First of all, there is a bug here:
pybind11/include/pybind11/pybind11.h
Line 1399 in ec81e8e
None of our test suite seems to use virtual base classes except for the brand new multi-inheritance tests added two days ago.
My current theory about what is going wrong:
add_basewith a try .. except, then get_animal works, but deallocating the object causes a segfault.Stumped about how to proceed.
Skylion007 commentedon Jan 28, 2022
@virtuald Any thoughts on how to handle virtual classes properly?
virtuald commentedon Jan 28, 2022
I don't have time at the moment to fully grok this, can look tonight.
... but I have virtual base class thingies working correctly as far as I can tell. I had found this previously (#2071) that indicated that using py::multiple_inheritance was required when dealing with a virtual base class. I don't remember if my autowrapper forces py::multiple_inheritance if it finds a virtual base class or not... I think it does?
rwgk commentedon Jan 29, 2022
If looked carefully at @Skylion007 's comment and I have some vague ideas that may or may not be relevant.
Could someone please create a reproducer draft PR that we can all play with? (@NAThompson or @Skylion007 I figure you must have something already.)
The most important of the vague ideas is:
void *further upstream? For polymorphic types that would bedynamic_cast<void *>, which is a very special beast.In another context we handle this properly, with template specializations distinguishing between polymorphic and non-polymorphic types:
pybind11/include/pybind11/detail/type_caster_base.h
Line 887 in 07103d6
Skylion007 commentedon Feb 8, 2022
Okay, looks like I am barking up the right tree: gnuradio/gnuradio#5292
Skylion007 commentedon Apr 12, 2022
Could be related to: #1257
plfoley commentedon May 15, 2022
I encountered the same issue and I think your analysis is right about the cast issue.
I went digging a bit in pybind11 (v2.6.1 & v2.9.2) code to try to figure out what the issue could be.
One of the thing that surprised me was that the typeinfo->implicit_casts available to the try_implicit_casts method of copyable_holder_caster did not contain an entry for all the branches in my inheritance tree. Actually a whole part behind the virtually inherited interface I was trying to cast to was missing even tough that class is exported to python through pybind.
My class hierarchy looks something like this:
VirtualInterface1
AbstractBaseClass1 : VirtualInterface1
VirtualInterface2 : VirtualInterface1
AbstractBaseClass2 : AbstractBaseClass1, VirtualInterface2
VirtualInterface3 : VirtualInterface2
AbstractBaseClass3 : AbstractBaseClass2, VirtualInterface3
DerivedClass3A : AbstractBaseClass3
DerivedClass3B : DerivedClass3A
DerivedClass3C : DerivedClass3B
All virtual interfaces are pure virtual with trivial constructors and public virtual destructors.
All of these classes and interfaces are fully exported through pybind.
I have two other classes which have methods that use instances polymorphically:
Implementation1
Implementation2 : Implementation1
In Implementation1 have a method that takes an instance of VirtualInterface1 as parameter. When I call this from Python on an instance of Implementation2, I have the same issue as described here but this happens only when the C++ code is compiled with MSVC, not with GCC nor LLDB. If I overload that method in Implementation2 to take AbstractBaseClass2 or AbstractBaseClass3 as parameter there is no problems.
I saw that behavior before when I was implementing a polymorphic delegation system. The issue was that we needed to cast to void* for compatibility reasons and needed to restore the type when executing the delegate. The problem was that if the delegate was instantiated from a base class, there was no way of knowing the most derived type to execute the correct static_cast to the most derived type. Doing this caused exactly the same problem we see here: getting a corrupted pointer with MSVC and much less often (although I did observed this in some of my tests) with GCC and LLDB.
The problem with casting to void* is that you lose all RTTI. The way I managed to make this work was to implement some sort of reflexion where we would extract the most derived type information and map it to a cast routine that would always static_cast to the correct type when resolved. The only drawback of this is that you can't initialize this in your construction sequence. I am guessing a similar solution could be applied to pybind11 since it seems to store std::type_info along with the instance pointer.
I just started to look into pybind11 code and everything is still unfamiliar so don't expect too much quickly. Moreover, the workaround of using the linear hierarchy is workable for us at the moment so we will probably go this way for now and refactor this when a solution has been implemented.
Another test I did was to set the correct pointer address manually in the aliasing constructor of the smart pointer (I use my own type of smart pointer, nor shared_ptr for historical reasons) when the cast operation on the VirtualInterface took place. This made the operation succeed and the call completed as expected.
There is clearly an issue in the library when it comes to cast instances polymorphically. This is a rather complicated issue to understand and fix, but I felt like sharing my experience in the hope that this could bring ideas to someone with more intrinsic knowledge in the library. If I can be of any help I would gladly help in any capacity I can because I would really want to see this one fixed.
Skylion007 commentedon May 15, 2022
@rwgk @henryiii @wjakob ^ See above.
rwgk commentedon May 15, 2022
Could you please provide a reproducer?
Until we have a reproducer it is too early to derive any conclusions about problems in the library.
That doesn't sound right: when virtual functions are involved, you need to use dynamic_cast.
plfoley commentedon May 15, 2022
First of all, I would like to praise you guys for being so responsive. This shows PyBind11 is very alive and kicking and that confort my choice to commit to the library in my architecture.
dr;tl
1 - Virtual methods and virtual inheritance are two very different concepts.
1a - Always use dynamic_cast to cast to void*.
1b - Always static cast void* to the most derived type the void* represents then dynamic_cast to virtually inherited base class.
2 - I will craft you a code sample that reproduces the issue. C++ class hierarchy with python bindings and Python code that triggers the issue. I will be very busy in the coming weeks so this might take some time however.
I am sorry if I state stuff you already know but I am covering them in the odd chance this makes you see what could be causing this issue.
When inheriting virtually, the derived class memory layout will contain only one copy of the virtually inherited class. This is true for every virtually inherited classes in the hierarchy. The standard is clear on the guaranties that a compiler must offer but the implementation details are left to the compiler vendor. In this particular regard, MSVC implementation differs significantly from GCC implementation.
As I am sure you know, you need to use the RTTI when navigating the class hierarchy, that's why you mentioned using dynamic_cast and in this regard this is absolutely true. The thing with virtual inheritance is that the class memory layout is not guaranteed since you need to have one and only one copy of the virtually inherited class. As long as you still have the RTTI on the instance you are fine navigating the hierarchy through dynamic_cast.
If you want to get a void* to the top of the instance memory layout, the way to do this is to use dynamic_cast<void*> as mentioned in an earlier comment. The problem then is that all RTTI will be gone on that instance. The only way to restore the RTTI is to static_cast the void* to the most derived type the instance refers to. Once the RTTI is restored on the instance you are free to use dynamic_cast to navigate the hierarchy again. If you cast the void* to an intermediate class, the result will be undefined. That explains why it sometimes works and sometime doesn't. In my experience this will almost never work properly with MSVC and much more often in GCC.
I think that this cast from void* to an intermediate class might be what is happening. I have to admit I haven't dug enough in pybind code at this point to be completely sure that this is what is happening. I would like to understand more how the implicit cast list works in the library so I plan to dig more on this topic as I think this might be a point of interest to solve this issue. What makes me think this is cast related is that when I manually correct the pointer passed to the aliasing constructor of my smart pointer (2nd parameter) to make it point to the top of the instance, the python operation succeeds. This is the exact same behavior I observed when I was dealing with cast issues when designing my polymorphic delegation system which was receiving void* and casting them to the target class before executing the stored pointer-to-member function on it.
I wanted to communicate that information to you guys sooner than later on the chance one of you might see where the described problematic situation might occur. I agree that without a reproducible example it is hard to definitively state that that is an issue in the library and I will make sure to give one to you as soon as possible.
Of course I will remain available to answer any question you might have and I might ask some guidance on the library design and architecture if you are inclined when I start digging.
rwgk commentedon May 15, 2022
I'm sorry to sound like a broken record, but the only thing I could act on is a reproducer.
We'd have to make guesses: there will be no certainty that we hit the right thing.
IIUC you have something that is broken: please reduce.
plfoley commentedon May 15, 2022
Don't worry I totally agree with the fact you don't want to go on a wild goose chase on a limb.
I did not expected anyone to look into this before I came back with a sure-fire way of reproducing this.
This is why I will make sure the exact same behavior is exhibited by the sample code.
This is also partly why it might take some time before I am able to give it to you.
Until I am able to get you something concrete to work on.
plfoley commentedon May 30, 2022
Hey guys!
I am working on a sample code to reproduce the issue. I should have this out tomorrow (I hope).
I have a deployment question for you all:
I usually always deploy my modules to site-packages and use them from there.
I'd like, if possible to avoid polluting yours.
Is there a way you are aware of that allows to load pybind11 generated modules in the Python environment without distributing them to site-packages?
Skylion007 commentedon May 30, 2022
@plfoley Modifying the PYTHONPATH environment variable usually works for local testing. Just running the
pytestcmake target should run all the tests thoug without installing anything.bluescarni commentedon Nov 28, 2022
@rwgk there is a small reproducer for an issue which may be the same as this, over at #4365 .