From 6e0eaaa5be9bf8ded632007a88629c3ae13cfd02 Mon Sep 17 00:00:00 2001 From: Stefan Arentz Date: Wed, 16 Nov 2016 15:28:35 -0500 Subject: [PATCH] Fixes #19 - Allow ROM regions to be loaded from files --- cpu.c | 33 +++++++++++++++++++++++++++++++-- cpu.h | 3 ++- 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/cpu.c b/cpu.c index cc0f3a0..b3795a6 100644 --- a/cpu.c +++ b/cpu.c @@ -21,13 +21,14 @@ // SOFTWARE. #include +#include #include #include #include #include #include #include - +#include #include #include @@ -351,7 +352,7 @@ static uint8_t _rom_read(struct cpu_t *cpu, struct mem_t *mem, uint16_t addr) { return ((uint8_t*) mem->obj)[addr - mem->start]; } -void cpu_add_rom(struct cpu_t *cpu, uint16_t start, uint16_t length, uint8_t *data) { +void cpu_add_rom_data(struct cpu_t *cpu, uint16_t start, uint16_t length, uint8_t *data) { struct mem_t *mem = (struct mem_t*) malloc(sizeof(struct mem_t)); mem->type = MEM_TYPE_ROM; mem->obj = data; @@ -363,6 +364,34 @@ void cpu_add_rom(struct cpu_t *cpu, uint16_t start, uint16_t length, uint8_t *da cpu_add_mem(cpu, mem); } +void cpu_add_rom_file(struct cpu_t *cpu, uint16_t start, char *path) { + int fd = open(path, O_RDONLY); + if (fd == -1) { + return; + } + + struct stat file_info; + if (fstat(fd, &file_info) == -1) { + close(fd); + return; + } + + if (file_info.st_size > (64 * 1024 - start)) { + close(fd); + return; + } + + char *data = malloc(file_info.st_size); + if (read(fd, data, file_info.st_size) != file_info.st_size) { + close(fd); + return; + } + + close(fd); + + cpu_add_rom_data(cpu, start, file_info.st_size, (uint8_t*) data); +} + // IO Memory void cpu_add_iom(struct cpu_t *cpu, uint16_t start, uint16_t length, void *obj, mem_read_handler_t read_handler, mem_write_handler_t write_handler) { diff --git a/cpu.h b/cpu.h index 15cd995..d889f64 100644 --- a/cpu.h +++ b/cpu.h @@ -73,7 +73,8 @@ void cpu_init(struct cpu_t *cpu); void cpu_add_mem(struct cpu_t *cpu, struct mem_t *mem); void cpu_add_ram(struct cpu_t *cpu, uint16_t start, uint16_t length); -void cpu_add_rom(struct cpu_t *cpu, uint16_t start, uint16_t length, uint8_t *data); +void cpu_add_rom_file(struct cpu_t *cpu, uint16_t start, char *path); +void cpu_add_rom_data(struct cpu_t *cpu, uint16_t start, uint16_t length, uint8_t *data); void cpu_add_iom(struct cpu_t *cpu, uint16_t start, uint16_t length, void *obj, mem_read_handler_t read_handler, mem_write_handler_t write_handler); void cpu_trace(struct cpu_t *cpu, uint8_t trace);