0

I write 2 C programs : main.c and sum.c.

Here is main.c :

int array[2] = {1, 2};
int main() {
    int val = sum(array, 2);
    return val;
}

Here is sum.c :

int sum(int* a, int n) {
    int i, s = 0;
    for (i = 0; i < n; i++) {
        s += a[i];
    }
    return s;
}

I use command gcc -c -o main.o main.c and objdump -d -r main.o>main.d and I get :

main.o:     file format elf64-x86-64


Disassembly of section .text:

0000000000000000 <main>:
   0:   f3 0f 1e fa             endbr64 
   4:   48 83 ec 08             sub    $0x8,%rsp
   8:   be 02 00 00 00          mov    $0x2,%esi
   d:   48 8d 3d 00 00 00 00    lea    0x0(%rip),%rdi        # 14 <main+0x14>
            10: R_X86_64_PC32   array-0x4
  14:   b8 00 00 00 00          mov    $0x0,%eax
  19:   e8 00 00 00 00          callq  1e <main+0x1e>
            1a: R_X86_64_PLT32  sum-0x4
  1e:   48 83 c4 08             add    $0x8,%rsp
  22:   c3                      retq   

What does 1e: R_X86_64_PLT32 sum-0x4 mean? Shouldn't it be sum-0x22 because at that time the RIP is 0x22?

And also what does 0x4 in 10: R_X86_64_PC32 array-0x4 stand for?

And one more question : My computer is 64-bit but why the address is 32-bit in the assembly code?

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
dubugger
  • 89
  • 6
  • 1
    It's `-4` because RIP already points to the next instruction which is 4 bytes ahead in this case. The actual value of rip is irrelevant. It's the displacement that is 32 bits (sign extended to 64), not the address. But with certain memory models you may use 32 bit addresses as well in special cases. – Jester Feb 18 '22 at 12:56
  • Does this answer your question? [What is callq instruction?](https://stackoverflow.com/questions/46752964/what-is-callq-instruction) – Mgetz Feb 18 '22 at 13:29
  • 1
    "My computer is 64-bit but why the address is 32-bit in the assembly code?" Because RIP-relative addressing has a 32-bit reach. See the instruction encoding table. "at that time the RIP is 0x22" - The "RIP" value in the object file is not the RIP value. It's the address relative to the start of the function. The final RIP doesn't get established until runtime. (Besides, did you really think that `main` started executing at address 0?) – Raymond Chen Feb 18 '22 at 14:17

0 Answers0