Search code examples
inheritancevisual-c++virtual-functionsvmt

Virtual Function Table entry from class that is not related


I am browsing through VFTs (VMTs) of a simple C++ Windows program (I don't have a source code, only binary), compiled by Visual Studio with some sort of optimization on.

I noticed that is uses inheritance and polymorphism. I found the location of struct s_RTTIBaseClassArray for each class that the program has. In that location there is an array of pointers to struct _s_RTTIBaseClassDescriptor. The array of base class descriptors should give you information about all the classes that the current class is derived from.

Virtual Function (Method) Table is a table that contains pointers to all the virtual functions of the current class. However in VFT of a few classes I found a pointer to a virtual method that actually belongs to a different class that is (acording to the Base Class Array) not related to the current class. Example below:

ClassA_BaseClassArray:
            dd offset ClassA_BaseClassDescriptor
            dd offset ClassB_BaseClassDescriptor ; ClassA inherits from ClassB

ClassB_BaseClassArray:
            dd offset ClassB_BaseClassDescriptor

ClassC_BaseClassArray:
            dd offset ClassC_BaseClassDescriptor

ClassA_VMT: 
            dd offset ClassA_VM1 ; virtual method of ClassA
            dd offset ClassA_VM2
            dd offset ClassB_VM2 ; virtual method of ClassB - override
            dd offset ClassC_VM3 ; virtual method of ClassC - NOTHING TO DO HERE
            dd offset ClassA_VM3

The example is short, the actual classes have much more virtual methods.

After examination of ClassC_VM3 I noticed, that it consists of just two instructions:

mov    eax, [ecx+10h]
retn

I found about 3 VMTs similar to this example so far, the unrelated method is always this short.

My question is: what is causing this? Could the code of ClassC_VM3 be identical to the code of some ClassA method, so the compiler just optimized it out?


Solution

  • This might be caused by COMDAT folding, an optimization that merges functions that have the same exact machine code into one. Since it's such a simple function the chances of that are good.