From fe8804c8d8e649159bd0fd506785fe17c16119a9 Mon Sep 17 00:00:00 2001 From: Henrik Hautakoski Date: Wed, 31 Oct 2018 17:52:21 +0100 Subject: [PATCH] add program module --- src/program.c | 45 +++++++++++++++++++++++++++++++++++++++++++++ src/program.h | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 77 insertions(+) create mode 100644 src/program.c create mode 100644 src/program.h diff --git a/src/program.c b/src/program.c new file mode 100644 index 0000000..975f5c0 --- /dev/null +++ b/src/program.c @@ -0,0 +1,45 @@ + +#include +#include +#include +#include +#include +#include +#include +#include "program.h" + +int program_loadfromfile(struct program *prog, const char *filename) { + + struct stat st; + ssize_t rc = -1; + int fd; + + fd = open(filename, O_RDONLY); + if (fd < 0) { + fprintf(stderr, "Could not open file %s: %s\n", + filename, strerror(errno)); + return -1; + } + + if (fstat(fd, &st) < 0) + goto close_fd; + + prog->len = st.st_size; + prog->instr = malloc(prog->len); + if (prog->instr == NULL) + goto close_fd; + + rc = read(fd, prog->instr, prog->len); + if (rc < 0) + goto free_mem; + return rc; +free_mem: free(prog->instr); +close_fd: close(fd); + return rc; +} + +void program_free(struct program *prog) { + + free(prog->instr); + prog->len = 0; +} diff --git a/src/program.h b/src/program.h new file mode 100644 index 0000000..3533d2d --- /dev/null +++ b/src/program.h @@ -0,0 +1,32 @@ +/* program.h + * + * Copyright (C) 2012,2014 Henrik Hautakoski + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + */ +#ifndef LOADER_H +#define LOADER_H + +struct program { + unsigned char *instr; + unsigned len; +}; + +int program_loadfromfile(struct program *prog, const char *filename); + +void program_free(struct program *prog); + +#endif /* LOADER_H */