简体   繁体   中英

How to generate IP relative addressing instructions with GCC

I wrote a small program to test GCC's options.

int main()
{
    int a=0;
    __asm__("movl %0,%%ecx\n"
            "jmp jmpsection\n"
            "inc %%ecx\n"
            "jmpsection: movl $1,%%eax\n"
            "movl $0,%%ebx\n"
            "int $0x80\n"::"a"(a):"ecx","ebx");
}

In order to keep var a equal to 1, skip the inc instruction. I want to force GCC to generate the jmp instruction using IP relative addressing method. I have searched the GCC manual to find a solution, but I feiled. Thanks for replay.

For the x86, IP relative addressing is only possible in long mode (64 bit) and you seem to be writing 32 bit code.

Edit: Actually, in 32 bit mode it is possible to make jumps relative to the current IP and I think the compiler actually generates the correct code in your case. Let's take a look at the relevant part of the generated assembly:

00000000 <main>:
  ...
  13:   eb 01                   jmp    16 <jmpsection>
  15:   41                      inc    %ecx

00000016 <jmpsection>:
  16:   b8 01 00 00 00          mov    $0x1,%eax
  ...

So, although it looks like the instruction at address 13 makes a direct jump to address 16, it actually is an IP relative jump. Take a look at the machine code:

eb 01

eb is the opcode for a short jmp with an 8-bit displacement. 01 is this displacement. The result of this instruction is a jump to %eip + 0x01 and, as the IP points to the next instruction to be executed, this will jump to address 16.

When you use inline assembly in GCC the assembly code is just passed on directly to the assembler. GCCs command line options do not change your assembly code. You can verify that looking at the output (use the -S option). The compiler options only change the way GCC generates assembly from C Code.

So instead of your compilers manual you need to look at your assemblers manual . In your case GAS will probably select the short PC relative coding for jmp without the need to specify any options.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM