ovs-vsctl: Support identifying Flow_Sample_Collector_Set records by id.
[cascardo/ovs.git] / lib / util.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015 Nicira, Inc.
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 <ctype.h>
20 #include <errno.h>
21 #include <limits.h>
22 #include <pthread.h>
23 #include <stdarg.h>
24 #include <stdint.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <sys/stat.h>
29 #include <unistd.h>
30 #include "bitmap.h"
31 #include "byte-order.h"
32 #include "coverage.h"
33 #include "ovs-rcu.h"
34 #include "ovs-thread.h"
35 #include "socket-util.h"
36 #include "openvswitch/vlog.h"
37 #ifdef HAVE_PTHREAD_SET_NAME_NP
38 #include <pthread_np.h>
39 #endif
40
41 VLOG_DEFINE_THIS_MODULE(util);
42
43 COVERAGE_DEFINE(util_xalloc);
44
45 /* argv[0] without directory names. */
46 char *program_name;
47
48 /* Name for the currently running thread or process, for log messages, process
49  * listings, and debuggers. */
50 DEFINE_PER_THREAD_MALLOCED_DATA(char *, subprogram_name);
51
52 /* --version option output. */
53 static char *program_version;
54
55 /* Buffer used by ovs_strerror() and ovs_format_message(). */
56 DEFINE_STATIC_PER_THREAD_DATA(struct { char s[128]; },
57                               strerror_buffer,
58                               { "" });
59
60 static char *xreadlink(const char *filename);
61
62 void
63 ovs_assert_failure(const char *where, const char *function,
64                    const char *condition)
65 {
66     /* Prevent an infinite loop (or stack overflow) in case VLOG_ABORT happens
67      * to trigger an assertion failure of its own. */
68     static int reentry = 0;
69
70     switch (reentry++) {
71     case 0:
72         VLOG_ABORT("%s: assertion %s failed in %s()",
73                    where, condition, function);
74         OVS_NOT_REACHED();
75
76     case 1:
77         fprintf(stderr, "%s: assertion %s failed in %s()",
78                 where, condition, function);
79         abort();
80
81     default:
82         abort();
83     }
84 }
85
86 void
87 out_of_memory(void)
88 {
89     ovs_abort(0, "virtual memory exhausted");
90 }
91
92 void *
93 xcalloc(size_t count, size_t size)
94 {
95     void *p = count && size ? calloc(count, size) : malloc(1);
96     COVERAGE_INC(util_xalloc);
97     if (p == NULL) {
98         out_of_memory();
99     }
100     return p;
101 }
102
103 void *
104 xzalloc(size_t size)
105 {
106     return xcalloc(1, size);
107 }
108
109 void *
110 xmalloc(size_t size)
111 {
112     void *p = malloc(size ? size : 1);
113     COVERAGE_INC(util_xalloc);
114     if (p == NULL) {
115         out_of_memory();
116     }
117     return p;
118 }
119
120 void *
121 xrealloc(void *p, size_t size)
122 {
123     p = realloc(p, size ? size : 1);
124     COVERAGE_INC(util_xalloc);
125     if (p == NULL) {
126         out_of_memory();
127     }
128     return p;
129 }
130
131 void *
132 xmemdup(const void *p_, size_t size)
133 {
134     void *p = xmalloc(size);
135     memcpy(p, p_, size);
136     return p;
137 }
138
139 char *
140 xmemdup0(const char *p_, size_t length)
141 {
142     char *p = xmalloc(length + 1);
143     memcpy(p, p_, length);
144     p[length] = '\0';
145     return p;
146 }
147
148 char *
149 xstrdup(const char *s)
150 {
151     return xmemdup0(s, strlen(s));
152 }
153
154 char *
155 xvasprintf(const char *format, va_list args)
156 {
157     va_list args2;
158     size_t needed;
159     char *s;
160
161     va_copy(args2, args);
162     needed = vsnprintf(NULL, 0, format, args);
163
164     s = xmalloc(needed + 1);
165
166     vsnprintf(s, needed + 1, format, args2);
167     va_end(args2);
168
169     return s;
170 }
171
172 void *
173 x2nrealloc(void *p, size_t *n, size_t s)
174 {
175     *n = *n == 0 ? 1 : 2 * *n;
176     return xrealloc(p, *n * s);
177 }
178
179 /* The desired minimum alignment for an allocated block of memory. */
180 #define MEM_ALIGN MAX(sizeof(void *), 8)
181 BUILD_ASSERT_DECL(IS_POW2(MEM_ALIGN));
182 BUILD_ASSERT_DECL(CACHE_LINE_SIZE >= MEM_ALIGN);
183
184 /* Allocates and returns 'size' bytes of memory in dedicated cache lines.  That
185  * is, the memory block returned will not share a cache line with other data,
186  * avoiding "false sharing".  (The memory returned will not be at the start of
187  * a cache line, though, so don't assume such alignment.)
188  *
189  * Use free_cacheline() to free the returned memory block. */
190 void *
191 xmalloc_cacheline(size_t size)
192 {
193 #ifdef HAVE_POSIX_MEMALIGN
194     void *p;
195     int error;
196
197     COVERAGE_INC(util_xalloc);
198     error = posix_memalign(&p, CACHE_LINE_SIZE, size ? size : 1);
199     if (error != 0) {
200         out_of_memory();
201     }
202     return p;
203 #else
204     void **payload;
205     void *base;
206
207     /* Allocate room for:
208      *
209      *     - Up to CACHE_LINE_SIZE - 1 bytes before the payload, so that the
210      *       start of the payload doesn't potentially share a cache line.
211      *
212      *     - A payload consisting of a void *, followed by padding out to
213      *       MEM_ALIGN bytes, followed by 'size' bytes of user data.
214      *
215      *     - Space following the payload up to the end of the cache line, so
216      *       that the end of the payload doesn't potentially share a cache line
217      *       with some following block. */
218     base = xmalloc((CACHE_LINE_SIZE - 1)
219                    + ROUND_UP(MEM_ALIGN + size, CACHE_LINE_SIZE));
220
221     /* Locate the payload and store a pointer to the base at the beginning. */
222     payload = (void **) ROUND_UP((uintptr_t) base, CACHE_LINE_SIZE);
223     *payload = base;
224
225     return (char *) payload + MEM_ALIGN;
226 #endif
227 }
228
229 /* Like xmalloc_cacheline() but clears the allocated memory to all zero
230  * bytes. */
231 void *
232 xzalloc_cacheline(size_t size)
233 {
234     void *p = xmalloc_cacheline(size);
235     memset(p, 0, size);
236     return p;
237 }
238
239 /* Frees a memory block allocated with xmalloc_cacheline() or
240  * xzalloc_cacheline(). */
241 void
242 free_cacheline(void *p)
243 {
244 #ifdef HAVE_POSIX_MEMALIGN
245     free(p);
246 #else
247     if (p) {
248         free(*(void **) ((uintptr_t) p - MEM_ALIGN));
249     }
250 #endif
251 }
252
253 char *
254 xasprintf(const char *format, ...)
255 {
256     va_list args;
257     char *s;
258
259     va_start(args, format);
260     s = xvasprintf(format, args);
261     va_end(args);
262
263     return s;
264 }
265
266 /* Similar to strlcpy() from OpenBSD, but it never reads more than 'size - 1'
267  * bytes from 'src' and doesn't return anything. */
268 void
269 ovs_strlcpy(char *dst, const char *src, size_t size)
270 {
271     if (size > 0) {
272         size_t len = strnlen(src, size - 1);
273         memcpy(dst, src, len);
274         dst[len] = '\0';
275     }
276 }
277
278 /* Copies 'src' to 'dst'.  Reads no more than 'size - 1' bytes from 'src'.
279  * Always null-terminates 'dst' (if 'size' is nonzero), and writes a zero byte
280  * to every otherwise unused byte in 'dst'.
281  *
282  * Except for performance, the following call:
283  *     ovs_strzcpy(dst, src, size);
284  * is equivalent to these two calls:
285  *     memset(dst, '\0', size);
286  *     ovs_strlcpy(dst, src, size);
287  *
288  * (Thus, ovs_strzcpy() is similar to strncpy() without some of the pitfalls.)
289  */
290 void
291 ovs_strzcpy(char *dst, const char *src, size_t size)
292 {
293     if (size > 0) {
294         size_t len = strnlen(src, size - 1);
295         memcpy(dst, src, len);
296         memset(dst + len, '\0', size - len);
297     }
298 }
299
300 /* Prints 'format' on stderr, formatting it like printf() does.  If 'err_no' is
301  * nonzero, then it is formatted with ovs_retval_to_string() and appended to
302  * the message inside parentheses.  Then, terminates with abort().
303  *
304  * This function is preferred to ovs_fatal() in a situation where it would make
305  * sense for a monitoring process to restart the daemon.
306  *
307  * 'format' should not end with a new-line, because this function will add one
308  * itself. */
309 void
310 ovs_abort(int err_no, const char *format, ...)
311 {
312     va_list args;
313
314     va_start(args, format);
315     ovs_abort_valist(err_no, format, args);
316 }
317
318 /* Same as ovs_abort() except that the arguments are supplied as a va_list. */
319 void
320 ovs_abort_valist(int err_no, const char *format, va_list args)
321 {
322     ovs_error_valist(err_no, format, args);
323     abort();
324 }
325
326 /* Prints 'format' on stderr, formatting it like printf() does.  If 'err_no' is
327  * nonzero, then it is formatted with ovs_retval_to_string() and appended to
328  * the message inside parentheses.  Then, terminates with EXIT_FAILURE.
329  *
330  * 'format' should not end with a new-line, because this function will add one
331  * itself. */
332 void
333 ovs_fatal(int err_no, const char *format, ...)
334 {
335     va_list args;
336
337     va_start(args, format);
338     ovs_fatal_valist(err_no, format, args);
339 }
340
341 /* Same as ovs_fatal() except that the arguments are supplied as a va_list. */
342 void
343 ovs_fatal_valist(int err_no, const char *format, va_list args)
344 {
345     ovs_error_valist(err_no, format, args);
346     exit(EXIT_FAILURE);
347 }
348
349 /* Prints 'format' on stderr, formatting it like printf() does.  If 'err_no' is
350  * nonzero, then it is formatted with ovs_retval_to_string() and appended to
351  * the message inside parentheses.
352  *
353  * 'format' should not end with a new-line, because this function will add one
354  * itself. */
355 void
356 ovs_error(int err_no, const char *format, ...)
357 {
358     va_list args;
359
360     va_start(args, format);
361     ovs_error_valist(err_no, format, args);
362     va_end(args);
363 }
364
365 /* Same as ovs_error() except that the arguments are supplied as a va_list. */
366 void
367 ovs_error_valist(int err_no, const char *format, va_list args)
368 {
369     const char *subprogram_name = get_subprogram_name();
370     int save_errno = errno;
371
372     if (subprogram_name[0]) {
373         fprintf(stderr, "%s(%s): ", program_name, subprogram_name);
374     } else {
375         fprintf(stderr, "%s: ", program_name);
376     }
377
378     vfprintf(stderr, format, args);
379     if (err_no != 0) {
380         fprintf(stderr, " (%s)", ovs_retval_to_string(err_no));
381     }
382     putc('\n', stderr);
383
384     errno = save_errno;
385 }
386
387 /* Many OVS functions return an int which is one of:
388  * - 0: no error yet
389  * - >0: errno value
390  * - EOF: end of file (not necessarily an error; depends on the function called)
391  *
392  * Returns the appropriate human-readable string. The caller must copy the
393  * string if it wants to hold onto it, as the storage may be overwritten on
394  * subsequent function calls.
395  */
396 const char *
397 ovs_retval_to_string(int retval)
398 {
399     return (!retval ? ""
400             : retval == EOF ? "End of file"
401             : ovs_strerror(retval));
402 }
403
404 /* This function returns the string describing the error number in 'error'
405  * for POSIX platforms.  For Windows, this function can be used for C library
406  * calls.  For socket calls that are also used in Windows, use sock_strerror()
407  * instead.  For WINAPI calls, look at ovs_lasterror_to_string(). */
408 const char *
409 ovs_strerror(int error)
410 {
411     enum { BUFSIZE = sizeof strerror_buffer_get()->s };
412     int save_errno;
413     char *buffer;
414     char *s;
415
416     if (error == 0) {
417         /*
418          * strerror(0) varies among platforms:
419          *
420          *   Success
421          *   No error
422          *   Undefined error: 0
423          *
424          * We want to provide a consistent result here because
425          * our testsuite has test cases which strictly matches
426          * log messages containing this string.
427          */
428         return "Success";
429     }
430
431     save_errno = errno;
432     buffer = strerror_buffer_get()->s;
433
434 #if STRERROR_R_CHAR_P
435     /* GNU style strerror_r() might return an immutable static string, or it
436      * might write and return 'buffer', but in either case we can pass the
437      * returned string directly to the caller. */
438     s = strerror_r(error, buffer, BUFSIZE);
439 #else  /* strerror_r() returns an int. */
440     s = buffer;
441     if (strerror_r(error, buffer, BUFSIZE)) {
442         /* strerror_r() is only allowed to fail on ERANGE (because the buffer
443          * is too short).  We don't check the actual failure reason because
444          * POSIX requires strerror_r() to return the error but old glibc
445          * (before 2.13) returns -1 and sets errno. */
446         snprintf(buffer, BUFSIZE, "Unknown error %d", error);
447     }
448 #endif
449
450     errno = save_errno;
451
452     return s;
453 }
454
455 /* Sets global "program_name" and "program_version" variables.  Should
456  * be called at the beginning of main() with "argv[0]" as the argument
457  * to 'argv0'.
458  *
459  * 'version' should contain the version of the caller's program.  If 'version'
460  * is the same as the VERSION #define, the caller is assumed to be part of Open
461  * vSwitch.  Otherwise, it is assumed to be an external program linking against
462  * the Open vSwitch libraries.
463  *
464  */
465 void
466 ovs_set_program_name(const char *argv0, const char *version)
467 {
468     char *basename;
469 #ifdef _WIN32
470     size_t max_len = strlen(argv0) + 1;
471
472     SetErrorMode(GetErrorMode() | SEM_NOGPFAULTERRORBOX);
473     _set_output_format(_TWO_DIGIT_EXPONENT);
474
475     basename = xmalloc(max_len);
476     _splitpath_s(argv0, NULL, 0, NULL, 0, basename, max_len, NULL, 0);
477 #else
478     const char *slash = strrchr(argv0, '/');
479     basename = xstrdup(slash ? slash + 1 : argv0);
480 #endif
481
482     assert_single_threaded();
483     free(program_name);
484     /* Remove libtool prefix, if it is there */
485     if (strncmp(basename, "lt-", 3) == 0) {
486         char *tmp_name = basename;
487         basename = xstrdup(basename + 3);
488         free(tmp_name);
489     }
490     program_name = basename;
491
492     free(program_version);
493     if (!strcmp(version, VERSION)) {
494         program_version = xasprintf("%s (Open vSwitch) "VERSION"\n",
495                                     program_name);
496     } else {
497         program_version = xasprintf("%s %s\n"
498                                     "Open vSwitch Library "VERSION"\n",
499                                     program_name, version);
500     }
501 }
502
503 /* Returns the name of the currently running thread or process. */
504 const char *
505 get_subprogram_name(void)
506 {
507     const char *name = subprogram_name_get();
508     return name ? name : "";
509 }
510
511 /* Sets 'subprogram_name' as the name of the currently running thread or
512  * process.  (This appears in log messages and may also be visible in system
513  * process listings and debuggers.) */
514 void
515 set_subprogram_name(const char *subprogram_name)
516 {
517     char *pname = xstrdup(subprogram_name ? subprogram_name : program_name);
518     free(subprogram_name_set(pname));
519
520 #if HAVE_GLIBC_PTHREAD_SETNAME_NP
521     pthread_setname_np(pthread_self(), pname);
522 #elif HAVE_NETBSD_PTHREAD_SETNAME_NP
523     pthread_setname_np(pthread_self(), "%s", pname);
524 #elif HAVE_PTHREAD_SET_NAME_NP
525     pthread_set_name_np(pthread_self(), pname);
526 #endif
527 }
528
529 /* Returns a pointer to a string describing the program version.  The
530  * caller must not modify or free the returned string.
531  */
532 const char *
533 ovs_get_program_version(void)
534 {
535     return program_version;
536 }
537
538 /* Returns a pointer to a string describing the program name.  The
539  * caller must not modify or free the returned string.
540  */
541 const char *
542 ovs_get_program_name(void)
543 {
544     return program_name;
545 }
546
547 /* Print the version information for the program.  */
548 void
549 ovs_print_version(uint8_t min_ofp, uint8_t max_ofp)
550 {
551     printf("%s", program_version);
552     if (min_ofp || max_ofp) {
553         printf("OpenFlow versions %#x:%#x\n", min_ofp, max_ofp);
554     }
555 }
556
557 /* Writes the 'size' bytes in 'buf' to 'stream' as hex bytes arranged 16 per
558  * line.  Numeric offsets are also included, starting at 'ofs' for the first
559  * byte in 'buf'.  If 'ascii' is true then the corresponding ASCII characters
560  * are also rendered alongside. */
561 void
562 ovs_hex_dump(FILE *stream, const void *buf_, size_t size,
563              uintptr_t ofs, bool ascii)
564 {
565   const uint8_t *buf = buf_;
566   const size_t per_line = 16; /* Maximum bytes per line. */
567
568   while (size > 0)
569     {
570       size_t start, end, n;
571       size_t i;
572
573       /* Number of bytes on this line. */
574       start = ofs % per_line;
575       end = per_line;
576       if (end - start > size)
577         end = start + size;
578       n = end - start;
579
580       /* Print line. */
581       fprintf(stream, "%08"PRIxMAX"  ", (uintmax_t) ROUND_DOWN(ofs, per_line));
582       for (i = 0; i < start; i++)
583         fprintf(stream, "   ");
584       for (; i < end; i++)
585         fprintf(stream, "%02x%c",
586                 buf[i - start], i == per_line / 2 - 1? '-' : ' ');
587       if (ascii)
588         {
589           for (; i < per_line; i++)
590             fprintf(stream, "   ");
591           fprintf(stream, "|");
592           for (i = 0; i < start; i++)
593             fprintf(stream, " ");
594           for (; i < end; i++) {
595               int c = buf[i - start];
596               putc(c >= 32 && c < 127 ? c : '.', stream);
597           }
598           for (; i < per_line; i++)
599             fprintf(stream, " ");
600           fprintf(stream, "|");
601         }
602       fprintf(stream, "\n");
603
604       ofs += n;
605       buf += n;
606       size -= n;
607     }
608 }
609
610 bool
611 str_to_int(const char *s, int base, int *i)
612 {
613     long long ll;
614     bool ok = str_to_llong(s, base, &ll);
615     *i = ll;
616     return ok;
617 }
618
619 bool
620 str_to_long(const char *s, int base, long *li)
621 {
622     long long ll;
623     bool ok = str_to_llong(s, base, &ll);
624     *li = ll;
625     return ok;
626 }
627
628 bool
629 str_to_llong(const char *s, int base, long long *x)
630 {
631     int save_errno = errno;
632     char *tail;
633     errno = 0;
634     *x = strtoll(s, &tail, base);
635     if (errno == EINVAL || errno == ERANGE || tail == s || *tail != '\0') {
636         errno = save_errno;
637         *x = 0;
638         return false;
639     } else {
640         errno = save_errno;
641         return true;
642     }
643 }
644
645 bool
646 str_to_uint(const char *s, int base, unsigned int *u)
647 {
648     long long ll;
649     bool ok = str_to_llong(s, base, &ll);
650     if (!ok || ll < 0 || ll > UINT_MAX) {
651         *u = 0;
652         return false;
653     } else {
654         *u = ll;
655         return true;
656     }
657 }
658
659 /* Converts floating-point string 's' into a double.  If successful, stores
660  * the double in '*d' and returns true; on failure, stores 0 in '*d' and
661  * returns false.
662  *
663  * Underflow (e.g. "1e-9999") is not considered an error, but overflow
664  * (e.g. "1e9999)" is. */
665 bool
666 str_to_double(const char *s, double *d)
667 {
668     int save_errno = errno;
669     char *tail;
670     errno = 0;
671     *d = strtod(s, &tail);
672     if (errno == EINVAL || (errno == ERANGE && *d != 0)
673         || tail == s || *tail != '\0') {
674         errno = save_errno;
675         *d = 0;
676         return false;
677     } else {
678         errno = save_errno;
679         return true;
680     }
681 }
682
683 /* Returns the value of 'c' as a hexadecimal digit. */
684 int
685 hexit_value(int c)
686 {
687     switch (c) {
688     case '0': case '1': case '2': case '3': case '4':
689     case '5': case '6': case '7': case '8': case '9':
690         return c - '0';
691
692     case 'a': case 'A':
693         return 0xa;
694
695     case 'b': case 'B':
696         return 0xb;
697
698     case 'c': case 'C':
699         return 0xc;
700
701     case 'd': case 'D':
702         return 0xd;
703
704     case 'e': case 'E':
705         return 0xe;
706
707     case 'f': case 'F':
708         return 0xf;
709
710     default:
711         return -1;
712     }
713 }
714
715 /* Returns the integer value of the 'n' hexadecimal digits starting at 's', or
716  * UINTMAX_MAX if one of those "digits" is not really a hex digit.  Sets '*ok'
717  * to true if the conversion succeeds or to false if a non-hex digit is
718  * detected. */
719 uintmax_t
720 hexits_value(const char *s, size_t n, bool *ok)
721 {
722     uintmax_t value;
723     size_t i;
724
725     value = 0;
726     for (i = 0; i < n; i++) {
727         int hexit = hexit_value(s[i]);
728         if (hexit < 0) {
729             *ok = false;
730             return UINTMAX_MAX;
731         }
732         value = (value << 4) + hexit;
733     }
734     *ok = true;
735     return value;
736 }
737
738 /* Parses the string in 's' as an integer in either hex or decimal format and
739  * puts the result right justified in the array 'valuep' that is 'field_width'
740  * big. If the string is in hex format, the value may be arbitrarily large;
741  * integers are limited to 64-bit values. (The rationale is that decimal is
742  * likely to represent a number and 64 bits is a reasonable maximum whereas
743  * hex could either be a number or a byte string.)
744  *
745  * On return 'tail' points to the first character in the string that was
746  * not parsed as part of the value. ERANGE is returned if the value is too
747  * large to fit in the given field. */
748 int
749 parse_int_string(const char *s, uint8_t *valuep, int field_width, char **tail)
750 {
751     unsigned long long int integer;
752     int i;
753
754     if (!strncmp(s, "0x", 2) || !strncmp(s, "0X", 2)) {
755         uint8_t *hexit_str;
756         int len = 0;
757         int val_idx;
758         int err = 0;
759
760         s += 2;
761         hexit_str = xmalloc(field_width * 2);
762
763         for (;;) {
764             uint8_t hexit;
765             bool ok;
766
767             s += strspn(s, " \t\r\n");
768             hexit = hexits_value(s, 1, &ok);
769             if (!ok) {
770                 *tail = CONST_CAST(char *, s);
771                 break;
772             }
773
774             if (hexit != 0 || len) {
775                 if (DIV_ROUND_UP(len + 1, 2) > field_width) {
776                     err = ERANGE;
777                     goto free;
778                 }
779
780                 hexit_str[len] = hexit;
781                 len++;
782             }
783             s++;
784         }
785
786         val_idx = field_width;
787         for (i = len - 1; i >= 0; i -= 2) {
788             val_idx--;
789             valuep[val_idx] = hexit_str[i];
790             if (i > 0) {
791                 valuep[val_idx] += hexit_str[i - 1] << 4;
792             }
793         }
794
795         memset(valuep, 0, val_idx);
796
797 free:
798         free(hexit_str);
799         return err;
800     }
801
802     errno = 0;
803     integer = strtoull(s, tail, 0);
804     if (errno) {
805         return errno;
806     }
807
808     for (i = field_width - 1; i >= 0; i--) {
809         valuep[i] = integer;
810         integer >>= 8;
811     }
812     if (integer) {
813         return ERANGE;
814     }
815
816     return 0;
817 }
818
819 /* Returns the current working directory as a malloc()'d string, or a null
820  * pointer if the current working directory cannot be determined. */
821 char *
822 get_cwd(void)
823 {
824     long int path_max;
825     size_t size;
826
827     /* Get maximum path length or at least a reasonable estimate. */
828 #ifndef _WIN32
829     path_max = pathconf(".", _PC_PATH_MAX);
830 #else
831     path_max = MAX_PATH;
832 #endif
833     size = (path_max < 0 ? 1024
834             : path_max > 10240 ? 10240
835             : path_max);
836
837     /* Get current working directory. */
838     for (;;) {
839         char *buf = xmalloc(size);
840         if (getcwd(buf, size)) {
841             return xrealloc(buf, strlen(buf) + 1);
842         } else {
843             int error = errno;
844             free(buf);
845             if (error != ERANGE) {
846                 VLOG_WARN("getcwd failed (%s)", ovs_strerror(error));
847                 return NULL;
848             }
849             size *= 2;
850         }
851     }
852 }
853
854 static char *
855 all_slashes_name(const char *s)
856 {
857     return xstrdup(s[0] == '/' && s[1] == '/' && s[2] != '/' ? "//"
858                    : s[0] == '/' ? "/"
859                    : ".");
860 }
861
862 #ifndef _WIN32
863 /* Returns the directory name portion of 'file_name' as a malloc()'d string,
864  * similar to the POSIX dirname() function but thread-safe. */
865 char *
866 dir_name(const char *file_name)
867 {
868     size_t len = strlen(file_name);
869     while (len > 0 && file_name[len - 1] == '/') {
870         len--;
871     }
872     while (len > 0 && file_name[len - 1] != '/') {
873         len--;
874     }
875     while (len > 0 && file_name[len - 1] == '/') {
876         len--;
877     }
878     return len ? xmemdup0(file_name, len) : all_slashes_name(file_name);
879 }
880
881 /* Returns the file name portion of 'file_name' as a malloc()'d string,
882  * similar to the POSIX basename() function but thread-safe. */
883 char *
884 base_name(const char *file_name)
885 {
886     size_t end, start;
887
888     end = strlen(file_name);
889     while (end > 0 && file_name[end - 1] == '/') {
890         end--;
891     }
892
893     if (!end) {
894         return all_slashes_name(file_name);
895     }
896
897     start = end;
898     while (start > 0 && file_name[start - 1] != '/') {
899         start--;
900     }
901
902     return xmemdup0(file_name + start, end - start);
903 }
904 #endif /* _WIN32 */
905
906 /* If 'file_name' starts with '/', returns a copy of 'file_name'.  Otherwise,
907  * returns an absolute path to 'file_name' considering it relative to 'dir',
908  * which itself must be absolute.  'dir' may be null or the empty string, in
909  * which case the current working directory is used.
910  *
911  * Returns a null pointer if 'dir' is null and getcwd() fails. */
912 char *
913 abs_file_name(const char *dir, const char *file_name)
914 {
915     if (file_name[0] == '/') {
916         return xstrdup(file_name);
917     } else if (dir && dir[0]) {
918         char *separator = dir[strlen(dir) - 1] == '/' ? "" : "/";
919         return xasprintf("%s%s%s", dir, separator, file_name);
920     } else {
921         char *cwd = get_cwd();
922         if (cwd) {
923             char *abs_name = xasprintf("%s/%s", cwd, file_name);
924             free(cwd);
925             return abs_name;
926         } else {
927             return NULL;
928         }
929     }
930 }
931
932 /* Like readlink(), but returns the link name as a null-terminated string in
933  * allocated memory that the caller must eventually free (with free()).
934  * Returns NULL on error, in which case errno is set appropriately. */
935 static char *
936 xreadlink(const char *filename)
937 {
938     size_t size;
939
940     for (size = 64; ; size *= 2) {
941         char *buf = xmalloc(size);
942         ssize_t retval = readlink(filename, buf, size);
943         int error = errno;
944
945         if (retval >= 0 && retval < size) {
946             buf[retval] = '\0';
947             return buf;
948         }
949
950         free(buf);
951         if (retval < 0) {
952             errno = error;
953             return NULL;
954         }
955     }
956 }
957
958 /* Returns a version of 'filename' with symlinks in the final component
959  * dereferenced.  This differs from realpath() in that:
960  *
961  *     - 'filename' need not exist.
962  *
963  *     - If 'filename' does exist as a symlink, its referent need not exist.
964  *
965  *     - Only symlinks in the final component of 'filename' are dereferenced.
966  *
967  * For Windows platform, this function returns a string that has the same
968  * value as the passed string.
969  *
970  * The caller must eventually free the returned string (with free()). */
971 char *
972 follow_symlinks(const char *filename)
973 {
974 #ifndef _WIN32
975     struct stat s;
976     char *fn;
977     int i;
978
979     fn = xstrdup(filename);
980     for (i = 0; i < 10; i++) {
981         char *linkname;
982         char *next_fn;
983
984         if (lstat(fn, &s) != 0 || !S_ISLNK(s.st_mode)) {
985             return fn;
986         }
987
988         linkname = xreadlink(fn);
989         if (!linkname) {
990             VLOG_WARN("%s: readlink failed (%s)",
991                       filename, ovs_strerror(errno));
992             return fn;
993         }
994
995         if (linkname[0] == '/') {
996             /* Target of symlink is absolute so use it raw. */
997             next_fn = linkname;
998         } else {
999             /* Target of symlink is relative so add to 'fn''s directory. */
1000             char *dir = dir_name(fn);
1001
1002             if (!strcmp(dir, ".")) {
1003                 next_fn = linkname;
1004             } else {
1005                 char *separator = dir[strlen(dir) - 1] == '/' ? "" : "/";
1006                 next_fn = xasprintf("%s%s%s", dir, separator, linkname);
1007                 free(linkname);
1008             }
1009
1010             free(dir);
1011         }
1012
1013         free(fn);
1014         fn = next_fn;
1015     }
1016
1017     VLOG_WARN("%s: too many levels of symlinks", filename);
1018     free(fn);
1019 #endif
1020     return xstrdup(filename);
1021 }
1022
1023 /* Pass a value to this function if it is marked with
1024  * __attribute__((warn_unused_result)) and you genuinely want to ignore
1025  * its return value.  (Note that every scalar type can be implicitly
1026  * converted to bool.) */
1027 void ignore(bool x OVS_UNUSED) { }
1028
1029 /* Returns an appropriate delimiter for inserting just before the 0-based item
1030  * 'index' in a list that has 'total' items in it. */
1031 const char *
1032 english_list_delimiter(size_t index, size_t total)
1033 {
1034     return (index == 0 ? ""
1035             : index < total - 1 ? ", "
1036             : total > 2 ? ", and "
1037             : " and ");
1038 }
1039
1040 /* Returns the number of trailing 0-bits in 'n'.  Undefined if 'n' == 0. */
1041 #if __GNUC__ >= 4 || _MSC_VER
1042 /* Defined inline in util.h. */
1043 #else
1044 /* Returns the number of trailing 0-bits in 'n'.  Undefined if 'n' == 0. */
1045 int
1046 raw_ctz(uint64_t n)
1047 {
1048     uint64_t k;
1049     int count = 63;
1050
1051 #define CTZ_STEP(X)                             \
1052     k = n << (X);                               \
1053     if (k) {                                    \
1054         count -= X;                             \
1055         n = k;                                  \
1056     }
1057     CTZ_STEP(32);
1058     CTZ_STEP(16);
1059     CTZ_STEP(8);
1060     CTZ_STEP(4);
1061     CTZ_STEP(2);
1062     CTZ_STEP(1);
1063 #undef CTZ_STEP
1064
1065     return count;
1066 }
1067
1068 /* Returns the number of leading 0-bits in 'n'.  Undefined if 'n' == 0. */
1069 int
1070 raw_clz64(uint64_t n)
1071 {
1072     uint64_t k;
1073     int count = 63;
1074
1075 #define CLZ_STEP(X)                             \
1076     k = n >> (X);                               \
1077     if (k) {                                    \
1078         count -= X;                             \
1079         n = k;                                  \
1080     }
1081     CLZ_STEP(32);
1082     CLZ_STEP(16);
1083     CLZ_STEP(8);
1084     CLZ_STEP(4);
1085     CLZ_STEP(2);
1086     CLZ_STEP(1);
1087 #undef CLZ_STEP
1088
1089     return count;
1090 }
1091 #endif
1092
1093 #if NEED_COUNT_1BITS_8
1094 #define INIT1(X)                                \
1095     ((((X) & (1 << 0)) != 0) +                  \
1096      (((X) & (1 << 1)) != 0) +                  \
1097      (((X) & (1 << 2)) != 0) +                  \
1098      (((X) & (1 << 3)) != 0) +                  \
1099      (((X) & (1 << 4)) != 0) +                  \
1100      (((X) & (1 << 5)) != 0) +                  \
1101      (((X) & (1 << 6)) != 0) +                  \
1102      (((X) & (1 << 7)) != 0))
1103 #define INIT2(X)   INIT1(X),  INIT1((X) +  1)
1104 #define INIT4(X)   INIT2(X),  INIT2((X) +  2)
1105 #define INIT8(X)   INIT4(X),  INIT4((X) +  4)
1106 #define INIT16(X)  INIT8(X),  INIT8((X) +  8)
1107 #define INIT32(X) INIT16(X), INIT16((X) + 16)
1108 #define INIT64(X) INIT32(X), INIT32((X) + 32)
1109
1110 const uint8_t count_1bits_8[256] = {
1111     INIT64(0), INIT64(64), INIT64(128), INIT64(192)
1112 };
1113 #endif
1114
1115 /* Returns true if the 'n' bytes starting at 'p' are zeros. */
1116 bool
1117 is_all_zeros(const void *p_, size_t n)
1118 {
1119     const uint8_t *p = p_;
1120     size_t i;
1121
1122     for (i = 0; i < n; i++) {
1123         if (p[i] != 0x00) {
1124             return false;
1125         }
1126     }
1127     return true;
1128 }
1129
1130 /* Returns true if the 'n' bytes starting at 'p' are 0xff. */
1131 bool
1132 is_all_ones(const void *p_, size_t n)
1133 {
1134     const uint8_t *p = p_;
1135     size_t i;
1136
1137     for (i = 0; i < n; i++) {
1138         if (p[i] != 0xff) {
1139             return false;
1140         }
1141     }
1142     return true;
1143 }
1144
1145 /* Copies 'n_bits' bits starting from bit 'src_ofs' in 'src' to the 'n_bits'
1146  * starting from bit 'dst_ofs' in 'dst'.  'src' is 'src_len' bytes long and
1147  * 'dst' is 'dst_len' bytes long.
1148  *
1149  * If you consider all of 'src' to be a single unsigned integer in network byte
1150  * order, then bit N is the bit with value 2**N.  That is, bit 0 is the bit
1151  * with value 1 in src[src_len - 1], bit 1 is the bit with value 2, bit 2 is
1152  * the bit with value 4, ..., bit 8 is the bit with value 1 in src[src_len -
1153  * 2], and so on.  Similarly for 'dst'.
1154  *
1155  * Required invariants:
1156  *   src_ofs + n_bits <= src_len * 8
1157  *   dst_ofs + n_bits <= dst_len * 8
1158  *   'src' and 'dst' must not overlap.
1159  */
1160 void
1161 bitwise_copy(const void *src_, unsigned int src_len, unsigned int src_ofs,
1162              void *dst_, unsigned int dst_len, unsigned int dst_ofs,
1163              unsigned int n_bits)
1164 {
1165     const uint8_t *src = src_;
1166     uint8_t *dst = dst_;
1167
1168     src += src_len - (src_ofs / 8 + 1);
1169     src_ofs %= 8;
1170
1171     dst += dst_len - (dst_ofs / 8 + 1);
1172     dst_ofs %= 8;
1173
1174     if (src_ofs == 0 && dst_ofs == 0) {
1175         unsigned int n_bytes = n_bits / 8;
1176         if (n_bytes) {
1177             dst -= n_bytes - 1;
1178             src -= n_bytes - 1;
1179             memcpy(dst, src, n_bytes);
1180
1181             n_bits %= 8;
1182             src--;
1183             dst--;
1184         }
1185         if (n_bits) {
1186             uint8_t mask = (1 << n_bits) - 1;
1187             *dst = (*dst & ~mask) | (*src & mask);
1188         }
1189     } else {
1190         while (n_bits > 0) {
1191             unsigned int max_copy = 8 - MAX(src_ofs, dst_ofs);
1192             unsigned int chunk = MIN(n_bits, max_copy);
1193             uint8_t mask = ((1 << chunk) - 1) << dst_ofs;
1194
1195             *dst &= ~mask;
1196             *dst |= ((*src >> src_ofs) << dst_ofs) & mask;
1197
1198             src_ofs += chunk;
1199             if (src_ofs == 8) {
1200                 src--;
1201                 src_ofs = 0;
1202             }
1203             dst_ofs += chunk;
1204             if (dst_ofs == 8) {
1205                 dst--;
1206                 dst_ofs = 0;
1207             }
1208             n_bits -= chunk;
1209         }
1210     }
1211 }
1212
1213 /* Zeros the 'n_bits' bits starting from bit 'dst_ofs' in 'dst'.  'dst' is
1214  * 'dst_len' bytes long.
1215  *
1216  * If you consider all of 'dst' to be a single unsigned integer in network byte
1217  * order, then bit N is the bit with value 2**N.  That is, bit 0 is the bit
1218  * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
1219  * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
1220  * 2], and so on.
1221  *
1222  * Required invariant:
1223  *   dst_ofs + n_bits <= dst_len * 8
1224  */
1225 void
1226 bitwise_zero(void *dst_, unsigned int dst_len, unsigned dst_ofs,
1227              unsigned int n_bits)
1228 {
1229     uint8_t *dst = dst_;
1230
1231     if (!n_bits) {
1232         return;
1233     }
1234
1235     dst += dst_len - (dst_ofs / 8 + 1);
1236     dst_ofs %= 8;
1237
1238     if (dst_ofs) {
1239         unsigned int chunk = MIN(n_bits, 8 - dst_ofs);
1240
1241         *dst &= ~(((1 << chunk) - 1) << dst_ofs);
1242
1243         n_bits -= chunk;
1244         if (!n_bits) {
1245             return;
1246         }
1247
1248         dst--;
1249     }
1250
1251     while (n_bits >= 8) {
1252         *dst-- = 0;
1253         n_bits -= 8;
1254     }
1255
1256     if (n_bits) {
1257         *dst &= ~((1 << n_bits) - 1);
1258     }
1259 }
1260
1261 /* Sets to 1 all of the 'n_bits' bits starting from bit 'dst_ofs' in 'dst'.
1262  * 'dst' is 'dst_len' bytes long.
1263  *
1264  * If you consider all of 'dst' to be a single unsigned integer in network byte
1265  * order, then bit N is the bit with value 2**N.  That is, bit 0 is the bit
1266  * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
1267  * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
1268  * 2], and so on.
1269  *
1270  * Required invariant:
1271  *   dst_ofs + n_bits <= dst_len * 8
1272  */
1273 void
1274 bitwise_one(void *dst_, unsigned int dst_len, unsigned dst_ofs,
1275             unsigned int n_bits)
1276 {
1277     uint8_t *dst = dst_;
1278
1279     if (!n_bits) {
1280         return;
1281     }
1282
1283     dst += dst_len - (dst_ofs / 8 + 1);
1284     dst_ofs %= 8;
1285
1286     if (dst_ofs) {
1287         unsigned int chunk = MIN(n_bits, 8 - dst_ofs);
1288
1289         *dst |= ((1 << chunk) - 1) << dst_ofs;
1290
1291         n_bits -= chunk;
1292         if (!n_bits) {
1293             return;
1294         }
1295
1296         dst--;
1297     }
1298
1299     while (n_bits >= 8) {
1300         *dst-- = 0xff;
1301         n_bits -= 8;
1302     }
1303
1304     if (n_bits) {
1305         *dst |= (1 << n_bits) - 1;
1306     }
1307 }
1308
1309 /* Scans the 'n_bits' bits starting from bit 'dst_ofs' in 'dst' for 1-bits.
1310  * Returns false if any 1-bits are found, otherwise true.  'dst' is 'dst_len'
1311  * bytes long.
1312  *
1313  * If you consider all of 'dst' to be a single unsigned integer in network byte
1314  * order, then bit N is the bit with value 2**N.  That is, bit 0 is the bit
1315  * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
1316  * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
1317  * 2], and so on.
1318  *
1319  * Required invariant:
1320  *   dst_ofs + n_bits <= dst_len * 8
1321  */
1322 bool
1323 bitwise_is_all_zeros(const void *p_, unsigned int len, unsigned int ofs,
1324                      unsigned int n_bits)
1325 {
1326     const uint8_t *p = p_;
1327
1328     if (!n_bits) {
1329         return true;
1330     }
1331
1332     p += len - (ofs / 8 + 1);
1333     ofs %= 8;
1334
1335     if (ofs) {
1336         unsigned int chunk = MIN(n_bits, 8 - ofs);
1337
1338         if (*p & (((1 << chunk) - 1) << ofs)) {
1339             return false;
1340         }
1341
1342         n_bits -= chunk;
1343         if (!n_bits) {
1344             return true;
1345         }
1346
1347         p--;
1348     }
1349
1350     while (n_bits >= 8) {
1351         if (*p) {
1352             return false;
1353         }
1354         n_bits -= 8;
1355         p--;
1356     }
1357
1358     if (n_bits && *p & ((1 << n_bits) - 1)) {
1359         return false;
1360     }
1361
1362     return true;
1363 }
1364
1365 /* Scans the bits in 'p' that have bit offsets 'start' (inclusive) through
1366  * 'end' (exclusive) for the first bit with value 'target'.  If one is found,
1367  * returns its offset, otherwise 'end'.  'p' is 'len' bytes long.
1368  *
1369  * If you consider all of 'p' to be a single unsigned integer in network byte
1370  * order, then bit N is the bit with value 2**N.  That is, bit 0 is the bit
1371  * with value 1 in p[len - 1], bit 1 is the bit with value 2, bit 2 is the bit
1372  * with value 4, ..., bit 8 is the bit with value 1 in p[len - 2], and so on.
1373  *
1374  * Required invariant:
1375  *   start <= end
1376  */
1377 unsigned int
1378 bitwise_scan(const void *p, unsigned int len, bool target, unsigned int start,
1379              unsigned int end)
1380 {
1381     unsigned int ofs;
1382
1383     for (ofs = start; ofs < end; ofs++) {
1384         if (bitwise_get_bit(p, len, ofs) == target) {
1385             break;
1386         }
1387     }
1388     return ofs;
1389 }
1390
1391 /* Scans the bits in 'p' that have bit offsets 'start' (inclusive) through
1392  * 'end' (exclusive) for the first bit with value 'target', in reverse order.
1393  * If one is found, returns its offset, otherwise 'end'.  'p' is 'len' bytes
1394  * long.
1395  *
1396  * If you consider all of 'p' to be a single unsigned integer in network byte
1397  * order, then bit N is the bit with value 2**N.  That is, bit 0 is the bit
1398  * with value 1 in p[len - 1], bit 1 is the bit with value 2, bit 2 is the bit
1399  * with value 4, ..., bit 8 is the bit with value 1 in p[len - 2], and so on.
1400  *
1401  * To scan an entire bit array in reverse order, specify start == len * 8 - 1
1402  * and end == -1, in which case the return value is nonnegative if successful
1403  * and -1 if no 'target' match is found.
1404  *
1405  * Required invariant:
1406  *   start >= end
1407  */
1408 int
1409 bitwise_rscan(const void *p, unsigned int len, bool target, int start, int end)
1410 {
1411     const uint8_t *s = p;
1412     int start_byte = len - (start / 8 + 1);
1413     int end_byte = len - (end / 8 + 1);
1414     int ofs_byte;
1415     int ofs;
1416     uint8_t the_byte;
1417
1418     /* Find the target in the start_byte from starting offset */
1419     ofs_byte = start_byte;
1420     the_byte = s[ofs_byte];
1421     for (ofs = start % 8; ofs >= 0; ofs--) {
1422         if (((the_byte & (1u << ofs)) != 0) == target) {
1423             break;
1424         }
1425     }
1426     if (ofs < 0) {
1427         /* Target not found in start byte, continue searching byte by byte */
1428         for (ofs_byte = start_byte + 1; ofs_byte <= end_byte; ofs_byte++) {
1429             if ((target && s[ofs_byte])
1430                     || (!target && (s[ofs_byte] != 0xff))) {
1431                break;
1432             }
1433         }
1434         if (ofs_byte > end_byte) {
1435             return end;
1436         }
1437         the_byte = s[ofs_byte];
1438         /* Target is in the_byte, find it bit by bit */
1439         for (ofs = 7; ofs >= 0; ofs--) {
1440             if (((the_byte & (1u << ofs)) != 0) == target) {
1441                 break;
1442             }
1443         }
1444     }
1445     int ret = (len - ofs_byte) * 8 - (8 - ofs);
1446     if (ret < end) {
1447         return end;
1448     }
1449     return ret;
1450 }
1451
1452 /* Copies the 'n_bits' low-order bits of 'value' into the 'n_bits' bits
1453  * starting at bit 'dst_ofs' in 'dst', which is 'dst_len' bytes long.
1454  *
1455  * If you consider all of 'dst' to be a single unsigned integer in network byte
1456  * order, then bit N is the bit with value 2**N.  That is, bit 0 is the bit
1457  * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
1458  * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
1459  * 2], and so on.
1460  *
1461  * Required invariants:
1462  *   dst_ofs + n_bits <= dst_len * 8
1463  *   n_bits <= 64
1464  */
1465 void
1466 bitwise_put(uint64_t value,
1467             void *dst, unsigned int dst_len, unsigned int dst_ofs,
1468             unsigned int n_bits)
1469 {
1470     ovs_be64 n_value = htonll(value);
1471     bitwise_copy(&n_value, sizeof n_value, 0,
1472                  dst, dst_len, dst_ofs,
1473                  n_bits);
1474 }
1475
1476 /* Returns the value of the 'n_bits' bits starting at bit 'src_ofs' in 'src',
1477  * which is 'src_len' bytes long.
1478  *
1479  * If you consider all of 'src' to be a single unsigned integer in network byte
1480  * order, then bit N is the bit with value 2**N.  That is, bit 0 is the bit
1481  * with value 1 in src[src_len - 1], bit 1 is the bit with value 2, bit 2 is
1482  * the bit with value 4, ..., bit 8 is the bit with value 1 in src[src_len -
1483  * 2], and so on.
1484  *
1485  * Required invariants:
1486  *   src_ofs + n_bits <= src_len * 8
1487  *   n_bits <= 64
1488  */
1489 uint64_t
1490 bitwise_get(const void *src, unsigned int src_len,
1491             unsigned int src_ofs, unsigned int n_bits)
1492 {
1493     ovs_be64 value = htonll(0);
1494
1495     bitwise_copy(src, src_len, src_ofs,
1496                  &value, sizeof value, 0,
1497                  n_bits);
1498     return ntohll(value);
1499 }
1500
1501 /* Returns the value of the bit with offset 'ofs' in 'src', which is 'len'
1502  * bytes long.
1503  *
1504  * If you consider all of 'src' to be a single unsigned integer in network byte
1505  * order, then bit N is the bit with value 2**N.  That is, bit 0 is the bit
1506  * with value 1 in src[len - 1], bit 1 is the bit with value 2, bit 2 is the
1507  * bit with value 4, ..., bit 8 is the bit with value 1 in src[len - 2], and so
1508  * on.
1509  *
1510  * Required invariants:
1511  *   ofs < len * 8
1512  */
1513 bool
1514 bitwise_get_bit(const void *src_, unsigned int len, unsigned int ofs)
1515 {
1516     const uint8_t *src = src_;
1517
1518     return (src[len - (ofs / 8 + 1)] & (1u << (ofs % 8))) != 0;
1519 }
1520
1521 /* Sets the bit with offset 'ofs' in 'dst', which is 'len' bytes long, to 0.
1522  *
1523  * If you consider all of 'dst' to be a single unsigned integer in network byte
1524  * order, then bit N is the bit with value 2**N.  That is, bit 0 is the bit
1525  * with value 1 in dst[len - 1], bit 1 is the bit with value 2, bit 2 is the
1526  * bit with value 4, ..., bit 8 is the bit with value 1 in dst[len - 2], and so
1527  * on.
1528  *
1529  * Required invariants:
1530  *   ofs < len * 8
1531  */
1532 void
1533 bitwise_put0(void *dst_, unsigned int len, unsigned int ofs)
1534 {
1535     uint8_t *dst = dst_;
1536
1537     dst[len - (ofs / 8 + 1)] &= ~(1u << (ofs % 8));
1538 }
1539
1540 /* Sets the bit with offset 'ofs' in 'dst', which is 'len' bytes long, to 1.
1541  *
1542  * If you consider all of 'dst' to be a single unsigned integer in network byte
1543  * order, then bit N is the bit with value 2**N.  That is, bit 0 is the bit
1544  * with value 1 in dst[len - 1], bit 1 is the bit with value 2, bit 2 is the
1545  * bit with value 4, ..., bit 8 is the bit with value 1 in dst[len - 2], and so
1546  * on.
1547  *
1548  * Required invariants:
1549  *   ofs < len * 8
1550  */
1551 void
1552 bitwise_put1(void *dst_, unsigned int len, unsigned int ofs)
1553 {
1554     uint8_t *dst = dst_;
1555
1556     dst[len - (ofs / 8 + 1)] |= 1u << (ofs % 8);
1557 }
1558
1559 /* Sets the bit with offset 'ofs' in 'dst', which is 'len' bytes long, to 'b'.
1560  *
1561  * If you consider all of 'dst' to be a single unsigned integer in network byte
1562  * order, then bit N is the bit with value 2**N.  That is, bit 0 is the bit
1563  * with value 1 in dst[len - 1], bit 1 is the bit with value 2, bit 2 is the
1564  * bit with value 4, ..., bit 8 is the bit with value 1 in dst[len - 2], and so
1565  * on.
1566  *
1567  * Required invariants:
1568  *   ofs < len * 8
1569  */
1570 void
1571 bitwise_put_bit(void *dst, unsigned int len, unsigned int ofs, bool b)
1572 {
1573     if (b) {
1574         bitwise_put1(dst, len, ofs);
1575     } else {
1576         bitwise_put0(dst, len, ofs);
1577     }
1578 }
1579
1580 /* Flips the bit with offset 'ofs' in 'dst', which is 'len' bytes long.
1581  *
1582  * If you consider all of 'dst' to be a single unsigned integer in network byte
1583  * order, then bit N is the bit with value 2**N.  That is, bit 0 is the bit
1584  * with value 1 in dst[len - 1], bit 1 is the bit with value 2, bit 2 is the
1585  * bit with value 4, ..., bit 8 is the bit with value 1 in dst[len - 2], and so
1586  * on.
1587  *
1588  * Required invariants:
1589  *   ofs < len * 8
1590  */
1591 void
1592 bitwise_toggle_bit(void *dst_, unsigned int len, unsigned int ofs)
1593 {
1594     uint8_t *dst = dst_;
1595
1596     dst[len - (ofs / 8 + 1)] ^= 1u << (ofs % 8);
1597 }
1598 \f
1599 /* ovs_scan */
1600
1601 struct scan_spec {
1602     unsigned int width;
1603     enum {
1604         SCAN_DISCARD,
1605         SCAN_CHAR,
1606         SCAN_SHORT,
1607         SCAN_INT,
1608         SCAN_LONG,
1609         SCAN_LLONG,
1610         SCAN_INTMAX_T,
1611         SCAN_PTRDIFF_T,
1612         SCAN_SIZE_T
1613     } type;
1614 };
1615
1616 static const char *
1617 skip_spaces(const char *s)
1618 {
1619     while (isspace((unsigned char) *s)) {
1620         s++;
1621     }
1622     return s;
1623 }
1624
1625 static const char *
1626 scan_int(const char *s, const struct scan_spec *spec, int base, va_list *args)
1627 {
1628     const char *start = s;
1629     uintmax_t value;
1630     bool negative;
1631     int n_digits;
1632
1633     negative = *s == '-';
1634     s += *s == '-' || *s == '+';
1635
1636     if ((!base || base == 16) && *s == '0' && (s[1] == 'x' || s[1] == 'X')) {
1637         base = 16;
1638         s += 2;
1639     } else if (!base) {
1640         base = *s == '0' ? 8 : 10;
1641     }
1642
1643     if (s - start >= spec->width) {
1644         return NULL;
1645     }
1646
1647     value = 0;
1648     n_digits = 0;
1649     while (s - start < spec->width) {
1650         int digit = hexit_value(*s);
1651
1652         if (digit < 0 || digit >= base) {
1653             break;
1654         }
1655         value = value * base + digit;
1656         n_digits++;
1657         s++;
1658     }
1659     if (!n_digits) {
1660         return NULL;
1661     }
1662
1663     if (negative) {
1664         value = -value;
1665     }
1666
1667     switch (spec->type) {
1668     case SCAN_DISCARD:
1669         break;
1670     case SCAN_CHAR:
1671         *va_arg(*args, char *) = value;
1672         break;
1673     case SCAN_SHORT:
1674         *va_arg(*args, short int *) = value;
1675         break;
1676     case SCAN_INT:
1677         *va_arg(*args, int *) = value;
1678         break;
1679     case SCAN_LONG:
1680         *va_arg(*args, long int *) = value;
1681         break;
1682     case SCAN_LLONG:
1683         *va_arg(*args, long long int *) = value;
1684         break;
1685     case SCAN_INTMAX_T:
1686         *va_arg(*args, intmax_t *) = value;
1687         break;
1688     case SCAN_PTRDIFF_T:
1689         *va_arg(*args, ptrdiff_t *) = value;
1690         break;
1691     case SCAN_SIZE_T:
1692         *va_arg(*args, size_t *) = value;
1693         break;
1694     }
1695     return s;
1696 }
1697
1698 static const char *
1699 skip_digits(const char *s)
1700 {
1701     while (*s >= '0' && *s <= '9') {
1702         s++;
1703     }
1704     return s;
1705 }
1706
1707 static const char *
1708 scan_float(const char *s, const struct scan_spec *spec, va_list *args)
1709 {
1710     const char *start = s;
1711     long double value;
1712     char *tail;
1713     char *copy;
1714     bool ok;
1715
1716     s += *s == '+' || *s == '-';
1717     s = skip_digits(s);
1718     if (*s == '.') {
1719         s = skip_digits(s + 1);
1720     }
1721     if (*s == 'e' || *s == 'E') {
1722         s++;
1723         s += *s == '+' || *s == '-';
1724         s = skip_digits(s);
1725     }
1726
1727     if (s - start > spec->width) {
1728         s = start + spec->width;
1729     }
1730
1731     copy = xmemdup0(start, s - start);
1732     value = strtold(copy, &tail);
1733     ok = *tail == '\0';
1734     free(copy);
1735     if (!ok) {
1736         return NULL;
1737     }
1738
1739     switch (spec->type) {
1740     case SCAN_DISCARD:
1741         break;
1742     case SCAN_INT:
1743         *va_arg(*args, float *) = value;
1744         break;
1745     case SCAN_LONG:
1746         *va_arg(*args, double *) = value;
1747         break;
1748     case SCAN_LLONG:
1749         *va_arg(*args, long double *) = value;
1750         break;
1751
1752     case SCAN_CHAR:
1753     case SCAN_SHORT:
1754     case SCAN_INTMAX_T:
1755     case SCAN_PTRDIFF_T:
1756     case SCAN_SIZE_T:
1757         OVS_NOT_REACHED();
1758     }
1759     return s;
1760 }
1761
1762 static void
1763 scan_output_string(const struct scan_spec *spec,
1764                    const char *s, size_t n,
1765                    va_list *args)
1766 {
1767     if (spec->type != SCAN_DISCARD) {
1768         char *out = va_arg(*args, char *);
1769         memcpy(out, s, n);
1770         out[n] = '\0';
1771     }
1772 }
1773
1774 static const char *
1775 scan_string(const char *s, const struct scan_spec *spec, va_list *args)
1776 {
1777     size_t n;
1778
1779     for (n = 0; n < spec->width; n++) {
1780         if (!s[n] || isspace((unsigned char) s[n])) {
1781             break;
1782         }
1783     }
1784     if (!n) {
1785         return NULL;
1786     }
1787
1788     scan_output_string(spec, s, n, args);
1789     return s + n;
1790 }
1791
1792 static const char *
1793 parse_scanset(const char *p_, unsigned long *set, bool *complemented)
1794 {
1795     const uint8_t *p = (const uint8_t *) p_;
1796
1797     *complemented = *p == '^';
1798     p += *complemented;
1799
1800     if (*p == ']') {
1801         bitmap_set1(set, ']');
1802         p++;
1803     }
1804
1805     while (*p && *p != ']') {
1806         if (p[1] == '-' && p[2] != ']' && p[2] > *p) {
1807             bitmap_set_multiple(set, *p, p[2] - *p + 1, true);
1808             p += 3;
1809         } else {
1810             bitmap_set1(set, *p++);
1811         }
1812     }
1813     if (*p == ']') {
1814         p++;
1815     }
1816     return (const char *) p;
1817 }
1818
1819 static const char *
1820 scan_set(const char *s, const struct scan_spec *spec, const char **pp,
1821          va_list *args)
1822 {
1823     unsigned long set[BITMAP_N_LONGS(UCHAR_MAX + 1)];
1824     bool complemented;
1825     unsigned int n;
1826
1827     /* Parse the scan set. */
1828     memset(set, 0, sizeof set);
1829     *pp = parse_scanset(*pp, set, &complemented);
1830
1831     /* Parse the data. */
1832     n = 0;
1833     while (s[n]
1834            && bitmap_is_set(set, (unsigned char) s[n]) == !complemented
1835            && n < spec->width) {
1836         n++;
1837     }
1838     if (!n) {
1839         return NULL;
1840     }
1841     scan_output_string(spec, s, n, args);
1842     return s + n;
1843 }
1844
1845 static const char *
1846 scan_chars(const char *s, const struct scan_spec *spec, va_list *args)
1847 {
1848     unsigned int n = spec->width == UINT_MAX ? 1 : spec->width;
1849
1850     if (strlen(s) < n) {
1851         return NULL;
1852     }
1853     if (spec->type != SCAN_DISCARD) {
1854         memcpy(va_arg(*args, char *), s, n);
1855     }
1856     return s + n;
1857 }
1858
1859 static bool
1860 ovs_scan__(const char *s, int *n, const char *format, va_list *args)
1861 {
1862     const char *const start = s;
1863     bool ok = false;
1864     const char *p;
1865
1866     p = format;
1867     while (*p != '\0') {
1868         struct scan_spec spec;
1869         unsigned char c = *p++;
1870         bool discard;
1871
1872         if (isspace(c)) {
1873             s = skip_spaces(s);
1874             continue;
1875         } else if (c != '%') {
1876             if (*s != c) {
1877                 goto exit;
1878             }
1879             s++;
1880             continue;
1881         } else if (*p == '%') {
1882             if (*s++ != '%') {
1883                 goto exit;
1884             }
1885             p++;
1886             continue;
1887         }
1888
1889         /* Parse '*' flag. */
1890         discard = *p == '*';
1891         p += discard;
1892
1893         /* Parse field width. */
1894         spec.width = 0;
1895         while (*p >= '0' && *p <= '9') {
1896             spec.width = spec.width * 10 + (*p++ - '0');
1897         }
1898         if (spec.width == 0) {
1899             spec.width = UINT_MAX;
1900         }
1901
1902         /* Parse type modifier. */
1903         switch (*p) {
1904         case 'h':
1905             if (p[1] == 'h') {
1906                 spec.type = SCAN_CHAR;
1907                 p += 2;
1908             } else {
1909                 spec.type = SCAN_SHORT;
1910                 p++;
1911             }
1912             break;
1913
1914         case 'j':
1915             spec.type = SCAN_INTMAX_T;
1916             p++;
1917             break;
1918
1919         case 'l':
1920             if (p[1] == 'l') {
1921                 spec.type = SCAN_LLONG;
1922                 p += 2;
1923             } else {
1924                 spec.type = SCAN_LONG;
1925                 p++;
1926             }
1927             break;
1928
1929         case 'L':
1930         case 'q':
1931             spec.type = SCAN_LLONG;
1932             p++;
1933             break;
1934
1935         case 't':
1936             spec.type = SCAN_PTRDIFF_T;
1937             p++;
1938             break;
1939
1940         case 'z':
1941             spec.type = SCAN_SIZE_T;
1942             p++;
1943             break;
1944
1945         default:
1946             spec.type = SCAN_INT;
1947             break;
1948         }
1949
1950         if (discard) {
1951             spec.type = SCAN_DISCARD;
1952         }
1953
1954         c = *p++;
1955         if (c != 'c' && c != 'n' && c != '[') {
1956             s = skip_spaces(s);
1957         }
1958         switch (c) {
1959         case 'd':
1960             s = scan_int(s, &spec, 10, args);
1961             break;
1962
1963         case 'i':
1964             s = scan_int(s, &spec, 0, args);
1965             break;
1966
1967         case 'o':
1968             s = scan_int(s, &spec, 8, args);
1969             break;
1970
1971         case 'u':
1972             s = scan_int(s, &spec, 10, args);
1973             break;
1974
1975         case 'x':
1976         case 'X':
1977             s = scan_int(s, &spec, 16, args);
1978             break;
1979
1980         case 'e':
1981         case 'f':
1982         case 'g':
1983         case 'E':
1984         case 'G':
1985             s = scan_float(s, &spec, args);
1986             break;
1987
1988         case 's':
1989             s = scan_string(s, &spec, args);
1990             break;
1991
1992         case '[':
1993             s = scan_set(s, &spec, &p, args);
1994             break;
1995
1996         case 'c':
1997             s = scan_chars(s, &spec, args);
1998             break;
1999
2000         case 'n':
2001             if (spec.type != SCAN_DISCARD) {
2002                 *va_arg(*args, int *) = s - start;
2003             }
2004             break;
2005         }
2006
2007         if (!s) {
2008             goto exit;
2009         }
2010     }
2011     if (n) {
2012         *n = s - start;
2013     }
2014
2015     ok = true;
2016 exit:
2017     return ok;
2018 }
2019
2020 /* This is an implementation of the standard sscanf() function, with the
2021  * following exceptions:
2022  *
2023  *   - It returns true if the entire format was successfully scanned and
2024  *     converted, false if any conversion failed.
2025  *
2026  *   - The standard doesn't define sscanf() behavior when an out-of-range value
2027  *     is scanned, e.g. if a "%"PRIi8 conversion scans "-1" or "0x1ff".  Some
2028  *     implementations consider this an error and stop scanning.  This
2029  *     implementation never considers an out-of-range value an error; instead,
2030  *     it stores the least-significant bits of the converted value in the
2031  *     destination, e.g. the value 255 for both examples earlier.
2032  *
2033  *   - Only single-byte characters are supported, that is, the 'l' modifier
2034  *     on %s, %[, and %c is not supported.  The GNU extension 'a' modifier is
2035  *     also not supported.
2036  *
2037  *   - %p is not supported.
2038  */
2039 bool
2040 ovs_scan(const char *s, const char *format, ...)
2041 {
2042     va_list args;
2043     bool res;
2044
2045     va_start(args, format);
2046     res = ovs_scan__(s, NULL, format, &args);
2047     va_end(args);
2048     return res;
2049 }
2050
2051 /*
2052  * This function is similar to ovs_scan(), with an extra parameter `n` added to
2053  * return the number of scanned characters.
2054  */
2055 bool
2056 ovs_scan_len(const char *s, int *n, const char *format, ...)
2057 {
2058     va_list args;
2059     bool success;
2060     int n1;
2061
2062     va_start(args, format);
2063     success = ovs_scan__(s + *n, &n1, format, &args);
2064     va_end(args);
2065     if (success) {
2066         *n = *n + n1;
2067     }
2068     return success;
2069 }
2070
2071 void
2072 xsleep(unsigned int seconds)
2073 {
2074     ovsrcu_quiesce_start();
2075 #ifdef _WIN32
2076     Sleep(seconds * 1000);
2077 #else
2078     sleep(seconds);
2079 #endif
2080     ovsrcu_quiesce_end();
2081 }
2082
2083 /* Determine whether standard output is a tty or not. This is useful to decide
2084  * whether to use color output or not when --color option for utilities is set
2085  * to `auto`.
2086  */
2087 bool
2088 is_stdout_a_tty(void)
2089 {
2090     char const *t = getenv("TERM");
2091     return (isatty(STDOUT_FILENO) && t && strcmp(t, "dumb") != 0);
2092 }
2093
2094 #ifdef _WIN32
2095 \f
2096 char *
2097 ovs_format_message(int error)
2098 {
2099     enum { BUFSIZE = sizeof strerror_buffer_get()->s };
2100     char *buffer = strerror_buffer_get()->s;
2101
2102     if (error == 0) {
2103         /* See ovs_strerror */
2104         return "Success";
2105     }
2106
2107     FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
2108                   NULL, error, 0, buffer, BUFSIZE, NULL);
2109     return buffer;
2110 }
2111
2112 /* Returns a null-terminated string that explains the last error.
2113  * Use this function to get the error string for WINAPI calls. */
2114 char *
2115 ovs_lasterror_to_string(void)
2116 {
2117     return ovs_format_message(GetLastError());
2118 }
2119
2120 int
2121 ftruncate(int fd, off_t length)
2122 {
2123     int error;
2124
2125     error = _chsize_s(fd, length);
2126     if (error) {
2127         return -1;
2128     }
2129     return 0;
2130 }
2131
2132 OVS_CONSTRUCTOR(winsock_start) {
2133     WSADATA wsaData;
2134     int error;
2135
2136     error = WSAStartup(MAKEWORD(2, 2), &wsaData);
2137     if (error != 0) {
2138         VLOG_FATAL("WSAStartup failed: %s", sock_strerror(sock_errno()));
2139    }
2140 }
2141 #endif