I try to “inline” my VM by copying code segments from C code between labels to memory allocated by malloc. So I have Ops defined with start and end labels, and I want to copy the instruction defined by the following code to a buffer and then get executed (Im not sure if this is even possible)
OP_PUSH0_START:
sp += 4; *sp = 0; // I WANT THE INSTRUCTIONS OF THIS LINE COPIED TO THE BUFFER
OP_PUSH0_END:
to do so I thought the following code snippet will work
void * ptr0 = &&OP_PUSH0_START;
void * ptr1 = &&OP_PUSH0_END;
while(ptr0 < ptr1)
{
buf[c++] = *ptr0;
ptr0++;
}
goto buf; //jump to start of buffer
but I cant eaven read it out without getting a memory error
I would be happy about any links or any suggestions how to achieve this
The only legal way to transfer execution to an arbitrary location is to use a function pointer.
gotoonly jumps to labels, not arrays or anything else.Also you cannot take the address of a label. A label is not an object or a function.
It is rightly pointed out that data areas are often placed in memory whose content cannot be executed as CPU instructions. There are, however, often workarounds for that. Windows and Linux provide functions to change the permissions/rights/privileges/whatever-you-call-it of a region of the memory.
For example, here’s an example of doing the kind of thing you’re trying to do on Windows.