How'd I go about copying a function in memory to a different location and be able to run it from the new location in C++?
I thought maybe memcmp would work, but I'm not sure how I'd go about running it after it copied to the new location.
How'd I go about copying a function in memory to a different location and be able to run it from the new location in C++?
I thought maybe memcmp would work, but I'm not sure how I'd go about running it after it copied to the new location.
You cannot do that (copying the code of some function) in a portable way. The machine code of some function cannot be moved without care, because in many instruction sets the code depends of its position. For example, many CALL
or JUMP
machine instructions are relative to the program counter (so if you "move" them they will jump to an erroneous location). Details are implementation specific and vary with the compiler, the calling conventions, the instruction set, the ABI, the operating system. Read more about linkers, e.g. Levine's Linkers & loaders book.
I thought maybe
memcpy
would work
No, it generally won't. (BTW memcmp
is just comparing bytes, not "moving" or "copying" them).
Read about Position Independent Code and Relocation (& virtual address space)
Perhaps you should consider generating machine code, using some JIT compilation library like GNU lightning, or GNU libjit, or asmjit, or GCCJIT, or LLVM. On POSIX systems, you could simply emit some C or C++ code into some temporary file, compile it (into a position independent shared object), and use dlopen(3) & dlsym(3) (see here for more).
but I'm not sure how I'd go about running it after it copied to the new location
If the new location contains valid executable machine code (but see W^X), you just use some function pointer (and call it). But beware of undefined behavior.
PS. You really should motivate your question, which looks like an XY problem.
memcpy
-ed one)
Commented
Oct 25, 2016 at 19:20