Functions in dynamic memory

Recently, as an experiment I was curious about executing code in dynamic memory in a C/C++ program.

It’s doable, but you need to do a few things you may not think of; you cannot just insert the assembly into your variable, and call it like a function.

The problem with that code is that you’re not changing the permissions of the memory to be executable; since it’s dynamically allocated, it has read and write permissions, but not execute.

In order to achieve that, we make use of the VirtualProtectEx function. The permission constant we’re after is PAGE_EXECUTE_READWRITE. Our code now becomes:

Now that you know what’s needed to execute it, what about writing the assembly into the variable? You sadly, cannot just assign it like this:

You need to work out the hex for each opcode and assign it on a per-byte basis. You also need to take into account how external functions are called in assembly:

The call is looked up in the programs thunk table, which then points to the proper address; a double pointer. So for us to do a call properly, we can either make use of the thunk table (finding it + referencing it) or we can use a variable of our own, like so:

Putting together everything from this article, here is a fully working “Hello world” achieved with dynamic memory.

That’s probably the most complicated hello world I’ve made..

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.