From: Jeffrey Tan[MSFT] on
I am writting a class which acts as the code thunk to "call/jmp" to another
function. The definition is listed below:

class x86CodeThunk
{
private:
const static BYTE X86_THUNK_OPRAND_LENGTH = sizeof(DWORD);
BYTE m_Opcode;
BYTE m_Oprand[X86_THUNK_OPRAND_LENGTH];

public:
x86CodeThunk()
{
memset(m_Oprand, X86_NOP_INSTRUCTION, X86_THUNK_OPRAND_LENGTH);
}
.....
};

However, to honor x86 /PAE DEP, I have to create this class memory on a heap
marked with executable memory protection attribute, like this:

g_hHeap = HeapCreate(HEAP_CREATE_ENABLE_EXECUTE, 0, 0);
assert(g_hHeap!=NULL);
if(g_hHeap==NULL)
{
MyPrintf(TEXT("HeapCreate fails with error %d\n"),
GetLastError());
return FALSE;
}

x86CodeThunk * pCodeThunk = (x86CodeThunk *)HeapAlloc(g_hHeap,
HEAP_ZERO_MEMORY, sizeof(x86CodeThunk));

However, this will not invoke the constructor of the x86CodeThunk class. Is
there any good solution for this problem?

I know I can first *new* x86CodeThunk object and call VirtualProtect to mark
the block with executable attribute. But its performance should be very
poor. Is it possible to tell C/C++ default CRT heap allocator to create
executable memory?

Thanks!