0

I have the following program to print a number in assembly:

.section .rodata
format: .ascii "Your number is: %d.\n\0"
.section .text
.globl main
main:
    lea format(%rip), %rdi
    mov $55, %rsi
    mov $0, %eax
    sub $8, %rsp
    call printf
    add $8, %rsp
    mov $0, %eax
    ret

And it works fine when being compiled via gcc on ubuntu with -no-pie:

ubuntu$ gcc -no-pie int.s -o int; ./int
Your number is: 55.

However, when I remove -no-pie it jumps to the wrong address for the printf statement. Single-stepping in gdb shows that when it does the call printf instruction it returns something along the lines of:

Cannot access memory at address 0x5554f7a48f00

Or, running it directly from the command-line I get:

$ gcc int.s -o int; ./int ./int: Symbol `printf' causes overflow in R_X86_64_PC32 relocation

Why does this occur, and how would I make the above program work without -no-pie in the command-line?

carl.hiass
  • 1,526
  • 1
  • 6
  • 26
  • Can't reproduce on Ubuntu 20.04. – Nate Eldredge Mar 26 '21 at 00:11
  • `call printf@plt`. It's strange you get a runtime error instead of compile time which I do. – Jester Mar 26 '21 at 00:11
  • @Jester yea, that works. Thank you. Want to post an answer showing what that does and what my error was without it? – carl.hiass Mar 26 '21 at 00:12
  • We'll just wait for Peter to show up and find the duplicate LOL – Jester Mar 26 '21 at 00:13
  • 1
    @Jester here's a good one actually: https://stackoverflow.com/a/5469334/12283181. The problem with duplicates is I don't know anything about `plt` before asking the question so I wouldn't know to look it up...that happens for a lot of dupes I'm guessing. – carl.hiass Mar 26 '21 at 00:13
  • 1
    My gcc seems to link to `printf@plt` all by itself without needing to be told. Maybe your version does not for some reason. – Nate Eldredge Mar 26 '21 at 00:14
  • @Jester by implication, would all C-runtime functions called in assembly without `-no-pie` require the `@plt` suffix? – carl.hiass Mar 26 '21 at 00:15
  • 1
    Not just C runtime, any shared library function. – Jester Mar 26 '21 at 00:27
  • @carl.hiass Generally speaking, you aren't doing anything wrong if you route calls to any external functions through the PLT. – fuz Mar 26 '21 at 14:14

0 Answers0