apply() is an important component of languages that support higher-order programming.

It’s usually built into a language, but it isn’t really available in C. Since C has support for dynamic typing (in the form of void*) and first-class functions, I thought it might be possible to implement apply() in C.

Today, I did.

My approach was to mmap() an executable buffer and then craft a payload that loads arguments to the callee. After assembling the payload, I call the target function, restore the stack to its original condition, and then return the contents of %rax to the caller.

What’s really interesting about this is that you can now take pointers to arbitrary functions, even ones with unknown prototypes, and apply them onto data of an arbitrary length. No function pointer typedefs needed!

This implementation of apply() makes it trivial to implement map().

It also makes implementing message passing fairly easy. If you represent an object as a map of function names to function pointers, send() is a breeze;

And there’s no need to stop there!

"This Actually Works?"

Yep. Here’s a basic demo of apply() in action;

… and here’s the source;

It only supports 64-bit operating systems that use the System V calling convention, so you might have to tweak a bit of the assembly if you’re on Windows.

"… Why do this?"

Because I can, of course.

-vk

  1. duliomatos reblogged this from vedantk
  2. vedantk posted this