Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/woip/c/safe.c
blob: f1390eab6f2d1fb10c45ed7ff086fee2f317e4b5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include "safe.h"

void *xalloc(size_t size) {
  void *ptr = malloc(size);
  
  if(!ptr) fatal("Couldn't allocate %zu bytes", size);
  
  memset(ptr, 0, size);
  return ptr;
}

FILE *xfopen(const char *path, const char *mode) {
  debug("opening %s mode %s", path, mode);
  
  FILE *fp = fopen(path, mode);
  
  if(!fp) fatal("Couldn't open %s", path);
  
  return fp;
}

int32_t xgetc(FILE *fp) {
  int32_t ret = getc(fp);
  
  if(ret == EOF && errno != 0) {
    fatal("Couldn't getc");
  }
  
  return ret;
}

int32_t xputc(uchar_t c, FILE *fp) {
  int32_t ret = putc(c, fp);
  
  if(ret == EOF)
    fatal("Couldn't putc");
    
  return ret;
}

void xfflush(FILE *fp) {
  if(fflush(fp) == EOF)
    fatal("Error on fflush");
}

void xfclose(FILE *fp) {
  if(fclose(fp) == EOF)
    fatal("Error on fclose");
}

void *xmmap(void *addr, size_t len, int prot, int flags, int fildes, off_t offset) {
  void *ptr;
  if((ptr = mmap(addr, len, prot, flags, fildes, offset)) < 0)
    fatal("Error on mmap");

  return ptr;
}

void *xmmapf(char *path, size_t *size) {
  int fd;
  struct stat s;

  if((fd = open(path, O_RDONLY)) < 0) fatal("Error open()ing %s", path);
  if(fstat(fd, &s) < 0) fatal("fstat");

  if(size) *size = s.st_size;

  return xmmap(NULL, (size_t) s.st_size, PROT_READ, MAP_PRIVATE, fd, (off_t) 0);
}