4

How to tell NASM (or LD) to process labels in a way that will make the segment position-independent?

The segment is going to be moved from one file to another and I want it to work properly on any position in any file.

Here is the code that illustrates my problem:

section .text
...
message: db 'hello world!',0x00
...
mov rax,SYSCALL_WRITE
mov rdi,STDOUT
mov rsi,message
mov rdx,13
syscall

In the orginal executable it prints "Hello world!", but when the segment is moved to another elf, it prints some random bytes.

rkhb
  • 14,159
  • 7
  • 32
  • 60
Hugo
  • 183
  • 5
  • Can You post some code ? As I might remember, Your code has to deal with that. Like stated here: http://l4u-00.jinr.ru/usoft/WWW/www_debian.org/Documentation/elf/node21.html – icbytes Dec 15 '15 at 12:08
  • 3
    Use `lea rsi, [rel message]` optionally add `default rel` at the top in which case you can do `lea rsi, [message]`. – Jester Dec 15 '15 at 12:24
  • Thanks Jester, it works! – Hugo Dec 15 '15 at 12:28
  • 1
    @Hugo: I tried to address this and other issues in my answer on http://stackoverflow.com/questions/34058101/referencing-the-contents-of-a-memory-location-x86-addressing-modes. See http://stackoverflow.com/tags/x86/info for other helpful stuff. – Peter Cordes Dec 17 '15 at 01:10
  • @PeterCordes I wasn't exactly sure what I was searching for so I didn't find your post, but it's fantastic, thanks a lot! – Hugo Dec 17 '15 at 06:33
  • @Hugo: thanks. I have plans to split out (into a separate question) the part about using LEA and how garbage in upper bits doesn't matter, since that's getting a bit off topic. Feedback (on any part) from a person trying to understand this for the first time would be helpful. It's been a while since I didn't already understand a lot of the background, so it can be hard to know what's obvious to other people (and what's useful and what's clutter.) – Peter Cordes Dec 17 '15 at 06:45

0 Answers0