util: Make out_of_memory() call abort() instead of exit(EXIT_FAILURE).
[sliver-openvswitch.git] / lib / util.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011 Nicira Networks.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18 #include "util.h"
19 #include <errno.h>
20 #include <stdarg.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <unistd.h>
25 #include "coverage.h"
26 #include "vlog.h"
27
28 VLOG_DEFINE_THIS_MODULE(util);
29
30 COVERAGE_DEFINE(util_xalloc);
31
32 const char *program_name;
33
34 void
35 out_of_memory(void)
36 {
37     ovs_abort(0, "virtual memory exhausted");
38 }
39
40 void *
41 xcalloc(size_t count, size_t size)
42 {
43     void *p = count && size ? calloc(count, size) : malloc(1);
44     COVERAGE_INC(util_xalloc);
45     if (p == NULL) {
46         out_of_memory();
47     }
48     return p;
49 }
50
51 void *
52 xzalloc(size_t size)
53 {
54     return xcalloc(1, size);
55 }
56
57 void *
58 xmalloc(size_t size)
59 {
60     void *p = malloc(size ? size : 1);
61     COVERAGE_INC(util_xalloc);
62     if (p == NULL) {
63         out_of_memory();
64     }
65     return p;
66 }
67
68 void *
69 xrealloc(void *p, size_t size)
70 {
71     p = realloc(p, size ? size : 1);
72     COVERAGE_INC(util_xalloc);
73     if (p == NULL) {
74         out_of_memory();
75     }
76     return p;
77 }
78
79 void *
80 xmemdup(const void *p_, size_t size)
81 {
82     void *p = xmalloc(size);
83     memcpy(p, p_, size);
84     return p;
85 }
86
87 char *
88 xmemdup0(const char *p_, size_t length)
89 {
90     char *p = xmalloc(length + 1);
91     memcpy(p, p_, length);
92     p[length] = '\0';
93     return p;
94 }
95
96 char *
97 xstrdup(const char *s)
98 {
99     return xmemdup0(s, strlen(s));
100 }
101
102 char *
103 xvasprintf(const char *format, va_list args)
104 {
105     va_list args2;
106     size_t needed;
107     char *s;
108
109     va_copy(args2, args);
110     needed = vsnprintf(NULL, 0, format, args);
111
112     s = xmalloc(needed + 1);
113
114     vsnprintf(s, needed + 1, format, args2);
115     va_end(args2);
116
117     return s;
118 }
119
120 void *
121 x2nrealloc(void *p, size_t *n, size_t s)
122 {
123     *n = *n == 0 ? 1 : 2 * *n;
124     return xrealloc(p, *n * s);
125 }
126
127 char *
128 xasprintf(const char *format, ...)
129 {
130     va_list args;
131     char *s;
132
133     va_start(args, format);
134     s = xvasprintf(format, args);
135     va_end(args);
136
137     return s;
138 }
139
140 /* Similar to strlcpy() from OpenBSD, but it never reads more than 'size - 1'
141  * bytes from 'src' and doesn't return anything. */
142 void
143 ovs_strlcpy(char *dst, const char *src, size_t size)
144 {
145     if (size > 0) {
146         size_t len = strnlen(src, size - 1);
147         memcpy(dst, src, len);
148         dst[len] = '\0';
149     }
150 }
151
152 /* Copies 'src' to 'dst'.  Reads no more than 'size - 1' bytes from 'src'.
153  * Always null-terminates 'dst' (if 'size' is nonzero), and writes a zero byte
154  * to every otherwise unused byte in 'dst'.
155  *
156  * Except for performance, the following call:
157  *     ovs_strzcpy(dst, src, size);
158  * is equivalent to these two calls:
159  *     memset(dst, '\0', size);
160  *     ovs_strlcpy(dst, src, size);
161  *
162  * (Thus, ovs_strzcpy() is similar to strncpy() without some of the pitfalls.)
163  */
164 void
165 ovs_strzcpy(char *dst, const char *src, size_t size)
166 {
167     if (size > 0) {
168         size_t len = strnlen(src, size - 1);
169         memcpy(dst, src, len);
170         memset(dst + len, '\0', size - len);
171     }
172 }
173
174 /* Prints 'format' on stderr, formatting it like printf() does.  If 'err_no' is
175  * nonzero, then it is formatted with ovs_retval_to_string() and appended to
176  * the message inside parentheses.  Then, terminates with abort().
177  *
178  * This function is preferred to ovs_fatal() in a situation where it would make
179  * sense for a monitoring process to restart the daemon.
180  *
181  * 'format' should not end with a new-line, because this function will add one
182  * itself. */
183 void
184 ovs_abort(int err_no, const char *format, ...)
185 {
186     va_list args;
187
188     va_start(args, format);
189     ovs_error_valist(err_no, format, args);
190     va_end(args);
191
192     abort();
193 }
194
195 /* Prints 'format' on stderr, formatting it like printf() does.  If 'err_no' is
196  * nonzero, then it is formatted with ovs_retval_to_string() and appended to
197  * the message inside parentheses.  Then, terminates with EXIT_FAILURE.
198  *
199  * 'format' should not end with a new-line, because this function will add one
200  * itself. */
201 void
202 ovs_fatal(int err_no, const char *format, ...)
203 {
204     va_list args;
205
206     va_start(args, format);
207     ovs_error_valist(err_no, format, args);
208     va_end(args);
209
210     exit(EXIT_FAILURE);
211 }
212
213 /* Prints 'format' on stderr, formatting it like printf() does.  If 'err_no' is
214  * nonzero, then it is formatted with ovs_retval_to_string() and appended to
215  * the message inside parentheses.
216  *
217  * 'format' should not end with a new-line, because this function will add one
218  * itself. */
219 void
220 ovs_error(int err_no, const char *format, ...)
221 {
222     va_list args;
223
224     va_start(args, format);
225     ovs_error_valist(err_no, format, args);
226     va_end(args);
227 }
228
229 /* Same as ovs_error() except that the arguments are supplied as a va_list. */
230 void
231 ovs_error_valist(int err_no, const char *format, va_list args)
232 {
233     int save_errno = errno;
234
235     fprintf(stderr, "%s: ", program_name);
236     vfprintf(stderr, format, args);
237     if (err_no != 0) {
238         fprintf(stderr, " (%s)", ovs_retval_to_string(err_no));
239     }
240     putc('\n', stderr);
241
242     errno = save_errno;
243 }
244
245 /* Many OVS functions return an int which is one of:
246  * - 0: no error yet
247  * - >0: errno value
248  * - EOF: end of file (not necessarily an error; depends on the function called)
249  *
250  * Returns the appropriate human-readable string. The caller must copy the
251  * string if it wants to hold onto it, as the storage may be overwritten on
252  * subsequent function calls.
253  */
254 const char *
255 ovs_retval_to_string(int retval)
256 {
257     static char unknown[48];
258
259     if (!retval) {
260         return "";
261     }
262     if (retval > 0) {
263         return strerror(retval);
264     }
265     if (retval == EOF) {
266         return "End of file";
267     }
268     snprintf(unknown, sizeof unknown, "***unknown return value: %d***", retval);
269     return unknown;
270 }
271
272 /* Sets program_name based on 'argv0'.  Should be called at the beginning of
273  * main(), as "set_program_name(argv[0]);".  */
274 void set_program_name(const char *argv0)
275 {
276     const char *slash = strrchr(argv0, '/');
277     program_name = slash ? slash + 1 : argv0;
278 }
279
280 /* Print the version information for the program.  */
281 void
282 ovs_print_version(char *date, char *time,
283                   uint8_t min_ofp, uint8_t max_ofp)
284 {
285     printf("%s (Open vSwitch) "VERSION BUILDNR"\n", program_name);
286     printf("Compiled %s %s\n", date, time);
287     if (min_ofp || max_ofp) {
288         printf("OpenFlow versions %#x:%#x\n", min_ofp, max_ofp);
289     }
290 }
291
292 /* Writes the 'size' bytes in 'buf' to 'stream' as hex bytes arranged 16 per
293  * line.  Numeric offsets are also included, starting at 'ofs' for the first
294  * byte in 'buf'.  If 'ascii' is true then the corresponding ASCII characters
295  * are also rendered alongside. */
296 void
297 ovs_hex_dump(FILE *stream, const void *buf_, size_t size,
298              uintptr_t ofs, bool ascii)
299 {
300   const uint8_t *buf = buf_;
301   const size_t per_line = 16; /* Maximum bytes per line. */
302
303   while (size > 0)
304     {
305       size_t start, end, n;
306       size_t i;
307
308       /* Number of bytes on this line. */
309       start = ofs % per_line;
310       end = per_line;
311       if (end - start > size)
312         end = start + size;
313       n = end - start;
314
315       /* Print line. */
316       fprintf(stream, "%08jx  ", (uintmax_t) ROUND_DOWN(ofs, per_line));
317       for (i = 0; i < start; i++)
318         fprintf(stream, "   ");
319       for (; i < end; i++)
320         fprintf(stream, "%02hhx%c",
321                 buf[i - start], i == per_line / 2 - 1? '-' : ' ');
322       if (ascii)
323         {
324           for (; i < per_line; i++)
325             fprintf(stream, "   ");
326           fprintf(stream, "|");
327           for (i = 0; i < start; i++)
328             fprintf(stream, " ");
329           for (; i < end; i++) {
330               int c = buf[i - start];
331               putc(c >= 32 && c < 127 ? c : '.', stream);
332           }
333           for (; i < per_line; i++)
334             fprintf(stream, " ");
335           fprintf(stream, "|");
336         }
337       fprintf(stream, "\n");
338
339       ofs += n;
340       buf += n;
341       size -= n;
342     }
343 }
344
345 bool
346 str_to_int(const char *s, int base, int *i)
347 {
348     long long ll;
349     bool ok = str_to_llong(s, base, &ll);
350     *i = ll;
351     return ok;
352 }
353
354 bool
355 str_to_long(const char *s, int base, long *li)
356 {
357     long long ll;
358     bool ok = str_to_llong(s, base, &ll);
359     *li = ll;
360     return ok;
361 }
362
363 bool
364 str_to_llong(const char *s, int base, long long *x)
365 {
366     int save_errno = errno;
367     char *tail;
368     errno = 0;
369     *x = strtoll(s, &tail, base);
370     if (errno == EINVAL || errno == ERANGE || tail == s || *tail != '\0') {
371         errno = save_errno;
372         *x = 0;
373         return false;
374     } else {
375         errno = save_errno;
376         return true;
377     }
378 }
379
380 bool
381 str_to_uint(const char *s, int base, unsigned int *u)
382 {
383     return str_to_int(s, base, (int *) u);
384 }
385
386 bool
387 str_to_ulong(const char *s, int base, unsigned long *ul)
388 {
389     return str_to_long(s, base, (long *) ul);
390 }
391
392 bool
393 str_to_ullong(const char *s, int base, unsigned long long *ull)
394 {
395     return str_to_llong(s, base, (long long *) ull);
396 }
397
398 /* Converts floating-point string 's' into a double.  If successful, stores
399  * the double in '*d' and returns true; on failure, stores 0 in '*d' and
400  * returns false.
401  *
402  * Underflow (e.g. "1e-9999") is not considered an error, but overflow
403  * (e.g. "1e9999)" is. */
404 bool
405 str_to_double(const char *s, double *d)
406 {
407     int save_errno = errno;
408     char *tail;
409     errno = 0;
410     *d = strtod(s, &tail);
411     if (errno == EINVAL || (errno == ERANGE && *d != 0)
412         || tail == s || *tail != '\0') {
413         errno = save_errno;
414         *d = 0;
415         return false;
416     } else {
417         errno = save_errno;
418         return true;
419     }
420 }
421
422 /* Returns the value of 'c' as a hexadecimal digit. */
423 int
424 hexit_value(int c)
425 {
426     switch (c) {
427     case '0': case '1': case '2': case '3': case '4':
428     case '5': case '6': case '7': case '8': case '9':
429         return c - '0';
430
431     case 'a': case 'A':
432         return 0xa;
433
434     case 'b': case 'B':
435         return 0xb;
436
437     case 'c': case 'C':
438         return 0xc;
439
440     case 'd': case 'D':
441         return 0xd;
442
443     case 'e': case 'E':
444         return 0xe;
445
446     case 'f': case 'F':
447         return 0xf;
448
449     default:
450         return -1;
451     }
452 }
453
454 /* Returns the integer value of the 'n' hexadecimal digits starting at 's', or
455  * UINT_MAX if one of those "digits" is not really a hex digit.  If 'ok' is
456  * nonnull, '*ok' is set to true if the conversion succeeds or to false if a
457  * non-hex digit is detected. */
458 unsigned int
459 hexits_value(const char *s, size_t n, bool *ok)
460 {
461     unsigned int value;
462     size_t i;
463
464     value = 0;
465     for (i = 0; i < n; i++) {
466         int hexit = hexit_value(s[i]);
467         if (hexit < 0) {
468             if (ok) {
469                 *ok = false;
470             }
471             return UINT_MAX;
472         }
473         value = (value << 4) + hexit;
474     }
475     if (ok) {
476         *ok = true;
477     }
478     return value;
479 }
480
481 /* Returns the current working directory as a malloc()'d string, or a null
482  * pointer if the current working directory cannot be determined. */
483 char *
484 get_cwd(void)
485 {
486     long int path_max;
487     size_t size;
488
489     /* Get maximum path length or at least a reasonable estimate. */
490     path_max = pathconf(".", _PC_PATH_MAX);
491     size = (path_max < 0 ? 1024
492             : path_max > 10240 ? 10240
493             : path_max);
494
495     /* Get current working directory. */
496     for (;;) {
497         char *buf = xmalloc(size);
498         if (getcwd(buf, size)) {
499             return xrealloc(buf, strlen(buf) + 1);
500         } else {
501             int error = errno;
502             free(buf);
503             if (error != ERANGE) {
504                 VLOG_WARN("getcwd failed (%s)", strerror(error));
505                 return NULL;
506             }
507             size *= 2;
508         }
509     }
510 }
511
512 static char *
513 all_slashes_name(const char *s)
514 {
515     return xstrdup(s[0] == '/' && s[1] == '/' && s[2] != '/' ? "//"
516                    : s[0] == '/' ? "/"
517                    : ".");
518 }
519
520 /* Returns the directory name portion of 'file_name' as a malloc()'d string,
521  * similar to the POSIX dirname() function but thread-safe. */
522 char *
523 dir_name(const char *file_name)
524 {
525     size_t len = strlen(file_name);
526     while (len > 0 && file_name[len - 1] == '/') {
527         len--;
528     }
529     while (len > 0 && file_name[len - 1] != '/') {
530         len--;
531     }
532     while (len > 0 && file_name[len - 1] == '/') {
533         len--;
534     }
535     return len ? xmemdup0(file_name, len) : all_slashes_name(file_name);
536 }
537
538 /* Returns the file name portion of 'file_name' as a malloc()'d string,
539  * similar to the POSIX basename() function but thread-safe. */
540 char *
541 base_name(const char *file_name)
542 {
543     size_t end, start;
544
545     end = strlen(file_name);
546     while (end > 0 && file_name[end - 1] == '/') {
547         end--;
548     }
549
550     if (!end) {
551         return all_slashes_name(file_name);
552     }
553
554     start = end;
555     while (start > 0 && file_name[start - 1] != '/') {
556         start--;
557     }
558
559     return xmemdup0(file_name + start, end - start);
560 }
561
562 /* If 'file_name' starts with '/', returns a copy of 'file_name'.  Otherwise,
563  * returns an absolute path to 'file_name' considering it relative to 'dir',
564  * which itself must be absolute.  'dir' may be null or the empty string, in
565  * which case the current working directory is used.
566  *
567  * Returns a null pointer if 'dir' is null and getcwd() fails. */
568 char *
569 abs_file_name(const char *dir, const char *file_name)
570 {
571     if (file_name[0] == '/') {
572         return xstrdup(file_name);
573     } else if (dir && dir[0]) {
574         char *separator = dir[strlen(dir) - 1] == '/' ? "" : "/";
575         return xasprintf("%s%s%s", dir, separator, file_name);
576     } else {
577         char *cwd = get_cwd();
578         if (cwd) {
579             char *abs_name = xasprintf("%s/%s", cwd, file_name);
580             free(cwd);
581             return abs_name;
582         } else {
583             return NULL;
584         }
585     }
586 }
587
588
589 /* Pass a value to this function if it is marked with
590  * __attribute__((warn_unused_result)) and you genuinely want to ignore
591  * its return value.  (Note that every scalar type can be implicitly
592  * converted to bool.) */
593 void ignore(bool x OVS_UNUSED) { }