woody-woodpacker/srcs/main.c

123 lines
2.9 KiB
C

#include "../includes/woody.h"
void free_elf_content(t_elf_content *woody)
{
if (woody->elf32)
free(woody->elf32);
else if (woody->elf64)
free(woody->elf64);
}
int get_elf_file(t_elf_content *woody)
{
int fd;
off_t off;
fd = open(woody->file_path, O_RDONLY);
if (fd < 0)
{
ft_printf("Error: Failed to open \'%s\'\n", woody->file_path);
return EXIT_FAILURE;
}
off = lseek(fd, 0, SEEK_END);
if (off == -1)
{
close(fd);
ft_printf("Error: Failed to read file offset \'%s\'\n", woody->file_path);
return EXIT_FAILURE;
}
woody->file_size = off;
woody->file = mmap(NULL, woody->file_size, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE, fd, 0);
if (woody->file == MAP_FAILED)
{
close(fd);
ft_printf("Error: Failed to map file \'%s\'\n", woody->file_path);
return EXIT_FAILURE;
}
close(fd);
return EXIT_SUCCESS;
}
int save_file(char *path, char *file, unsigned long int size)
{
int fd = open(path, O_CREAT | O_WRONLY | O_TRUNC, 0755);
if (fd == -1) {
ft_printf("Error: Failed to create new file \'%s\'\n", path);
return EXIT_FAILURE;
}
if (write(fd, file, size) == -1) {
close(fd);
ft_printf("Error: Failed to write new file \'%s\'\n", path);
return EXIT_FAILURE;
}
close(fd);
return EXIT_SUCCESS;
}
int save_woody(t_elf_content *woody)
{
char *woody_file = malloc(woody->file_size);
if (!woody_file)
return ft_put_error("Allocation error");
ft_memcpy(woody_file, woody->file, woody->file_size);
if (munmap(woody->file, woody->file_size))
return ft_put_error("Umapping error");
int save_error = save_file("woody", woody_file, woody->file_size);
if (save_error)
return save_error;
free(woody_file);
return EXIT_SUCCESS;
}
int main(int ac, char **av)
{
t_elf_content woody = {0};
if (ac != 2)
{
return ft_put_error("Woody_woodpacker take 1 argument\n");
}
woody.file_path = av[1];
int elf_error = get_elf_file(&woody);
if (elf_error)
return elf_error;
if (woody.file_size < sizeof(Elf32_Ehdr) || !elf_magic_numbers(woody.file))
{
ft_printf("Error: \'%s\' is not a valid ELF file\n", woody.file_path);
return EXIT_FAILURE;
}
int elfclass = woody.file[4];
if (elfclass == ELFCLASS32)
{
if (!(woody.elf32 = malloc(sizeof(t_elf32))))
return ft_put_error("Allocation error");
elf_error = get_elf_sections32(&woody);
}
else if (elfclass == ELFCLASS64)
{
if (!(woody.elf64 = malloc(sizeof(t_elf64))))
return ft_put_error("Allocation error");
elf_error = get_elf_sections64(&woody);
}
else
{
elf_error = EXIT_FAILURE;
ft_printf("Error: \'%s\' is not a valid ELF file\n", woody.file_path);
}
if (elf_error)
return elf_error;
int inject_error = -1;
if (elfclass == ELFCLASS32)
inject_error = inject32(&woody);
else if (elfclass == ELFCLASS64)
inject_error = inject64(&woody);
if (inject_error)
{
free_elf_content(&woody);
return inject_error;
}
int save_error = save_woody(&woody);
free_elf_content(&woody);
return save_error;
}