;write_file.asm
;creat open write close, hard-coded 

section .data
LF equ 10            ;\n
NULL equ 0           ;terminate the string
TRUE equ 1
FALSE equ 0
EXIT_SUCCESS equ 0
STDIN equ 0
STDOUT equ 1
STDERR equ 2
SYS_read equ 0
SYS_write equ 1
SYS_open equ 2
SYS_close equ 3
SYS_fork equ 57
SYS_exit equ 60
SYS_creat equ 85
SYS_time equ 201
O_CREAT equ 0x40
O_TRUNC equ 0x200
O_APPEND equ 0x400
O_RDONLY equ 0q       ;q=octal
O_WRONLY equ 1q
O_RDWR equ 2q
S_IRUSR equ 400q      ; owner, read permission
S_IWUSR equ 200q      ; owner, write permission
S_IXUSR equ 100q      ; owner, execute permission

newline db LF, LF, NULL
header db LF, "file write test", LF, NULL
filename db "url.txt", NULL
url db "/home/rnzuser/Scrivania", LF, NULL
len dq $-url-1
writedone db "scrittura completata!", LF, NULL
filedescript dq 0
erroropenmsg db "errore nell'apertura del file ", LF, NULL
errorwritemsg db "fiile writing error", LF, NULL

Section .text
global _start
_start:

mov rdi, header 
call printstring


mov rdi, header
call printstring



; -----
; Attempt to open file.
; rax = SYS_creat (file open/create)
; rdi = address of file name string
; rsi = attributes (i.e., read only, etc.)
; Returns: if error -> eax < 0
; if success -> eax = file descriptor number
; The file descriptor points to the FCB File Control Block
; the file descriptor is used for all subsequent
; file operations (read, write, close).

openinputfile:
mov rax, SYS_creat
mov rdi, filename 
mov rsi, S_IRUSR | S_IWUSR     ;allow ownerr read/write
syscall

cmp rax, 0
jl erroronopen  ; if rax<0, signed data, jb unsigned data

mov qword[filedescript], rax   ;save descriptor 
 
; -----
; Write to file.
; In this example, the characters to write are in a
; predefined string containing a URL.
; rax = SYS_write
; rdi = file descriptor
; rsi = address of characters to write
; rdx = count of characters to write
; Returns: if error -> rax < 0
; if success -> rax = count of characters actually read

mov rax, SYS_write
mov rdi, qword[filedescript]
mov rsi, url
mov rdx, qword[len]
syscall

cmp rax, 0
jl erroronwrite

mov rdi, writedone
call printstring

; -----
; Close the file.
; rax = SYS_close
; rdi = file descriptor

mov rax, SYS_close
mov rdi, qword[filedescript]
syscall

jmp FATTO

erroronopen:
mov rdi, erroropenmsg
call printstring

jmp FATTO

erroronwrite:
mov rdi, errorwritemsg
call printstring

jmp FATTO

FATTO:
mov rax, SYS_exit
mov rdi, EXIT_SUCCESS 
syscall



global printstring
printstring:

push rbp
mov rbp, rsp
push rbx

; count characters in string
mov rbx, rdi   
mov rdx, 0
stringcountloop:
cmp byte[rbx], NULL
je stringcountdone
inc rdx
inc rbx
jmp stringcountloop

stringcountdone
cmp rdx, 0
je printdone

;call OS to output string

mov rax, SYS_write    ; to output characters to the console 
mov rsi, rdi          ; address of characters
mov rdi, STDOUT       ; File Descriptor to write characters in the console
syscall

printdone:
pop rbx
pop rbp
ret






