chiark / gitweb /
hostside: utils: new dumphex function, moved from hidraw-ioctl.c
[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 <sys/types.h>
13 #include <sys/wait.h>
14
15 #include "common.h"
16
17 static void vdie_vprintf(const char *fmt, va_list al) {
18   va_list al_copy;
19   va_copy(al_copy,al);
20   vfprintf(stderr,fmt,al_copy);
21   die_vprintf_hook(fmt,al);
22 }
23
24 static void vdie_printf(const char *fmt, ...) {
25   va_list al;
26   va_start(al,fmt);
27   vdie_vprintf(fmt,al);
28   va_end(al);
29 }
30
31 void vdie(const char *fmt, int ev, va_list al) {
32   vdie_printf("%s: fatal: ", progname);
33   vdie_vprintf(fmt,al);
34   if (ev) vdie_printf(": %s",strerror(ev));
35   vdie_printf("\n");
36   die_hook();
37   exit(12);
38 }
39
40 void badusage(const char *why) {
41   fprintf(stderr,"%s: bad usage: %s\n",progname,why); exit(8);
42 }
43
44 void die(const char *fmt, ...)
45   { va_list al; va_start(al,fmt); vdie(fmt,0,al); }
46 void diee(const char *fmt, ...)
47   { va_list al; va_start(al,fmt); vdie(fmt,errno,al); }
48 void diem(void)
49   { diee("malloc failed"); }
50
51 void *mmalloc(size_t sz) {
52   void *p;
53   if (!sz) return 0;
54   p= malloc(sz);
55   if (!p) diem();
56   return p;
57 }
58                   
59 void *mrealloc(void *o, size_t sz) {
60   void *r;
61   if (!sz) { free(o); return 0; }
62   r= realloc(o,sz);
63   if (!r) diem();
64   return r;
65 }
66                   
67 char *mstrdupl(const char *s, int l) {
68   char *p;
69   p= mmalloc(l+1);
70   memcpy(p,s,l);
71   p[l]= 0;
72   return p;
73 }
74                   
75 char *mstrdup(const char *s) { return mstrdupl(s,strlen(s)); }
76
77 void mrename(const char *old, const char *new) {
78   if (rename(old,new))
79     diee("failed to rename `%s' to `%s'", old,new);
80 }
81
82 void mwaitpid(pid_t child, const char *what) {
83   pid_t rpid;
84   int status;
85   
86   rpid= waitpid(child,&status,0);  if (rpid!=child) diee("waitpid");
87   if (WIFEXITED(status)) {
88     int st= WEXITSTATUS(status);
89     if (st) die("%s exited with nonzero status %d",what,st);
90   } else if (WIFSIGNALED(status)) {
91     die("%s died due to %s%s", what, strsignal(WTERMSIG(status)),
92         WCOREDUMP(status) ? " (core dumped)" : "");
93   } else {
94     die("%s failed with unexpected wait status 0x%x", what, status);
95   }
96 }
97
98 void mflushstdout(void) {
99   if (ferror(stdout) || fflush(stdout)) diee("write to stdout");
100 }
101
102 void dumphex(FILE *f, const void *pu, int l) {
103   const uint8_t *p= pu;
104   while (l>0) {
105     fprintf(f,"%02x",*p++);
106     l--;
107   }
108   putc(' ',f);
109 }