secd/src/util.c

98 lines
1.5 KiB
C

#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include "dbg.h"
#include "util.h"
#ifdef POSIX
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>
#endif
// print message to stderr and then exit
void die(const char* s) {
fprintf(stderr, "FATAL ERROR: %s.\n", s);
exit(1);
}
// print perror message to stderr and then exit
void diePerror(const char* s) {
perror(s);
exit(1);
}
// malloc which dies on failure
void* xmalloc(size_t bytes) {
void* p = malloc(bytes);
GUARD(p);
return p;
}
// realloc which dies on failure
void* xrealloc(void* p, size_t bytes) {
p = realloc(p, bytes);
GUARD(p);
return p;
}
// free which is garantueed null pointer safe
void xfree(void* p) {
if (p) {
free(p);
}
}
// read the file at the given path and return a byte buffer
// pointing to the contents of the file, the length of which
// is stored in rsize
uint8_t* readFile(char* path, size_t* rsize) {
size_t size = 0;
uint8_t* buf = 0;
#ifdef POSIX
int fd = 0;
fd = open(path, O_RDONLY);
SGUARD(fd);
size = lseek(fd, 0, SEEK_END);
SGUARD(size);
buf = mmap(0, size, PROT_READ, MAP_PRIVATE, fd, 0);
SGUARD(buf);
SGUARD(close(fd));
#else
FILE* fp = 0;
fp = fopen(path, "rb");
GUARD(fp);
GUARD(fseek(fp, 0, SEEK_END));
size = ftell(fp);
rewind(fp);
buf = xmalloc(size);
GUARD(fread(buf, 1, size, fp) == size);
GUARD(fclose(fp));
#endif
*rsize = size;
return buf;
}
// free read file
void freeFile(uint8_t* buf, size_t size) {
#ifdef POSIX
SGUARD(munmap(buf, size));
#else
xfree(buf);
#endif
}