diff options
Diffstat (limited to 'src/elfhandle.c')
-rw-r--r-- | src/elfhandle.c | 74 |
1 files changed, 74 insertions, 0 deletions
diff --git a/src/elfhandle.c b/src/elfhandle.c new file mode 100644 index 0000000..a17216d --- /dev/null +++ b/src/elfhandle.c @@ -0,0 +1,74 @@ +#include <errno.h> +#include <sys/types.h> +#include <sys/stat.h> +#include <fcntl.h> +#include <stdio.h> +#include <string.h> +#include <unistd.h> + +#include <libelf.h> + +#include "elfhandle.h" + + +void openElf(ELFHandles *h, char *fn, Elf_Cmd elfmode) +{ + int openflags = 0; + int openmode = 0; + + h->e = NULL; + + switch(elfmode) { + case ELF_C_READ: + openflags = O_RDONLY; + break; + case ELF_C_WRITE: + openflags = O_WRONLY | O_CREAT; + openmode = S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH; + break; + case ELF_C_RDWR: + openflags = O_RDWR; + break; + default: + return; + } + + + h->fd = open(fn, openflags, openmode); + if (h->fd < 0) { + fprintf(stderr, "Cannot open %s: %s\n", fn, strerror(errno)); + return; + } + + h->e = elf_begin(h->fd, elfmode, NULL); + if (!h->e) { + fprintf(stderr, "elf_begin() failed on %s: %s\n", fn, elf_errmsg(-1)); + goto ERR; + } + + if (elfmode == ELF_C_READ || elfmode == ELF_C_RDWR) { + if (elf_kind(h->e) != ELF_K_ELF) { + fprintf(stderr, "Not an ELF object: %s", fn); + goto ERR; + } + } + + return; + +ERR: + if (h->e) { + elf_end(h->e); + h->e = NULL; + } + close(h->fd); +} + + +void closeElf(ELFHandles *h) +{ + if (h->e) { + elf_end(h->e); + close(h->fd); + h->e = NULL; + } +} |