5

I have this snippet in my code

void jmp_esp()
{
    __asm__("jmp *%esp");
}

when compiling with gcc

gcc aslr.c -o aslr -ggdb -fno-stack-protector -z execstack

i get this error.

aslr.c: Assembler messages:
aslr.c:6: Error: operand type mismatch for `jmp'

Why this line is failing to compile although the assembly instruction is valid ?

I've read about DEP (Data Execution Prevention). could it be that this feature is creating this compilation error ? if so, how to disable it ?

hannibal
  • 266
  • 4
  • 15
  • 4
    Unrelated to your question, but this is not a valid use of inline asm since you have no control over the value of `%esp` when the inline asm block is entered. In particular it is **not** necessarily the value of the stack pointer at function entry. If you need to do this you need an asm source file or file-scope asm statement defining the function entry point rather than a C function. – R.. GitHub STOP HELPING ICE Jun 10 '18 at 14:07
  • 1
    @R..: I suspect the OP wants the 2-byte sequence to appear somewhere in their code for playing with a ret2reg attack, not for calling this function normally. Of course putting it at the global scope with a label on the actual instruction would make it easier to find (no need to search the machine code, just use `nm` and look for the `jmpesp:` label you added). – Peter Cordes Jun 10 '18 at 17:58
  • @R.. as Peter Cordes said, i was just playing around with ASLR bypassing and wanted the jmp *%esp to appear in the assembly code – hannibal Jun 11 '18 at 15:09

1 Answers1

6

The instruction jmp *%esp is available only in 16 and 32 bit modes. In 64 bit mode, jmp r/m32 cannot be encoded. Depending on what your intent is, there are two ways to fix your code:

  • if your intent is to write a 32 bit x86 program, compile and link with -m32 to make the compiler emit 32 bit code.
  • if your intent is to write a 64 bit x86 program, change the instruction to jmp *%rsp to jump to the address contained in the rsp register instead.

Note that this is independent of DEP. DEP prevents the execution of memory regions not specifically marked as executable. This happens at runtime, not at compile time.

fuz
  • 88,405
  • 25
  • 200
  • 352