Factor out file-loading logic

This commit is contained in:
Bill Rossi 2023-12-21 09:47:43 -05:00
parent 47c1398c6d
commit d45f882710
2 changed files with 31 additions and 18 deletions

View File

@ -2,31 +2,20 @@ format ELF64 executable 3
include "lib/linux_syscall.inc"
include "lib/itoa.inc"
include "lib/print.inc"
include "lib/file.inc"
segment readable executable
entry main
main:
;; Determine the file size of the input file
stat input_filename, file_stat
;; Open a file descriptor for the input file
open input_filename, 0
mov [input_fd], rax
;; Map the input file into memory
mmap 0, [file_stat.st_size], PROT_READ, MAP_PRIVATE, [input_fd], 0
mov [input], rax
;; Close the input file
close [input_fd]
mov rdi, input_filename
call load_file
call part_1
call part_2
;; Unmap the mapped file
munmap [input], [file_stat.st_size]
call unload_file
;; Done!
exit 0
@ -118,10 +107,7 @@ part_2:
segment readable writable
input_filename db '../data/2015/1/input.txt', 0
input_fd dq -1
input dq -1
part_1_verbiage db 'Part 1: '
part_1_answer db ' ', 0
part_2_verbiage db 'Part 2: '
part_2_answer db ' ', 0
file_stat s_stat

27
fasm/lib/file.inc Normal file
View File

@ -0,0 +1,27 @@
input_fd dq -1
input dq -1
file_stat s_stat
;;; The input filename should be in rdi
load_file:
mov r8, rdi
;; Determine the file size of the input file
stat r8, file_stat
;; Open a file descriptor for the input file
open r8, 0
mov [input_fd], rax
;; Map the input file into memory
mmap 0, [file_stat.st_size], PROT_READ, MAP_PRIVATE, [input_fd], 0
mov [input], rax
;; Close the input file
close [input_fd]
ret
unload_file:
;; Unmap the mapped file
munmap [input], [file_stat.st_size]
ret