secd/src/util.c

78 lines
1.2 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, "ERROR: %s.\n", s);
exit(1);
}
// print perror message to stderr and then exit
void diePerror(const char* s) {
perror(s);
exit(1);
}
// 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 = malloc(size);
GUARD(buf);
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
free(buf);
#endif
}