mirror of https://github.com/Nonannet/copapy.git
85 lines
2.1 KiB
C
85 lines
2.1 KiB
C
/*
|
|
* file: coparun.c
|
|
* Description: This file alows to run copapy programs in the command line
|
|
* reading copapy data, code and patch instructions from a file and jump to the
|
|
* entry point to execute it or dump the patched code memory for debugging to a file.
|
|
*
|
|
* It's intended for testing and debugging purposes, to run copapy programs in a
|
|
* debugger or emulator like qemu.
|
|
*
|
|
* Usage: coparun <code_file> [memory_dump_file]
|
|
*/
|
|
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include "runmem.h"
|
|
#include "mem_man.h"
|
|
|
|
int main(int argc, char *argv[]) {
|
|
if (argc < 2) {
|
|
fprintf(stderr, "Usage: %s <code_file>\n", argv[0]);
|
|
return EXIT_FAILURE;
|
|
}
|
|
|
|
FILE *f = fopen(argv[1], "rb");
|
|
if (!f) {
|
|
perror("fopen");
|
|
return EXIT_FAILURE;
|
|
}
|
|
|
|
/* Determine file size */
|
|
if (fseek(f, 0, SEEK_END) != 0) {
|
|
perror("fseek");
|
|
fclose(f);
|
|
return EXIT_FAILURE;
|
|
}
|
|
long sz = ftell(f);
|
|
if (sz < 0) {
|
|
perror("ftell");
|
|
fclose(f);
|
|
return EXIT_FAILURE;
|
|
}
|
|
rewind(f);
|
|
|
|
if (sz == 0) {
|
|
fprintf(stderr, "Error: File is empty\n");
|
|
fclose(f);
|
|
return EXIT_FAILURE;
|
|
}
|
|
|
|
uint8_t *file_buff = allocate_buffer_memory((uint32_t)sz);
|
|
|
|
/* Read file into allocated memory */
|
|
size_t nread = fread(file_buff, 1, (size_t)sz, f);
|
|
fclose(f);
|
|
if (nread != (size_t)sz) {
|
|
perror("fread");
|
|
return EXIT_FAILURE;
|
|
}
|
|
|
|
runmem_t targ;
|
|
targ.executable_memory_len = 0;
|
|
targ.data_memory_len = 0;
|
|
targ.executable_memory = NULL;
|
|
targ.data_memory = NULL;
|
|
targ.entr_point = NULL;
|
|
targ.data_offs = 0;
|
|
|
|
int ret = parse_commands(&targ, file_buff);
|
|
|
|
if (ret == 2) {
|
|
/* Dump code for debugging */
|
|
if (argc != 3) {
|
|
fprintf(stderr, "Usage: %s <code_file> <memory_dump_file>\n", argv[0]);
|
|
return EXIT_FAILURE;
|
|
}
|
|
f = fopen(argv[2], "wb");
|
|
fwrite(targ.executable_memory, 1, (size_t)targ.executable_memory_len, f);
|
|
fclose(f);
|
|
}
|
|
|
|
free_memory(&targ);
|
|
|
|
return ret < 0;
|
|
}
|