From 43fcbc5def9896a17450292509850829146c7c66 Mon Sep 17 00:00:00 2001
From: Christian Cunningham <cc@localhost>
Date: Sat, 13 Jul 2024 21:32:41 -0700
Subject: Basic file handling

---
 file.inc | 111 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 111 insertions(+)
 create mode 100644 file.inc

diff --git a/file.inc b/file.inc
new file mode 100644
index 0000000..3415c4f
--- /dev/null
+++ b/file.inc
@@ -0,0 +1,111 @@
+%ifndef FILE_INC
+%define FILE_INC
+%define FBUF_DEFAULT_SIZE 1024*32
+%ifndef SYS_INC
+%include "sys.inc"
+%endif
+%ifndef ALLOC_INC
+%include "alloc.inc"
+%endif
+%ifndef ZSTRING_INC
+%include "zstring.inc"
+%endif
+
+struc FileData
+fname:	resq	1
+buffer:	resq	1
+size:	resq	1
+fd:	resq	1
+endstruc
+
+%macro make_fbuffer 3
+	;; %1 = File Name
+	;; %2 = Buffer Name
+	;; %3 = Buffer Size
+	section .data
+%2_fname:	db %1,0
+%2_buffer:	times %3 db 0
+%2_bufferLen:	equ $ - %2_buffer
+	db 0
+	section .bss
+%2_fd:	resq 1
+	section .data
+%2_filedata:
+	istruc FileData
+	at	fname,	dq	%2_fname
+	at	buffer,	dq	%2_buffer
+	at	size,	dq	%2_bufferLen
+	at	fd,	dq	%2_fd
+	iend
+%endm
+
+%macro fopen 1
+	mov	rax,	SYS_OPEN
+	lea	rdi,	[rel %1_fname]
+	xor	rsi,	rsi	; READ-ONLY
+	syscall
+	mov	[rel %1_fd],	rax
+%endm
+
+%macro flen 1
+	mov	rax,	SYS_LSEEK
+	mov	rdi,	[rel %1_fd]
+	mov	rsi,	0
+	mov	rdx,	2
+	syscall
+%endm
+
+%macro fbegin 1
+	mov	rax,	SYS_LSEEK
+	mov	rdi,	[rel %1_fd]
+	mov	rsi,	0
+	mov	rdx,	0
+	syscall
+%endm
+
+%macro fread 1
+	mov	rax,	SYS_READ
+	mov	rdi,	[rel %1_fd]
+	lea	rsi,	[rel %1_buffer]
+	mov	rdx,	%1_bufferLen
+	syscall
+%endm
+
+%macro fclose 1
+	mov	rax,	SYS_CLOSE
+	mov	rdi,	[rel %1_fd]
+	syscall
+%endm
+
+ffopen:
+	push	rbp
+	mov	rbp,	rsp
+	;; RAX = filedata
+	push	rax
+	mov	rdi,	[rax + fname]
+	mov	rax,	SYS_OPEN
+	xor	rsi,	rsi
+	syscall
+	pop	rdx
+	mov	rcx,	rdx
+	mov	rdx,	[rdx + fd]
+	mov	[rdx],	rax
+	mov	rax,	rcx
+	;;
+	mov	rsp,	rbp
+	pop	rbp
+	ret
+
+print_filedata:
+	push	rbp
+	mov	rbp,	rsp
+	;; RAX = filedata
+	push	rax
+	mov	rax,	[rax + buffer]
+	call	print_zstring
+	pop	rax
+	mov	rsp,	rbp
+	pop	rbp
+	ret
+
+%endif
-- 
cgit v1.2.1