views:

54

answers:

4

can I do something like:

typedef void (*functor)(void* param);

//machine code of function
char functionBody[] = {
    0xff,0x43,0xBC,0xC0,0xDE,....
}
//cast pointer to function
functor myFunc = (functor)functionBody;
//call to functor
myFunc(param);
A: 

Depends on protection ring.

on most popular desktop platforms, you will not be able to execute code in data segment because of page privileges.

Pavel Radzivilovsky
i'am assuming windows, using C language, like this: http://www.wlug.org.nz/CastingPointerToFunction he said once i got a pointer to your machine code (usually an array of bytes), you need to cast it to the appropriate type and call it.
uray
Just to clarify, in theory, this is possible, as long as the opcodes are valid it'll execute just fine.
roe
A: 

On modern operating systems, it depends on whether the memory is marked executable or not. On POSIX systems, it may be possible to obtain executable memory using mmap. Keep in mind that even on a given cpu architecture, calling convention may vary. For example if the caller expects the callee to clear arguments off the stack, your code had better do that or it will crash on return. (Normally, C ABIs don't make this stupid requirement, but it's something to think about.)

Rather than trying to call your machine code directly as a C function pointer, it may be better to write an inline asm wrapper that calls it. This way, you have control over the calling convention.

R..
Or to rephrase: there is no portable way to do it. It boils down to what application can do to allocate or mark the memory as executable. For *NIX one should start reading the `man mmap` and `man mprotect` and look for PROT_EXEC. Keep in mind the position independent v. dependent code. Rest is "as usual" to asm programming...
Dummy00001
+1  A: 

Formally, the C language doesn't allow conversions between function pointers and object pointers, so this can't be done.

However, many C implementations - perhaps even "most" - support this as an extension. Whether it works or not depends on things like memory permissions and cache coherency, which will change depending on your architecture and operating system.

caf
A: 

It could work. Possibly using const char[] for the machine instructions is even better, because on many platforms static const storage is placed in the read-only program memory section.

Peter G.