A comment wasn't enough space. Joe_Muc is correct. You should not stuff code into memory obtained by malloc
or new
. You will run into problems if you change the page properties of pages that Windows allocates.
This isn't a problem becuase using VirtualAlloc() and the related WIn32 APIs is every easy: call VirtualAlloc() and set the flProtect
to [PAGE_EXECUTE_READWRITE][2]
Note, you should probably do three allocations, one guard page, the pages you need for your code, then another guard page. This will give you a little protection from bad code.
Also wrap calls to your generated code with structured exception handling.
Next, the Windows X86 ABI (calling conventions) are not well documented (I know, I've looked). There is some info here, here, here The best way to see how things work is to look at code generated by the compiler. This is easy to do with the \FA
switches ( there are four of them).
You can find the 64-bit calling conventions here.
Also, you can still obtain Microsoft's Macro Assembler MASM here. I recommend writing your machine code in MASM and look at its output, then have your machine code generator do similar things.
Intel's and AMD's processor manuals are good references - get them if you don't have them.