diff options
| author | onelin <oscar@nelin.dk> | 2026-11-19 21:26:47 +0000 |
|---|---|---|
| committer | onelin <oscar@nelin.dk> | 2026-11-19 21:26:47 +0000 |
| commit | c38941afde2b398bf6b6ed040d8248a7570c1450 (patch) | |
| tree | 37a903c8a94f9168fa8a60a158c8073a813aaa2f | |
| parent | c46053cad6bef5437c018b2f66e3146dcf74ec59 (diff) | |
Use simpler functions, better error handling
| -rw-r--r-- | write_elf.c | 54 |
1 files changed, 39 insertions, 15 deletions
diff --git a/write_elf.c b/write_elf.c index adb11a8..1d571a1 100644 --- a/write_elf.c +++ b/write_elf.c @@ -1,8 +1,11 @@ #include <elf.h> #include <err.h> +#include <errno.h> +#include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> +#include <unistd.h> int write_elf(char* restrict file, size_t opcodes_len, char* restrict opcodes) { @@ -101,26 +104,47 @@ write_elf(char* restrict file, size_t opcodes_len, char* restrict opcodes) { .e_shstrndx = 2, }; - size_t bytes_written = 0; - FILE* fd = fopen(file, "w"); + int fd = open(file, O_WRONLY | O_CREAT, 00740); + if (fd == -1) { + err(EXIT_FAILURE, "Failed to open file: %s", strerror(errno)); + } - fwrite(&header, sizeof(Elf64_Ehdr), 1, fd); - fwrite(&header_program, sizeof(Elf64_Phdr), - sizeof(header_program) / sizeof(header_program[0]), fd); - fwrite(&header_section, sizeof(Elf64_Shdr), - sizeof(header_section) / sizeof(header_section[0]), fd); + size_t write_len = write(fd, &header, sizeof(Elf64_Ehdr)); + if (write_len != sizeof(Elf64_Ehdr)) { + err(EXIT_FAILURE, "failed to write elf header"); + } + write_len = write(fd, &header_program, + sizeof(Elf64_Phdr) * + (sizeof(header_program) / sizeof(header_program[0]))); + if (write_len != sizeof(Elf64_Phdr) * + (sizeof(header_program) / sizeof(header_program[0]))) { + err(EXIT_FAILURE, "failed to write program headers"); + } + write_len = write(fd, &header_section, + sizeof(Elf64_Shdr) * + (sizeof(header_section) / sizeof(header_section[0]))); + if (write_len != sizeof(Elf64_Shdr) * + (sizeof(header_section) / sizeof(header_section[0]))) { + err(EXIT_FAILURE, "failed to write section headers"); + } - fseek(fd, 0x1000, SEEK_SET); + lseek(fd, 0x1000, SEEK_SET); - do { - bytes_written += fwrite(opcodes, sizeof(char), opcodes_len, fd); - } while (bytes_written != opcodes_len); + write_len = write(fd, opcodes, sizeof(char) * opcodes_len); + if (write_len != opcodes_len) { + err(EXIT_FAILURE, "failed to write opcodes"); + } - fseek(fd, 0x2000, SEEK_SET); - fwrite(string_header_table, sizeof(char), - sizeof(string_header_table) / sizeof(string_header_table[0]), fd); + lseek(fd, 0x2000, SEEK_SET); + write_len = write(fd, string_header_table, + sizeof(char) * (sizeof(string_header_table) / + sizeof(string_header_table[0]))); + if (write_len != + sizeof(string_header_table) / sizeof(string_header_table[0])) { + err(EXIT_FAILURE, "failed to write string table header"); + } - error = fclose(fd); + error = close(fd); if (error) { err(EXIT_FAILURE, "no way"); } |
