1 #define _GNU_SOURCE
2 #include <stdarg.h>
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <string.h>
6 #include <limits.h>
7 #include <math.h>
9 #include "utils.h"
11 #include <sys/types.h>
12 #include <sys/stat.h>
13 #include <unistd.h>
15 int verbose = 1;
16 void error(char *fmt, ...)
17 {
18 va_list ap;
19 fprintf(stderr, "error: ");
20 va_start(ap, fmt);
21 vfprintf(stderr, fmt, ap);
22 va_end(ap);
23 fprintf(stderr, "\n");
24 exit(2);
25 }
26 void warn(char *fmt, ...)
27 {
28 va_list ap;
29 if (verbose <= 0)
30 return;
31 fprintf(stderr, "warning: ");
32 va_start(ap, fmt);
33 vfprintf(stderr, fmt, ap);
34 va_end(ap);
35 fprintf(stderr, "\n");
36 }
37 void dbg(const char *f, int ln, char *fmt, ...)
38 {
39 va_list ap;
40 if (getenv("MKCFW_VERBOSITY"))
41 verbose = atoi(getenv("MKCFW_VERBOSITY"));
42 if (verbose <= 1)
43 return;
44 fprintf(stderr, "DBG[%16s:%3d]: ", f, ln);
45 va_start(ap, fmt);
46 vfprintf(stderr, fmt, ap);
47 va_end(ap);
48 fprintf(stderr, "\n");
49 }
50 void *safe_alloc(const char *fn, const char *file, int ln, int n)
51 {
52 void *ret = calloc(n, 1);
53 if (!ret)
54 error("out of memory: request for %d bytes from function %s() [%s:%d]",
55 n, fn, file, ln);
56 return ret;
57 }
58 void safe_snprintf(char *str, size_t size, const char *format, ...)
59 {
60 char *t = ALLOC(size);
61 va_list ap;
62 va_start(ap, format);
63 vsnprintf(t, size, format, ap);
64 va_end(ap);
65 strcpy(str, t);
66 free(t);
67 }
68 char *make_opts(const struct option *options)
69 {
70 int i = 0;
71 static char opts[256];
72 while (options[i].name) {
73 safe_snprintf(opts, sizeof(opts), "%s%c%s%s", opts, options[i].val,
74 options[i].has_arg?":":"",
75 (options[i].has_arg == 2)?":":"");
76 ++i;
77 }
78 return opts;
79 }