exit() instead of ret in main

This commit is contained in:
janis 2025-10-16 19:14:28 +02:00
parent 3d4cfc8e2b
commit 7bc428caf3
Signed by: janis
SSH key fingerprint: SHA256:bB1qbbqmDXZNT0KKD5c2Dfjg53JGhj7B3CFcLIzSqq8

View file

@ -1,7 +1,6 @@
;; Compile with:
;; nasm -f elf64 main.asm -o main.o
;; RO section
section .data
hello_msg db "Hello, World!", 10
hello_msg_len equ $ - hello_msg
@ -32,7 +31,10 @@ _start:
mov rdx, rax ; filename pointer
call fopen_read
mov rax, 42
ret
; exit with success
mov rdi, 0 ; status:
mov rax, 60 ; syscall: exit
syscall
.no_filename:
call die
@ -54,9 +56,7 @@ die:
;; Writes a string to stderr:
;; rdx: pointer to string
;; rcx: length of string
eprint_str: ; print string-length pair to stderr
; str pointer in rdx
; length in rcx
eprint_str:
mov rax, 1 ; syscall: write
mov rdi, 2 ; fd: stderr
mov rsi, rdx ; buf: str
@ -93,7 +93,7 @@ memcpy:
ret
;; Opens file for reading:
;; rdx: pointer to filename (null-terminated)
;; rdx: pointer to filename (null-terminated)
fopen_read:
mov rax, 2 ; syscall: open
mov rdi, rdx ; filename
@ -103,42 +103,43 @@ fopen_read:
cmp rax, 0
jl .file_error
ret ;fd in rax
.file_error:
; allocate stack space for error message
mov rdx, rdi ; filename is in rdi
call strlen ; get length of filename
mov r9, rax
mov r9, rax ; r9 = filename length
mov rsi, r9
add rsi, file_error_msg_len ; add length of error message prefix
add rsi, 1 ; for new line
; align to 16 bytes
add rsi, file_error_msg_len ; + prefix
add rsi, 1 ; + newline
add rsi, 15
and rsi, -16
sub rsp, rsi ; alloca
push rsi ; save length for dealloca
and rsi, -16 ; align up to 16
sub rsp, rsi ; allocate buffer
push rsi ; save allocation size
; copy file_error_msg
lea rdx, [rsp + 8]
mov rcx, file_error_msg
mov r8, file_error_msg_len
call memcpy
; copy filename
lea rdx, [rsp + 8 + file_error_msg_len]
mov rcx, rdi
mov r8, r9
call memcpy
; trailing newline
lea rdx, [rsp + 8 + file_error_msg_len + r9]
mov byte [rdx], 10
; print error message
lea rdx, [rsp + 8]
mov rcx, r9
add rcx, file_error_msg_len
add rcx, 1
mov rcx, file_error_msg_len
add rcx, r9
add rcx, 1 ; include newline
call eprint_str
pop rsi
add rsp, rsi ; dealloca
add rsp, rsi ; dealloc
ret