From 2b6ebadac229b36056c4edf8bc6df1bac142dfc8 Mon Sep 17 00:00:00 2001 From: Zoe Roux Date: Wed, 31 May 2023 14:16:00 +0900 Subject: [PATCH] Parse arguments --- .gitignore | 2 ++ Makefile | 3 ++- src/dasm.c | 20 ++++++++++++++++++++ src/dasm.h | 6 ++++++ src/main.c | 50 ++++++++++++++++++++++++++++++++++++++++++++++++-- 5 files changed, 78 insertions(+), 3 deletions(-) create mode 100644 src/dasm.c create mode 100644 src/dasm.h diff --git a/.gitignore b/.gitignore index be69536..fce30e4 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,4 @@ setuptools ._setuptools +*.o +dasm diff --git a/Makefile b/Makefile index 60cefa4..5b959a3 100644 --- a/Makefile +++ b/Makefile @@ -2,7 +2,8 @@ NAME = dasm CFLAGS = -Wall -Wextra -Wshadow LDFLAGS = -SRC = src/main.c +SRC = src/main.c \ + src/dasm.c OBJ = $(SRC:%.c=%.o) diff --git a/src/dasm.c b/src/dasm.c new file mode 100644 index 0000000..d029e7a --- /dev/null +++ b/src/dasm.c @@ -0,0 +1,20 @@ +#include +#include +#include "dasm.h" + +void print_instruction(unsigned addr) +{ + printf("%X\n", addr); +} + +int dasm(char *binary) +{ + int pc = 0; + + while (*binary) { + instruction_t inst = *binary; + print_instruction(pc); + pc += inst.size; + } + return 0; +} diff --git a/src/dasm.h b/src/dasm.h new file mode 100644 index 0000000..5da5f6f --- /dev/null +++ b/src/dasm.h @@ -0,0 +1,6 @@ +int dasm(char *binary); + +typedef struct instruction { + const char *name; + unsigned size; +} instruction_t; diff --git a/src/main.c b/src/main.c index c69349d..ed43cfb 100644 --- a/src/main.c +++ b/src/main.c @@ -1,4 +1,50 @@ -int main() +#include +#include +#include +#include "dasm.h" + +char *open_and_read(char *path) { - + FILE *file = fopen(path, "r"); + if (!file) { + dprintf(2, "Invalid path: %s. File does not exist.\n", path); + return NULL; + } + + int rc = fseek(file, 0L, SEEK_END); + if (rc != 0) { + fclose(file); + return NULL; + } + long size = ftell(file); + if (size == -1) { + fclose(file); + return NULL; + } + rewind(file); + + char *ret = malloc((size + 1) * sizeof(char)); + size = fread(ret, sizeof(char), size, file); + ret[size] = '\0'; + + fclose(file); + return ret; +} + +int main(int argc, char **argv) +{ + if (argc != 3 || strcmp(argv[1], "-d")) { + printf("Usage: %s -d \n", argv[0]); + return 2; + } + + char *binary = open_and_read(argv[2]); + if (!binary) { + puts("Could not read binary file."); + return 2; + } + + int ret = dasm(binary); + free(binary); + return ret; }