I want to study NASM x86 assembly language on my macOS Monterey 12.1.
MY code is as below:
SECTION .data
msg db 'Hello World!', 0Ah ; assign msg variable with your message string
SECTION .text
global _start
_start:
mov edx, 13 ; number of bytes to write - one for each letter plus 0Ah (line feed character)
mov ecx, msg ; move the memory address of our message string into ecx
mov ebx, 1 ; write to the STDOUT file
mov eax, 4 ; invoke SYS_WRITE (kernel opcode 4)
int 80h
After I input the command:
nasm -f macho64 -o helloworld.o helloworld.asm
I will get:
helloworld.asm:15: error: Mach-O 64-bit format does not support 32-bit absolute addresses
Is there any solutions to solve it?
CodePudding user response:
The addressing space used for macho64 is x86-64, so the registers are a different size which can handle 64-bit addressing. ECX for example is 32 bits, and you try to load it with a 64 bit address, causing the error.
This is what the Hello World code looks like for x86-64:
global _main
SECTION .data
msg db 'Hello World!', 0x0A ; assign msg variable
SECTION .text
_main:
mov rdx, 13 ; number of bytes to write - one for each letter plus LF char.
lea rsi, [rel msg] ; move the memory address of our message string into rsi
mov rdi, 1 ; write to the STDOUT file
mov rax, 0x2000004 ; invoke SYS_WRITE (kernel opcode 4)
syscall
mov rax, 0x2000001 ; exit
mov rdi, 0
syscall
Compiled, linked, executed:
% nasm -f macho64 -o helloworld.o helloworld.asm
% ld helloworld.o -o hello -lSystem -L/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/lib
% ./hello
Hello World!
