Skip to content

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

Description

@jpenglert

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:

  • jnaerator:0.12
  • bridj:0.7.0
  • jna:4.2.1
  • MS Visual Studio 2013

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions