chiark / gitweb /
giant reorg abolishes TrainNum most of the time; working on making it build
[trains.git] / hostside / utils.c
1 /*
2  * common
3  * general utility functions
4  */
5
6 #include <stdarg.h>
7 #include <errno.h>
8 #include <string.h>
9 #include <stdio.h>
10 #include <stdlib.h>
11
12 #include "common.h"
13
14 static void vdie_vprintf(const char *fmt, va_list al) {
15   va_list al_copy;
16   va_copy(al_copy,al);
17   vfprintf(stderr,fmt,al_copy);
18   die_vprintf_hook(fmt,al);
19 }
20
21 static void vdie_printf(const char *fmt, ...) {
22   va_list al;
23   va_start(al,fmt);
24   vdie_vprintf(fmt,al);
25   va_end(al);
26 }
27
28 void vdie(const char *fmt, int ev, va_list al) {
29   vdie_printf("%s: fatal: ", progname);
30   vdie_vprintf(fmt,al);
31   if (ev) vdie_printf(": %s",strerror(ev));
32   vdie_printf("\n");
33   die_hook();
34   exit(12);
35 }
36
37 void badusage(const char *why) {
38   fprintf(stderr,"%s: bad usage: %s\n",progname,why); exit(8);
39 }
40
41 void die(const char *fmt, ...)
42   { va_list al; va_start(al,fmt); vdie(fmt,0,al); }
43 void diee(const char *fmt, ...)
44   { va_list al; va_start(al,fmt); vdie(fmt,errno,al); }
45 void diem(void)
46   { diee("malloc failed"); }
47
48 void *mmalloc(size_t sz) {
49   void *p;
50   if (!sz) return 0;
51   p= malloc(sz);
52   if (!p) diem();
53   return p;
54 }
55                   
56 char *mstrdupl(const char *s, int l) {
57   char *p;
58   p= mmalloc(l+1);
59   memcpy(p,s,l);
60   p[l]= 0;
61   return p;
62 }
63                   
64 char *mstrdup(const char *s) { return mstrdupl(s,strlen(s)); }
65
66 void mgettimeofday(struct timeval *tv) {
67   int r;
68   r= gettimeofday(tv,0);
69   if (r) diee("gettimeofday failed");
70 }