diff --git a/src/relf/relf.c b/src/relf/relf.c index b9e89e9..3f55b0b 100644 --- a/src/relf/relf.c +++ b/src/relf/relf.c @@ -10,6 +10,39 @@ #include #include +int relf_file_check(const char* path) +{ + uint8_t e_ident[EI_NIDENT] = {0}; + + int fd = open(path, O_RDONLY); + if (fd < 0) return -1; + + if (read(fd, e_ident, EI_NIDENT) < EI_NIDENT) + { + close(fd); + return -1; + } + + if (!memcmp(e_ident, ELFMAG, sizeof(ELFMAG))) + { + close(fd); + return -1; + } + + // now we need to read ELF type + // e_type comes right after e_ident in ELF header + uint16_t e_type; + if (read(fd, &e_type, sizeof(e_type)) < sizeof(e_type)) + { + close(fd); + return -1; + } + + close(fd); + // return ELF type + return e_type; +} + // returns 1 if size not suitable for 32 bit host static int check_32bit_limit(off_t st_size) { diff --git a/src/relf/relf.h b/src/relf/relf.h index e04e12d..26502ec 100644 --- a/src/relf/relf.h +++ b/src/relf/relf.h @@ -4,12 +4,11 @@ #include #include -// composite error type typedef enum { RELF_MMAP_FAILED = -5, // file memory mapping failed RELF_UNSUPPORTED = -4, // big endian or not x86/x86-64 architecture - RELF_NOT_AN_ELF = -3, // wrong magic - RELF_TOO_BIG = -2, // file is over size_t limit + RELF_TOO_BIG = -3, // file is over size_t limit + RELF_NOT_AN_ELF = -2, // wrong magic RELF_FAILED_OPEN = -1, // failed to stat or open file RELF_OK = 0, } relf_error_t; @@ -93,6 +92,13 @@ typedef struct { unsigned symbol_num; } relf_t; +// tries to open ELF file, checks its magic and if everything ok +// returns ELF type. In case of error, return -1 +// if "e_ident" is non-null, e_ident of ELF would be saved here, +// in that case "e_ident" must provide at least EI_NIDENT bytes size place, +// if "fd" is non-null, file won't be closed and file descriptor would be placed here +int relf_file_check(const char* path); + // opens ELF file, checks ELF magic and maps it into memory // may load additional info like string table relf_error_t relf_open(relf_t* relf, const char* path); diff --git a/src/relf_test/relf_test.c b/src/relf_test/relf_test.c index d67a2e5..8110867 100644 --- a/src/relf_test/relf_test.c +++ b/src/relf_test/relf_test.c @@ -4,6 +4,8 @@ int main(int argc, char** argv) { + printf("relf_file_check %u\n", relf_file_check(argv[1])); + relf_t dummy; relf_open(&dummy, argv[1]);