" marked as duplicate by Neil Butterworth, Sombrero Chicken c++ yesterday
This question has been asked before and already has an answer. If those answers do not fully address your question, please edit this question to explain how it is different or ask a new question."
Wrong!
Example:
byte chunk[] = { 0x90, 0xC3 }; //opcodes for nop and ret instructions
((void(__cdecl*)())(&chunk))(); //call the function pointer
Throws an
Exception thrown at here_address_of_chunk in MyProgram.exe: 0xC0000005: Access violation executing location here_address_of_chunk.
Why this happens and how to properly implement this?
Edit: In a request of drescherjm:
class ExampleClass
{
public:
ExampleClass()
{
chunk[0] = 0x90;
chunk[1] = 0xC3;
VirtualProtect(&chunk, 2, PAGE_EXECUTE_READWRITE, 0);
}
auto Call()
{
((void(__cdecl*)())(&chunk))();
}
unsigned char chunk[2];
};
ExampleClass().Call();
Edit2: For the record:
byte chunk[] = { 0x90, 0xC3 };
DWORD old_protection;
VirtualProtect(&chunk, 2, PAGE_EXECUTE_READWRITE, &old_protection);
((void(__cdecl*)())(&chunk))();
Works just fine.
Resolved: Stupid bug not caught because of the silent behavior of the VirtualProtect function. I passed a 0 as the pointer of the old protection and thus the memory access wasn't modified at all!
https://msdn.microsoft.com/en-us/library/windows/desktop/aa366898(v=vs.85).aspx
"lpflOldProtect [out]
A pointer to a variable that receives the previous access protection value of the first
page in the specified region of pages. If this parameter is NULL or does not point to a
valid variable, the function fails."
It fails silently and leads to nasty bugs!
Great thanks to drescherjm - the only person trying to help me in contrast of some individuals that always are bashing peoples asking for help here.
User contributions licensed under CC BY-SA 3.0