As mentioned in Max's answer, VirtualAllocEx is one way to allocate memory pages in a remote process if you have PROCESS_VM_OPERATION access to the process in question. You will also want to make sure that new pages are marked PAGE_EXECUTE_READWRITE for their level of protection during recording, and then change it later to PAGE_EXECUTE_READ using VirtualProtectEx .
Note that the branching and some call commands in x86 are IP related. This means that their encodings depend on where they are located in memory, since they use a signed relative offset from the end of the instruction. Therefore, if you plan to call an existing function from your new code, make sure that you take this into account when using the relative call command or use an indirect / immediate form.
However, not knowing exactly what you are trying to execute here, it is difficult to recommend a method to execute your new target code. Using the new code, you can simply enter the remote thread using CreateRemoteThread to execute it without having to interrupt existing threads. This would be the easiest solution to execute new code, but requires that the code you invoke is thread safe. Choosing an already running thread, pausing it, changing the EIP or introducing a detour and resuming it without any side effects (correctly maintaining the context in a nested call) is very difficult to say.
Personal note: as the author of a code coverage tool in Visual Studio 2012 that uses a bunch of tricks to rewrite third-party x86 / x86-64 code on the fly to collect coverage data, this stuff is oh-lot of fun to crack and think :)
source share