Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I save the value of rip? [duplicate]

#include <stdint.h>
uint64_t rip;
int main()
{
    asm(
        "movq %%rip, %0\n" : "=m" (rip)
        );

    sleep(10);
}

When I compile I get

cc -m64    rip.c   -o rip
/tmp/ccwNbZi1.s: Assembler messages:
/tmp/ccwNbZi1.s:12: Error: suffix or operands invalid for `movq'
make: *** [rip] Error 1
like image 713
dbbd Avatar asked Sep 12 '12 23:09

dbbd


People also ask

How does RIP register work?

The %rip register on x86-64 is a special-purpose register that always holds the memory address of the next instruction to execute in the program's code segment.

What is %rip in x86?

The instruction pointer register (%rip) points to the next instruction to execute; it cannot be directly accessed by the programmer, but is heavily used as the base for position-independent code addressing.


1 Answers

You can't read (E|R)IP because there's no x86(/64) instruction to read it directly.

The only way to "read" it is to make a call with the CALL instruction. It will save the return address on the stack and that one you can read.

UPDATE: In 64-bit mode you can exploit the RIP-relative addressing, so LEA RAX, [RIP] will give you the address of itself in RAX. Yet another workaround is MOV RAX, $ in assembly.

like image 135
Alexey Frunze Avatar answered Sep 24 '22 19:09

Alexey Frunze