'Are there any instructions (other than those that use RIP-relative addressing) that are position dependent?

(This question refers specifically to x86/x86_64)

I'm working on an application that needs to insert a small block of instructions at specific points within another (both in userspace) at runtime. The general process currently looks like this:

  • Find a suitable replacement point
  • Copy the instruction being replaced (plus the added ones) to an unused area of memory
  • Overwrite the original instruction with a jmp (can't use call for fear of corrupting the stack) pointing to the moved code

The redirected block of instructions carries out some basic operations, restores the processor back to its pre-jump state, runs the replaced instruction, then jumps back to the original code.

It is of critical importance that the original functionality of the application being modified is perfectly maintained. With the current setup, it is of course possible that the targeted application could detect the replacement and change its behavior, or otherwise attempt to defend against such modification, but the intended use of this program makes it very unlikely that that the target would care to defend itself in any serious way, so this is not a concern. Some basic steps are already taken to ensure this:

  • The replacement point is checked to be a single instruction greater than or equal to in size to the replacing jmp
  • The moved block is checked to ensure that the replacing jmp can actually reach it

Obviously, however, some instructions may not execute correctly after they have moved (in other words, they are position dependent). Of the top of my head, the only such instructions I can think of are ones that use RIP-relative addressing, like any relative calls / jumps like jmp, jcc, call and others, and any with a [rip+rel32] memory operand. This is easily detected, and such instructions can be modified so that the calculated addresses refer to their original locations.

Are there any other instructions (or encodings) that could pose a problem here?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source