nativelibs4java / BridJ

BridJ: blazing fast Java / C / C++ interop
https://code.google.com/archive/p/bridj/
Other
289 stars 77 forks source link

Virtual destructor not taken into account when allocating memory for object #87

Open jpenglert opened 8 years ago

jpenglert commented 8 years ago

Heap corruption can easily occur if not enough bytes are allocated by Bridj when instantiating the peer C++ object. In this case, I ran into a situation where the 4 bytes needed for V-Table pointer were not being added to the total object size computed by org.bridj.StructUtils.performLayout().

If you have a header file that declares a virtual destructor and no other virtual methods then JNAerator will NOT generate the corresponding Java method for the destructor annotated with @Virtual. org.bridj.StructDescription.isVirtual() depends on at least one method in the corresponding Java class having the @Virtual annotation in order for org.bridj.StructUtils.performLayout() to pad the total object size with the 4-bytes needed for V-Table pointer.

This may be a JNAerator bug but I've found no mention of destructors in Bridj documentation.

class Foo
{
public:
   Foo() {};
   virtual ~Foo() {};

private:
   int mField1;
   int mField2;
};

JNAerator will generate Foo.java for the above class with a ctor and methods for the fields but no method for the destructor. BridJ.sizeOf(Foo.class) will return 8 and thus org.bridj.cpp.CPPRuntime.newCPPInstance(...) will only allocate 8 bytes of memory when the actual size of Foo.cpp is 12 bytes. This can cause heap corruption AFAICT.

Not sure what the solution should be but here are a few thoughts:

  1. Have Bridj examine the destructor symbol and detect that it's virtual? Not sure if name mangling exposes this info.
  2. JNAerator creates corresponding Java method for destructor with @Virtual annotation
  3. JNAerator annotates corresponding Java class with @Virtual when it detects any virtual method

I think option 3 is the way to go because then no Java destructor needs to be created.

Environment: