implement relf file check function to get ELF type
This commit is contained in:
parent
3ce2738715
commit
226d306bfa
3 changed files with 44 additions and 3 deletions
|
|
@ -10,6 +10,39 @@
|
|||
#include <stdlib.h>
|
||||
#include <errno.h>
|
||||
|
||||
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)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -4,12 +4,11 @@
|
|||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
|
||||
// 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);
|
||||
|
|
|
|||
|
|
@ -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]);
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue