From f981835e44e17a58c438a53a1ae32de7de3273c2 Mon Sep 17 00:00:00 2001 From: Stefan Arentz Date: Mon, 21 Nov 2016 20:47:27 -0500 Subject: [PATCH] Fixes #31 - Allow RAM images to be loaded from disk --- cpu.c | 34 +++++++++++++++++++++++++++++++++- cpu.h | 4 +++- 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/cpu.c b/cpu.c index 8313f74..e438f6a 100644 --- a/cpu.c +++ b/cpu.c @@ -221,9 +221,13 @@ static void _ram_write(struct cpu_t *cpu, struct mem_t *mem, uint16_t addr, uint } void cpu_add_ram(struct cpu_t *cpu, uint16_t start, uint16_t length) { + cpu_add_ram_data(cpu, start, length, calloc(length, 0x01)); +} + +void cpu_add_ram_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_RAM; - mem->obj = malloc(length); + mem->obj = data; mem->start = start; mem->length = length; mem->read_handler = _ram_read; @@ -232,6 +236,34 @@ void cpu_add_ram(struct cpu_t *cpu, uint16_t start, uint16_t length) { cpu_add_mem(cpu, mem); } +void cpu_add_ram_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_ram_data(cpu, start, file_info.st_size, (uint8_t*) data); +} + // ROM Memory static uint8_t _rom_read(struct cpu_t *cpu, struct mem_t *mem, uint16_t addr) { diff --git a/cpu.h b/cpu.h index 488cd59..aca5a28 100644 --- a/cpu.h +++ b/cpu.h @@ -83,8 +83,10 @@ void cpu_shutdown(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_file(struct cpu_t *cpu, uint16_t start, char *path); +void cpu_add_ram_data(struct cpu_t *cpu, uint16_t start, uint16_t length, uint8_t *data); +void cpu_add_ram_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_rom_file(struct cpu_t *cpu, uint16_t start, char *path); 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_strict(struct cpu_t *cpu, bool strict);