Is there a way, in purely standard C++, to somehow call a function generated within a buffer?
Let's assume:
- We've used implementation-specific knowledge (and obv. architecture-specific) to generate the byte sequence implementing some function in an array of
char. - This implementation correctly matches the implementation's calling convention, and other relevant parts of the ABI, so that it will actually function correctly if called as C++ function
- The buffer is correctly marked as executable
I.e., all the architecture / ABI hurdles have been overcome, all we need to do is actually call this block of code. The question is: is there a standards-compliant way to create a function pointer to this and call said function pointer without hitting undefined behavior?
As I understand it, it is implementation-defined if we can cast a pointer to an object type to a function pointer type. I also believe that it is implementation-defined if said pointer will point to the same logical address as the original pointer. The obstacle is the call: from the perspective of the implementation, all I've done is try and cast a pointer to an array of chars into a function pointer and then call it. If said ptr was one to an object type, I know this would be violating strict aliasing rules, and would be undefined behavior. But is it undefined behavior or merely implementation-defined what will occur if I attempt to call this function pointer?