feat: error handling and header start

This commit is contained in:
gbrochar 2024-03-15 15:58:57 +01:00
parent 5f52bc4c8f
commit e21df48de1
5 changed files with 62 additions and 5 deletions

View File

@ -1,6 +1,8 @@
NAME = ft_nm
SRC_FILES = main.c \
error.c \
header.c \
INC_FILES = ft_nm.h \

View File

@ -9,4 +9,10 @@
# include "libft.h"
# define FT_NM_SUCCESS 0
# define FT_NM_FAILURE -1
void ft_nm_error(const char *path);
int check_header(Elf64_Ehdr *header);
#endif

11
src/error.c Normal file
View File

@ -0,0 +1,11 @@
#include "ft_nm.h"
// XXX
#include <string.h>
void ft_nm_error(const char *path) {
char *str = malloc(8 + ft_strlen(path));
ft_strcpy(str, "ft_nm: ");
ft_strcat(str, path);
perror(str);
free(str);
}

26
src/header.c Normal file
View File

@ -0,0 +1,26 @@
#include "ft_nm.h"
int check_magic_number(Elf64_Ehdr *header) {
if (ft_strncmp((void *)&header->e_ident[EI_MAG0], "\x7f""ELF", 4)) {
return FT_NM_FAILURE;
}
return FT_NM_SUCCESS;
}
int check_format(Elf64_Ehdr *header) {
if (header->e_ident[EI_CLASS] == ELFCLASSNONE) {
printf("problem\n");
return FT_NM_FAILURE;
}
return FT_NM_SUCCESS;
}
int check_header(Elf64_Ehdr *header) {
if (check_magic_number(header) == FT_NM_FAILURE) {
return FT_NM_FAILURE;
}
if (check_format(header) == FT_NM_FAILURE) {
return FT_NM_FAILURE;
}
return FT_NM_SUCCESS;
}

View File

@ -1,5 +1,12 @@
#include "ft_nm.h"
void print_bits(char c) {
for (int a = 7; a >= 0; a--) {
ft_putnbr(c >> a & 1);
}
ft_putchar('\n');
}
int main(int ac, char **av) {
char *path = ft_strdup("a.out");
if (ac > 1) {
@ -7,17 +14,22 @@ int main(int ac, char **av) {
path = av[1];
}
int fd = open(path, O_RDONLY);
printf("Opening file %s with fd %d\n", path, fd);
if (fd == -1) {
ft_nm_error(path);
}
void *ptr = NULL;
Elf64_Ehdr *header;
ptr = mmap(NULL, 64, PROT_READ, MAP_PRIVATE, fd, 0);
if (ptr != MAP_FAILED) {
header = (Elf64_Ehdr *)ptr;
write(1, ptr, 4);
write(1, "\n", 1);
write(1, header->e_ident, 4);
write(1, "\n", 1);
if (check_header(header) == FT_NM_FAILURE) {
printf("ft_nm: %s: file format not recognized\n", path);
exit (1);
}
for (int i = 0; i < 64; i++) {
print_bits(((char *)ptr)[i]);
}
if (header->e_ident[EI_OSABI] == 0x00) {
printf("This ELF is for System V! :)\n");
}