2

I am trying to create a dylib from objects file assembled with NASM, but I get the following error:

ld: illegal text-relocation to 'newline' in objects/ft_puts.o from '_ft_puts' in objects/ft_puts.o for architecture x86_64

Here is my ft_puts.s:

SYS_WRITE   equ 0x2000004
STDOUT      equ 1

section .data
    newline db 10

section .text
    global _ft_puts

_ft_puts:
    push rbp
    mov rbp, rsp
    mov rdx, rdi ; save address of str to print

    ; calculate len of string pointed by rdi
    mov rcx, -1
    xor rax, rax
    repnz scasb
    not rcx
    push rcx ; save string length (+1 for the '\n' to add)
    dec rcx
    ; print the string
    mov rax, SYS_WRITE
    mov rdi, STDOUT
    mov rsi, rdx
    mov rdx, rcx
    syscall
    ; print the \n
    mov rax, SYS_WRITE
    mov rsi, newline
    mov rdx, 1
    syscall

    pop rax
return:
    pop rbp
    ret

and here is my makefile:

$(LIB): $(OBJECTS)
    gcc -dynamiclib -o $@ $(addprefix $(OBJECTS_D), $^)
    # ranlib $@

%.o: $(SOURCES_D)%.s
    $(NASM) $^ -o $(OBJECTS_D)$@

I am on macOS Sierra 10.12.6, NASM version 2.13.03.
I don't know how to fix that, so if anyone could help, and also explain where this error comes from? Thanks.

zx485
  • 28,498
  • 28
  • 50
  • 59
Stephane
  • 153
  • 1
  • 10
  • 5
    Change `mov rsi, newline` to `lea rsi, [rel newline]` to produce position independent code. PS: it might be a good idea to put that into a read-only section or even just create it on the stack as needed. – Jester Nov 02 '18 at 19:28
  • Related: [Mach-O 64-bit format does not support 32-bit absolute addresses. NASM Accessing Array](https://stackoverflow.com/q/47300844) for more detail on LEA. But unlike an executable, a shared library can't use `mov r64, imm64` with a 64-bit absolute address: OS X apparently won't do text relocations to fix up absolute addresses when loading libraries to arbitrary virtual addresses. – Peter Cordes Nov 02 '18 at 22:11
  • thanks guys, i still have trouble to picture how memory works, like virtual memory, and stuff like that. But problem fixed. – Stephane Nov 03 '18 at 16:25

0 Answers0