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