JohnDDuncanIII/fasm

Hello64 Linking

CharlesBunders opened this issue · 2 comments

I am running OS X version 10.11.6. I get the following error when linking the example.

$ ld -arch x86_64 -macosx_version_min 10.6 -o hello64 hello64_m.o /usr/lib/crt1.o /usr/lib/libc.dylib
ld: illegal text-relocation to '.data' in hello64_m.o from '_main' in hello64_m.o for architecture x86_64

Hey. I'm not sure why it's failing to link. I no longer own a working MacBook, but I will be able to use one to test this in a week or so. In the mean time, I will look into what could be causing the error.

Using lea instead of mov for filling rsi resolves the problem. Because of the "zero pages", addresses are too big to fit in 32 bits. Address field for some instructions are 32 bits, so addressing should be "rip relative". In the following code, the lea instruction points to msgHelloWorld relatively to rip register.

Depending on how you convert the object file, you don't even need to link against crt or libc.

fasm HelloWorld.asm HelloWorld.elf.o
objconv -fmacho64 -ar:start:_start -nu HelloWorld.elf.o HelloWorld.macho64.o
ld -arch x86_64 -macosx_version_min 10.6 -o HelloWorld HelloWorld.macho64.o


format ELF64

define SYSCALL_WRITE 0x2000004
define SYSCALL_EXIT 0x2000001

; macro for create .size constant automatically

struc db [data]{
common
. db data
.size = $ - .
}

section '.data' writeable

msgHelloWorld db 'Hello 64bit World from FASM!',0x0A,0

section '.text' executable

public start

start:
mov rax, SYSCALL_WRITE
mov rdi, 1 ; stdout
lea rsi, [msgHelloWorld] ; string
mov rdx, msgHelloWorld.size ; length
syscall

mov rax, SYSCALL_EXIT ; sys_exit
xor rdi, rdi ; exit code
syscall