I just started learning nasm on macos and I’m having problems with it when using addressing.
Here’s the task I’m trying to complete: “remove words starting with a given character from the source string.”
Here’s the code I wrote:
section .data
source db 'apple banana cat dog elephant',0 ; Original string
dest db 1000 dup(0) ; Buffer for the resulting string
delimiter db ' ',0 ; Word delimiter
to_remove db 'c' ; Character to remove words starting with
section .text
global _start
_start:
; Pointers to the beginning of the source and resulting strings
mov rsi, source
mov rdi, dest
; Check for end of the source string
next_word:
mov al, byte [rsi]
cmp al, 0
je end_program
; Read the next word
mov rbx, rsi
mov rax, rsi
mov rcx, 0
jmp check_delimiter
read_word:
inc rsi
inc rcx
check_delimiter:
; Check for end of the source string
mov al, byte [rsi]
cmp al, 0
je end_program
mov al, byte [rsi]
cmp al, delimiter
jne read_word
; Check for end of the source string after the delimiter
mov al, byte [rsi]
cmp al, 0
je end_program
; Check if the word starts with the character to remove
mov al, byte [rbx]
cmp al, 'c'
je skip_word
; Copy the word to the resulting string
mov rdx, rcx
mov rsi, rbx
mov rdi, rax
copy_word:
mov al, byte [rsi]
mov byte [rdi], al
inc rsi
inc rdi
cmp rsi, rdx
jl copy_word
; Add a space if it's not the last word
mov al, byte [rbx + rcx]
cmp al, 0
je end_program
mov byte [rdi], ' '
inc rdi
skip_word:
; Skip the word in the source string
mov rsi, rcx
; Move to the next word
jmp next_word
end_program:
; Print the result to the console
mov rax, 0x2000004 ; System call for printing a string
mov rdi, rax ; File descriptor (stdout)
mov rsi, dest ; Pointer to the beginning of the string
xor rdx, rdx ; Length of the string (initially 0)
calculate_length:
inc rdx
mov al, byte [rsi + rdx]
cmp al, 0
jne calculate_length
; System call for printing a string
mov rax, 0x2000004
mov rdi, rax ; File descriptor (stdout)
mov rsi, dest ; Pointer to the beginning of the string
mov rdx, rdx ; Length of the string
syscall
; Exit the program
mov rax, 0x2000001
xor rdi, rdi
syscall
I tried different ways to change the addressing code, but I kept getting errors:
1)Mach-O 64-bit format does not support 32-bit absolute addresses
2)zsh: segmentation fault ./main
3)bus error
system: macos big sur, Intel processor.
compilation string:
nasm -f macho64 main.asm -o main.o;
ld -o main main.o -arch x86_64 -l System -syslibroot xcrun -sdk macosx --show-sdk-path
-e _start;
./main
I will be glad for any help.