From d45f882710896eb52445107cf36616baef67efcc Mon Sep 17 00:00:00 2001 From: Bill Rossi Date: Thu, 21 Dec 2023 09:47:43 -0500 Subject: [PATCH] Factor out file-loading logic --- fasm/2015/1/problem.asm | 22 ++++------------------ fasm/lib/file.inc | 27 +++++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 18 deletions(-) create mode 100644 fasm/lib/file.inc diff --git a/fasm/2015/1/problem.asm b/fasm/2015/1/problem.asm index bc02954..ca25292 100644 --- a/fasm/2015/1/problem.asm +++ b/fasm/2015/1/problem.asm @@ -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 diff --git a/fasm/lib/file.inc b/fasm/lib/file.inc new file mode 100644 index 0000000..3c6978a --- /dev/null +++ b/fasm/lib/file.inc @@ -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 \ No newline at end of file