Live data from Hacker News

Overriding C++ virtual functions at run time

blog.visionappster.com

1–10 of 39 posts

Re: Overriding C++ virtual functions at run time

#4
Had to go a step further in a project and patch static functions in a codebase with no source. It’s certainly enlightening how much you can do with just a symbol map and type info.

I don’t think the articles vtable layout is entirely accurate for gcc though - usually you’ll get 2 destructors at the start of the vtable (assuming the first virtual func declared is the destructor).

Re: Overriding C++ virtual functions at run time

#6

> The C++ standard does not specify how virtual functions should be implemented. In practice, however, compilers generate a virtual function table and place a pointer to it as the first member of a class. wishful thinking: https://gcc.godbolt.org/z/qWEe9r

Cool. Is this due to "final" and the fact that the compiler can figure out the target at compile time?

Re: Overriding C++ virtual functions at run time

#7

> The C++ standard does not specify how virtual functions should be implemented. In practice, however, compilers generate a virtual function table and place a pointer to it as the first member of a class. wishful thinking: https://gcc.godbolt.org/z/qWEe9r

Not sure what you are trying to show, the object still has a vtable and is placed as the first member (and in your example, only) of the class, so that quote is correct.

Obviously if you enable optimizations and one of those optimizations is avoiding the virtual call when the compiler thinks it isn't necessary, then sure you wont get a virtual call everywhere.

But if your code is relying on implementation assumptions like having a vtable at the start of a class, then it should also make sure that this assumption holds by not trying to work around it (e.g. via final) and using compiler options that control that optimization (e.g. GCC has -fno-devirtualize).

It doesn't make much sense to both try and take advantage of implementation details and work against taking advantage of implementation details at the same time.

Re: Overriding C++ virtual functions at run time

#9
post #8

As you might imagine, overwriting vtables in memory is a common technique to hijack control flow and making your program execute attacker's code in an exploit.

Patching function pointers in general is very desirable thing to be able to do when writing these kinds of things. vtables are interesting because unlike normal C function pointers they can only be used in a standards-compliant manner in a few very limited ways, so if you’re implementing control flow verification you can really ratchet up the security for these. For normal C function pointers, sadly, the best you can do is usually very little, if anything at all. Especially because the use of non-compliant constructs like forging ordinary function pointers is extremely common in things like language runtimes.
Post reply on HN