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