0

I found some assembly code about "hello world", but I don't understand leaq L1(%rip), %rdi, why rip is used here?

.text
.globl _main
_main:
    pushq %rbp
    movq %rsp, %rbp
    leaq L1(%rip), %rdi   <--it's the first time that I found IP is directly used in code.
    movq $0, %rax
    callq printf
    movq #0, %rax    <-sorry, here shoud be $0
    leaveq
    retq

    .data 
L1: .string 'hello jason\n'

usually, I understand and often use the following style assembly code as url http://libra.cs.virginia.edu/~aaron/08-nasm/nasmexamples.html

    global  _main
    extern  _printf

    section .text
_main:
    push    message
    call    _printf
    add esp, 4
    ret
message:
    db  'Hello, World', 10, 0

therefore, I don't understand the first program, why %rip is used? it's very strange.

  • Your 2nd example is NASM syntax (a flavour of Intel syntax) and is for a 32-bit stack-args calling convention, while your first code block is GAS AT&T syntax (https://stackoverflow.com/tags/att/info) for x86-64 (using a register args calling convention), compiled with optimization disabled. The use of RIP-relative addressing specifically is covered in the linked duplicate. – Peter Cordes Feb 09 '20 at 05:29
  • Also, you clearly didn't copy-paste this because `movq #0, %rax` is a syntax error. Maybe you meant `$0` again? Hmm, this looks a lot like GCC output, but it's not. A compiler would have used `mov $0, %eax`, not a larger `movq $0, %eax`, and GCC would use `pop %rbp` instead of `leave` in a function where it didn't move RSP after setting up RBP as a frame pointer. Also, the string literal is in `.data` instead of `.rodata`. So it looks like someone took GCC's label names and un-optimized output then made it even worse. – Peter Cordes Feb 09 '20 at 05:32
  • hi Peter, It my wrong, it's should be movq $0, %rax, thank you. And the second code is from NASM code. – Zhang Jason Feb 09 '20 at 05:44

0 Answers0