Skip to content

Instantly share code, notes, and snippets.

@phoemur
Created July 9, 2023 21:51
Show Gist options
  • Save phoemur/2355f8e8a3f7b562a04614f916faf6a8 to your computer and use it in GitHub Desktop.
Save phoemur/2355f8e8a3f7b562a04614f916faf6a8 to your computer and use it in GitHub Desktop.
Simple program emulating UNIX cat
; Simple program emulating UNIX cat
;
; Assembler: YASM
;
; Fernando Giannasi
; July 09, 2023
section .data
SYS_EXIT equ 60
SYS_READ equ 0
SYS_WRITE equ 1
SYS_OPEN equ 2
SYS_CLOSE equ 3
STD_OUT equ 1
O_RDONLY equ 0
EXIT_SUCCESS equ 0
BUFFER_SIZE equ 256
errorMsg db "Usage: ./cat <filename_1> ... <filename_n>",10,0
errorMsgLen equ $ - errorMsg
errorMsg2 db "Error opening the file",10,0
errorMsg2Len equ $ - errorMsg2
section .bss
buffer resb BUFFER_SIZE
section .text
global _start
%macro printMacro 2
mov rsi, %1
mov rdx, %2
mov rax, SYS_WRITE
mov rdi, STD_OUT
syscall
%endmacro
_start:
; check args (argc >= 2)
pop rcx
cmp rcx, 2
jl _error
mov r15, rcx
_outerloopRW:
dec r15
cmp r15, 0
je _sysExit ; exit outerloop
; get filename, open read-mode and check
mov rax, SYS_OPEN
pop rdi
pop rdi
mov rsi, O_RDONLY
mov rdx, 0
syscall
push rax
cmp rax, 0
jle _filerror
; read from file
_innerloopRW:
mov rdi, [rsp]
mov rax, SYS_READ
mov rsi, buffer
mov rdx, BUFFER_SIZE
syscall
; check number of bytes read, exit innerloop if 0
cmp rax, 0
je _outerloopRW
; print
printMacro buffer, rax
jmp _innerloopRW
_sysExit:
mov rax, SYS_EXIT
mov rdi, EXIT_SUCCESS
syscall
ret
_error:
printMacro errorMsg, errorMsgLen
call _sysExit
_filerror:
printMacro errorMsg2, errorMsg2Len
call _sysExit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment