chiark / gitweb /
Merge and end branch-hostside-wip-2008-01-25 PROPERLY; cvs up -j branch-hostside...
[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 void *mrealloc(void *o, size_t sz) {
57   void *r;
58   if (!sz) { free(o); return 0; }
59   r= realloc(o,sz);
60   if (!r) diem();
61   return r;
62 }
63                   
64 char *mstrdupl(const char *s, int l) {
65   char *p;
66   p= mmalloc(l+1);
67   memcpy(p,s,l);
68   p[l]= 0;
69   return p;
70 }
71                   
72 char *mstrdup(const char *s) { return mstrdupl(s,strlen(s)); }
73
74 void mgettimeofday(struct timeval *tv) {
75   int r;
76   r= gettimeofday(tv,0);
77   if (r) diee("gettimeofday failed");
78 }
79
80 void mrename(const char *old, const char *new) {
81   if (rename(old,new))
82     diee("failed to rename `%s' to `%s'", old,new);
83 }