Interesting hack to dump binary contents of a function.

It's cool that you figured this out. I feel like I should point out a few limitations - you basically have implemented a loader, but are missing a few key features: the biggest one being relocations. Your memory mapped function won't execute for anything but trivial examples (especially on architectures which don't use pc relative addressing, in that case even jumps won't work).

Not all functions are contiguous either. In fact, most optimized functions are not - it's common to split a function into "hot" and "cold" portions, with jumps between them, and the cold portion located off in some corner of the binary.

Functions definitely don't always end in ret instructions. There are tail calls, of course - and functions which don't return at all. Functions with multiple ret instructions. And of course cold code, like above.

I think there are few practical applications for a customer loader, as it's usually easier to just ask the OS to do it for you (LoadLibrary or friends), but there are a few use cases around security, obfuscation, etc.

Note that it's getting increasingly common for environments to just not allow user mode code to create executable pages. Sigh.

And to get the length of a function (along with multiple sections of a function) there isn't a way other than digging into the debug information (PDBs on windows) or reading the instructions - and you'll end up building a nearly fully functional x86/amd64/etc interpreter before you get getFunctionLength() working properly.

/r/cpp_questions Thread