tests: Fix unit test failure.
[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     save_errno = errno;
417     buffer = strerror_buffer_get()->s;
418
419 #if STRERROR_R_CHAR_P
420     /* GNU style strerror_r() might return an immutable static string, or it
421      * might write and return 'buffer', but in either case we can pass the
422      * returned string directly to the caller. */
423     s = strerror_r(error, buffer, BUFSIZE);
424 #else  /* strerror_r() returns an int. */
425     s = buffer;
426     if (strerror_r(error, buffer, BUFSIZE)) {
427         /* strerror_r() is only allowed to fail on ERANGE (because the buffer
428          * is too short).  We don't check the actual failure reason because
429          * POSIX requires strerror_r() to return the error but old glibc
430          * (before 2.13) returns -1 and sets errno. */
431         snprintf(buffer, BUFSIZE, "Unknown error %d", error);
432     }
433 #endif
434
435     errno = save_errno;
436
437     return s;
438 }
439
440 /* Sets global "program_name" and "program_version" variables.  Should
441  * be called at the beginning of main() with "argv[0]" as the argument
442  * to 'argv0'.
443  *
444  * 'version' should contain the version of the caller's program.  If 'version'
445  * is the same as the VERSION #define, the caller is assumed to be part of Open
446  * vSwitch.  Otherwise, it is assumed to be an external program linking against
447  * the Open vSwitch libraries.
448  *
449  * The 'date' and 'time' arguments should likely be called with
450  * "__DATE__" and "__TIME__" to use the time the binary was built.
451  * Alternatively, the "ovs_set_program_name" macro may be called to do this
452  * automatically.
453  */
454 void
455 ovs_set_program_name__(const char *argv0, const char *version, const char *date,
456                        const char *time)
457 {
458     char *basename;
459 #ifdef _WIN32
460     size_t max_len = strlen(argv0) + 1;
461
462     SetErrorMode(GetErrorMode() | SEM_NOGPFAULTERRORBOX);
463     _set_output_format(_TWO_DIGIT_EXPONENT);
464
465     basename = xmalloc(max_len);
466     _splitpath_s(argv0, NULL, 0, NULL, 0, basename, max_len, NULL, 0);
467 #else
468     const char *slash = strrchr(argv0, '/');
469     basename = xstrdup(slash ? slash + 1 : argv0);
470 #endif
471
472     assert_single_threaded();
473     free(program_name);
474     /* Remove libtool prefix, if it is there */
475     if (strncmp(basename, "lt-", 3) == 0) {
476         char *tmp_name = basename;
477         basename = xstrdup(basename + 3);
478         free(tmp_name);
479     }
480     program_name = basename;
481
482     free(program_version);
483     if (!strcmp(version, VERSION)) {
484         program_version = xasprintf("%s (Open vSwitch) "VERSION"\n"
485                                     "Compiled %s %s\n",
486                                     program_name, date, time);
487     } else {
488         program_version = xasprintf("%s %s\n"
489                                     "Open vSwitch Library "VERSION"\n"
490                                     "Compiled %s %s\n",
491                                     program_name, version, date, time);
492     }
493 }
494
495 /* Returns the name of the currently running thread or process. */
496 const char *
497 get_subprogram_name(void)
498 {
499     const char *name = subprogram_name_get();
500     return name ? name : "";
501 }
502
503 /* Sets the formatted value of 'format' as the name of the currently running
504  * thread or process.  (This appears in log messages and may also be visible in
505  * system process listings and debuggers.) */
506 void
507 set_subprogram_name(const char *format, ...)
508 {
509     char *pname;
510
511     if (format) {
512         va_list args;
513
514         va_start(args, format);
515         pname = xvasprintf(format, args);
516         va_end(args);
517     } else {
518         pname = xstrdup(program_name);
519     }
520
521     free(subprogram_name_set(pname));
522
523 #if HAVE_GLIBC_PTHREAD_SETNAME_NP
524     pthread_setname_np(pthread_self(), pname);
525 #elif HAVE_NETBSD_PTHREAD_SETNAME_NP
526     pthread_setname_np(pthread_self(), "%s", pname);
527 #elif HAVE_PTHREAD_SET_NAME_NP
528     pthread_set_name_np(pthread_self(), pname);
529 #endif
530 }
531
532 /* Returns a pointer to a string describing the program version.  The
533  * caller must not modify or free the returned string.
534  */
535 const char *
536 ovs_get_program_version(void)
537 {
538     return program_version;
539 }
540
541 /* Returns a pointer to a string describing the program name.  The
542  * caller must not modify or free the returned string.
543  */
544 const char *
545 ovs_get_program_name(void)
546 {
547     return program_name;
548 }
549
550 /* Print the version information for the program.  */
551 void
552 ovs_print_version(uint8_t min_ofp, uint8_t max_ofp)
553 {
554     printf("%s", program_version);
555     if (min_ofp || max_ofp) {
556         printf("OpenFlow versions %#x:%#x\n", min_ofp, max_ofp);
557     }
558 }
559
560 /* Writes the 'size' bytes in 'buf' to 'stream' as hex bytes arranged 16 per
561  * line.  Numeric offsets are also included, starting at 'ofs' for the first
562  * byte in 'buf'.  If 'ascii' is true then the corresponding ASCII characters
563  * are also rendered alongside. */
564 void
565 ovs_hex_dump(FILE *stream, const void *buf_, size_t size,
566              uintptr_t ofs, bool ascii)
567 {
568   const uint8_t *buf = buf_;
569   const size_t per_line = 16; /* Maximum bytes per line. */
570
571   while (size > 0)
572     {
573       size_t start, end, n;
574       size_t i;
575
576       /* Number of bytes on this line. */
577       start = ofs % per_line;
578       end = per_line;
579       if (end - start > size)
580         end = start + size;
581       n = end - start;
582
583       /* Print line. */
584       fprintf(stream, "%08"PRIxMAX"  ", (uintmax_t) ROUND_DOWN(ofs, per_line));
585       for (i = 0; i < start; i++)
586         fprintf(stream, "   ");
587       for (; i < end; i++)
588         fprintf(stream, "%02x%c",
589                 buf[i - start], i == per_line / 2 - 1? '-' : ' ');
590       if (ascii)
591         {
592           for (; i < per_line; i++)
593             fprintf(stream, "   ");
594           fprintf(stream, "|");
595           for (i = 0; i < start; i++)
596             fprintf(stream, " ");
597           for (; i < end; i++) {
598               int c = buf[i - start];
599               putc(c >= 32 && c < 127 ? c : '.', stream);
600           }
601           for (; i < per_line; i++)
602             fprintf(stream, " ");
603           fprintf(stream, "|");
604         }
605       fprintf(stream, "\n");
606
607       ofs += n;
608       buf += n;
609       size -= n;
610     }
611 }
612
613 bool
614 str_to_int(const char *s, int base, int *i)
615 {
616     long long ll;
617     bool ok = str_to_llong(s, base, &ll);
618     *i = ll;
619     return ok;
620 }
621
622 bool
623 str_to_long(const char *s, int base, long *li)
624 {
625     long long ll;
626     bool ok = str_to_llong(s, base, &ll);
627     *li = ll;
628     return ok;
629 }
630
631 bool
632 str_to_llong(const char *s, int base, long long *x)
633 {
634     int save_errno = errno;
635     char *tail;
636     errno = 0;
637     *x = strtoll(s, &tail, base);
638     if (errno == EINVAL || errno == ERANGE || tail == s || *tail != '\0') {
639         errno = save_errno;
640         *x = 0;
641         return false;
642     } else {
643         errno = save_errno;
644         return true;
645     }
646 }
647
648 bool
649 str_to_uint(const char *s, int base, unsigned int *u)
650 {
651     long long ll;
652     bool ok = str_to_llong(s, base, &ll);
653     if (!ok || ll < 0 || ll > UINT_MAX) {
654         *u = 0;
655         return false;
656     } else {
657         *u = ll;
658         return true;
659     }
660 }
661
662 /* Converts floating-point string 's' into a double.  If successful, stores
663  * the double in '*d' and returns true; on failure, stores 0 in '*d' and
664  * returns false.
665  *
666  * Underflow (e.g. "1e-9999") is not considered an error, but overflow
667  * (e.g. "1e9999)" is. */
668 bool
669 str_to_double(const char *s, double *d)
670 {
671     int save_errno = errno;
672     char *tail;
673     errno = 0;
674     *d = strtod(s, &tail);
675     if (errno == EINVAL || (errno == ERANGE && *d != 0)
676         || tail == s || *tail != '\0') {
677         errno = save_errno;
678         *d = 0;
679         return false;
680     } else {
681         errno = save_errno;
682         return true;
683     }
684 }
685
686 /* Returns the value of 'c' as a hexadecimal digit. */
687 int
688 hexit_value(int c)
689 {
690     switch (c) {
691     case '0': case '1': case '2': case '3': case '4':
692     case '5': case '6': case '7': case '8': case '9':
693         return c - '0';
694
695     case 'a': case 'A':
696         return 0xa;
697
698     case 'b': case 'B':
699         return 0xb;
700
701     case 'c': case 'C':
702         return 0xc;
703
704     case 'd': case 'D':
705         return 0xd;
706
707     case 'e': case 'E':
708         return 0xe;
709
710     case 'f': case 'F':
711         return 0xf;
712
713     default:
714         return -1;
715     }
716 }
717
718 /* Returns the integer value of the 'n' hexadecimal digits starting at 's', or
719  * UINTMAX_MAX if one of those "digits" is not really a hex digit.  Sets '*ok'
720  * to true if the conversion succeeds or to false if a non-hex digit is
721  * detected. */
722 uintmax_t
723 hexits_value(const char *s, size_t n, bool *ok)
724 {
725     uintmax_t value;
726     size_t i;
727
728     value = 0;
729     for (i = 0; i < n; i++) {
730         int hexit = hexit_value(s[i]);
731         if (hexit < 0) {
732             *ok = false;
733             return UINTMAX_MAX;
734         }
735         value = (value << 4) + hexit;
736     }
737     *ok = true;
738     return value;
739 }
740
741 /* Parses the string in 's' as an integer in either hex or decimal format and
742  * puts the result right justified in the array 'valuep' that is 'field_width'
743  * big. If the string is in hex format, the value may be arbitrarily large;
744  * integers are limited to 64-bit values. (The rationale is that decimal is
745  * likely to represent a number and 64 bits is a reasonable maximum whereas
746  * hex could either be a number or a byte string.)
747  *
748  * On return 'tail' points to the first character in the string that was
749  * not parsed as part of the value. ERANGE is returned if the value is too
750  * large to fit in the given field. */
751 int
752 parse_int_string(const char *s, uint8_t *valuep, int field_width, char **tail)
753 {
754     unsigned long long int integer;
755     int i;
756
757     if (!strncmp(s, "0x", 2) || !strncmp(s, "0X", 2)) {
758         uint8_t *hexit_str;
759         int len = 0;
760         int val_idx;
761         int err = 0;
762
763         s += 2;
764         hexit_str = xmalloc(field_width * 2);
765
766         for (;;) {
767             uint8_t hexit;
768             bool ok;
769
770             s += strspn(s, " \t\r\n");
771             hexit = hexits_value(s, 1, &ok);
772             if (!ok) {
773                 *tail = CONST_CAST(char *, s);
774                 break;
775             }
776
777             if (hexit != 0 || len) {
778                 if (DIV_ROUND_UP(len + 1, 2) > field_width) {
779                     err = ERANGE;
780                     goto free;
781                 }
782
783                 hexit_str[len] = hexit;
784                 len++;
785             }
786             s++;
787         }
788
789         val_idx = field_width;
790         for (i = len - 1; i >= 0; i -= 2) {
791             val_idx--;
792             valuep[val_idx] = hexit_str[i];
793             if (i > 0) {
794                 valuep[val_idx] += hexit_str[i - 1] << 4;
795             }
796         }
797
798         memset(valuep, 0, val_idx);
799
800 free:
801         free(hexit_str);
802         return err;
803     }
804
805     errno = 0;
806     integer = strtoull(s, tail, 0);
807     if (errno) {
808         return errno;
809     }
810
811     for (i = field_width - 1; i >= 0; i--) {
812         valuep[i] = integer;
813         integer >>= 8;
814     }
815     if (integer) {
816         return ERANGE;
817     }
818
819     return 0;
820 }
821
822 /* Returns the current working directory as a malloc()'d string, or a null
823  * pointer if the current working directory cannot be determined. */
824 char *
825 get_cwd(void)
826 {
827     long int path_max;
828     size_t size;
829
830     /* Get maximum path length or at least a reasonable estimate. */
831 #ifndef _WIN32
832     path_max = pathconf(".", _PC_PATH_MAX);
833 #else
834     path_max = MAX_PATH;
835 #endif
836     size = (path_max < 0 ? 1024
837             : path_max > 10240 ? 10240
838             : path_max);
839
840     /* Get current working directory. */
841     for (;;) {
842         char *buf = xmalloc(size);
843         if (getcwd(buf, size)) {
844             return xrealloc(buf, strlen(buf) + 1);
845         } else {
846             int error = errno;
847             free(buf);
848             if (error != ERANGE) {
849                 VLOG_WARN("getcwd failed (%s)", ovs_strerror(error));
850                 return NULL;
851             }
852             size *= 2;
853         }
854     }
855 }
856
857 static char *
858 all_slashes_name(const char *s)
859 {
860     return xstrdup(s[0] == '/' && s[1] == '/' && s[2] != '/' ? "//"
861                    : s[0] == '/' ? "/"
862                    : ".");
863 }
864
865 #ifndef _WIN32
866 /* Returns the directory name portion of 'file_name' as a malloc()'d string,
867  * similar to the POSIX dirname() function but thread-safe. */
868 char *
869 dir_name(const char *file_name)
870 {
871     size_t len = strlen(file_name);
872     while (len > 0 && file_name[len - 1] == '/') {
873         len--;
874     }
875     while (len > 0 && file_name[len - 1] != '/') {
876         len--;
877     }
878     while (len > 0 && file_name[len - 1] == '/') {
879         len--;
880     }
881     return len ? xmemdup0(file_name, len) : all_slashes_name(file_name);
882 }
883
884 /* Returns the file name portion of 'file_name' as a malloc()'d string,
885  * similar to the POSIX basename() function but thread-safe. */
886 char *
887 base_name(const char *file_name)
888 {
889     size_t end, start;
890
891     end = strlen(file_name);
892     while (end > 0 && file_name[end - 1] == '/') {
893         end--;
894     }
895
896     if (!end) {
897         return all_slashes_name(file_name);
898     }
899
900     start = end;
901     while (start > 0 && file_name[start - 1] != '/') {
902         start--;
903     }
904
905     return xmemdup0(file_name + start, end - start);
906 }
907 #endif /* _WIN32 */
908
909 /* If 'file_name' starts with '/', returns a copy of 'file_name'.  Otherwise,
910  * returns an absolute path to 'file_name' considering it relative to 'dir',
911  * which itself must be absolute.  'dir' may be null or the empty string, in
912  * which case the current working directory is used.
913  *
914  * Returns a null pointer if 'dir' is null and getcwd() fails. */
915 char *
916 abs_file_name(const char *dir, const char *file_name)
917 {
918     if (file_name[0] == '/') {
919         return xstrdup(file_name);
920     } else if (dir && dir[0]) {
921         char *separator = dir[strlen(dir) - 1] == '/' ? "" : "/";
922         return xasprintf("%s%s%s", dir, separator, file_name);
923     } else {
924         char *cwd = get_cwd();
925         if (cwd) {
926             char *abs_name = xasprintf("%s/%s", cwd, file_name);
927             free(cwd);
928             return abs_name;
929         } else {
930             return NULL;
931         }
932     }
933 }
934
935 /* Like readlink(), but returns the link name as a null-terminated string in
936  * allocated memory that the caller must eventually free (with free()).
937  * Returns NULL on error, in which case errno is set appropriately. */
938 static char *
939 xreadlink(const char *filename)
940 {
941     size_t size;
942
943     for (size = 64; ; size *= 2) {
944         char *buf = xmalloc(size);
945         ssize_t retval = readlink(filename, buf, size);
946         int error = errno;
947
948         if (retval >= 0 && retval < size) {
949             buf[retval] = '\0';
950             return buf;
951         }
952
953         free(buf);
954         if (retval < 0) {
955             errno = error;
956             return NULL;
957         }
958     }
959 }
960
961 /* Returns a version of 'filename' with symlinks in the final component
962  * dereferenced.  This differs from realpath() in that:
963  *
964  *     - 'filename' need not exist.
965  *
966  *     - If 'filename' does exist as a symlink, its referent need not exist.
967  *
968  *     - Only symlinks in the final component of 'filename' are dereferenced.
969  *
970  * For Windows platform, this function returns a string that has the same
971  * value as the passed string.
972  *
973  * The caller must eventually free the returned string (with free()). */
974 char *
975 follow_symlinks(const char *filename)
976 {
977 #ifndef _WIN32
978     struct stat s;
979     char *fn;
980     int i;
981
982     fn = xstrdup(filename);
983     for (i = 0; i < 10; i++) {
984         char *linkname;
985         char *next_fn;
986
987         if (lstat(fn, &s) != 0 || !S_ISLNK(s.st_mode)) {
988             return fn;
989         }
990
991         linkname = xreadlink(fn);
992         if (!linkname) {
993             VLOG_WARN("%s: readlink failed (%s)",
994                       filename, ovs_strerror(errno));
995             return fn;
996         }
997
998         if (linkname[0] == '/') {
999             /* Target of symlink is absolute so use it raw. */
1000             next_fn = linkname;
1001         } else {
1002             /* Target of symlink is relative so add to 'fn''s directory. */
1003             char *dir = dir_name(fn);
1004
1005             if (!strcmp(dir, ".")) {
1006                 next_fn = linkname;
1007             } else {
1008                 char *separator = dir[strlen(dir) - 1] == '/' ? "" : "/";
1009                 next_fn = xasprintf("%s%s%s", dir, separator, linkname);
1010                 free(linkname);
1011             }
1012
1013             free(dir);
1014         }
1015
1016         free(fn);
1017         fn = next_fn;
1018     }
1019
1020     VLOG_WARN("%s: too many levels of symlinks", filename);
1021     free(fn);
1022 #endif
1023     return xstrdup(filename);
1024 }
1025
1026 /* Pass a value to this function if it is marked with
1027  * __attribute__((warn_unused_result)) and you genuinely want to ignore
1028  * its return value.  (Note that every scalar type can be implicitly
1029  * converted to bool.) */
1030 void ignore(bool x OVS_UNUSED) { }
1031
1032 /* Returns an appropriate delimiter for inserting just before the 0-based item
1033  * 'index' in a list that has 'total' items in it. */
1034 const char *
1035 english_list_delimiter(size_t index, size_t total)
1036 {
1037     return (index == 0 ? ""
1038             : index < total - 1 ? ", "
1039             : total > 2 ? ", and "
1040             : " and ");
1041 }
1042
1043 /* Returns the number of trailing 0-bits in 'n'.  Undefined if 'n' == 0. */
1044 #if __GNUC__ >= 4 || _MSC_VER
1045 /* Defined inline in util.h. */
1046 #else
1047 /* Returns the number of trailing 0-bits in 'n'.  Undefined if 'n' == 0. */
1048 int
1049 raw_ctz(uint64_t n)
1050 {
1051     uint64_t k;
1052     int count = 63;
1053
1054 #define CTZ_STEP(X)                             \
1055     k = n << (X);                               \
1056     if (k) {                                    \
1057         count -= X;                             \
1058         n = k;                                  \
1059     }
1060     CTZ_STEP(32);
1061     CTZ_STEP(16);
1062     CTZ_STEP(8);
1063     CTZ_STEP(4);
1064     CTZ_STEP(2);
1065     CTZ_STEP(1);
1066 #undef CTZ_STEP
1067
1068     return count;
1069 }
1070
1071 /* Returns the number of leading 0-bits in 'n'.  Undefined if 'n' == 0. */
1072 int
1073 raw_clz64(uint64_t n)
1074 {
1075     uint64_t k;
1076     int count = 63;
1077
1078 #define CLZ_STEP(X)                             \
1079     k = n >> (X);                               \
1080     if (k) {                                    \
1081         count -= X;                             \
1082         n = k;                                  \
1083     }
1084     CLZ_STEP(32);
1085     CLZ_STEP(16);
1086     CLZ_STEP(8);
1087     CLZ_STEP(4);
1088     CLZ_STEP(2);
1089     CLZ_STEP(1);
1090 #undef CLZ_STEP
1091
1092     return count;
1093 }
1094 #endif
1095
1096 #if NEED_COUNT_1BITS_8
1097 #define INIT1(X)                                \
1098     ((((X) & (1 << 0)) != 0) +                  \
1099      (((X) & (1 << 1)) != 0) +                  \
1100      (((X) & (1 << 2)) != 0) +                  \
1101      (((X) & (1 << 3)) != 0) +                  \
1102      (((X) & (1 << 4)) != 0) +                  \
1103      (((X) & (1 << 5)) != 0) +                  \
1104      (((X) & (1 << 6)) != 0) +                  \
1105      (((X) & (1 << 7)) != 0))
1106 #define INIT2(X)   INIT1(X),  INIT1((X) +  1)
1107 #define INIT4(X)   INIT2(X),  INIT2((X) +  2)
1108 #define INIT8(X)   INIT4(X),  INIT4((X) +  4)
1109 #define INIT16(X)  INIT8(X),  INIT8((X) +  8)
1110 #define INIT32(X) INIT16(X), INIT16((X) + 16)
1111 #define INIT64(X) INIT32(X), INIT32((X) + 32)
1112
1113 const uint8_t count_1bits_8[256] = {
1114     INIT64(0), INIT64(64), INIT64(128), INIT64(192)
1115 };
1116 #endif
1117
1118 /* Returns true if the 'n' bytes starting at 'p' are zeros. */
1119 bool
1120 is_all_zeros(const void *p_, size_t n)
1121 {
1122     const uint8_t *p = p_;
1123     size_t i;
1124
1125     for (i = 0; i < n; i++) {
1126         if (p[i] != 0x00) {
1127             return false;
1128         }
1129     }
1130     return true;
1131 }
1132
1133 /* Returns true if the 'n' bytes starting at 'p' are 0xff. */
1134 bool
1135 is_all_ones(const void *p_, size_t n)
1136 {
1137     const uint8_t *p = p_;
1138     size_t i;
1139
1140     for (i = 0; i < n; i++) {
1141         if (p[i] != 0xff) {
1142             return false;
1143         }
1144     }
1145     return true;
1146 }
1147
1148 /* Copies 'n_bits' bits starting from bit 'src_ofs' in 'src' to the 'n_bits'
1149  * starting from bit 'dst_ofs' in 'dst'.  'src' is 'src_len' bytes long and
1150  * 'dst' is 'dst_len' bytes long.
1151  *
1152  * If you consider all of 'src' to be a single unsigned integer in network byte
1153  * order, then bit N is the bit with value 2**N.  That is, bit 0 is the bit
1154  * with value 1 in src[src_len - 1], bit 1 is the bit with value 2, bit 2 is
1155  * the bit with value 4, ..., bit 8 is the bit with value 1 in src[src_len -
1156  * 2], and so on.  Similarly for 'dst'.
1157  *
1158  * Required invariants:
1159  *   src_ofs + n_bits <= src_len * 8
1160  *   dst_ofs + n_bits <= dst_len * 8
1161  *   'src' and 'dst' must not overlap.
1162  */
1163 void
1164 bitwise_copy(const void *src_, unsigned int src_len, unsigned int src_ofs,
1165              void *dst_, unsigned int dst_len, unsigned int dst_ofs,
1166              unsigned int n_bits)
1167 {
1168     const uint8_t *src = src_;
1169     uint8_t *dst = dst_;
1170
1171     src += src_len - (src_ofs / 8 + 1);
1172     src_ofs %= 8;
1173
1174     dst += dst_len - (dst_ofs / 8 + 1);
1175     dst_ofs %= 8;
1176
1177     if (src_ofs == 0 && dst_ofs == 0) {
1178         unsigned int n_bytes = n_bits / 8;
1179         if (n_bytes) {
1180             dst -= n_bytes - 1;
1181             src -= n_bytes - 1;
1182             memcpy(dst, src, n_bytes);
1183
1184             n_bits %= 8;
1185             src--;
1186             dst--;
1187         }
1188         if (n_bits) {
1189             uint8_t mask = (1 << n_bits) - 1;
1190             *dst = (*dst & ~mask) | (*src & mask);
1191         }
1192     } else {
1193         while (n_bits > 0) {
1194             unsigned int max_copy = 8 - MAX(src_ofs, dst_ofs);
1195             unsigned int chunk = MIN(n_bits, max_copy);
1196             uint8_t mask = ((1 << chunk) - 1) << dst_ofs;
1197
1198             *dst &= ~mask;
1199             *dst |= ((*src >> src_ofs) << dst_ofs) & mask;
1200
1201             src_ofs += chunk;
1202             if (src_ofs == 8) {
1203                 src--;
1204                 src_ofs = 0;
1205             }
1206             dst_ofs += chunk;
1207             if (dst_ofs == 8) {
1208                 dst--;
1209                 dst_ofs = 0;
1210             }
1211             n_bits -= chunk;
1212         }
1213     }
1214 }
1215
1216 /* Zeros the 'n_bits' bits starting from bit 'dst_ofs' in 'dst'.  'dst' is
1217  * 'dst_len' bytes long.
1218  *
1219  * If you consider all of 'dst' to be a single unsigned integer in network byte
1220  * order, then bit N is the bit with value 2**N.  That is, bit 0 is the bit
1221  * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
1222  * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
1223  * 2], and so on.
1224  *
1225  * Required invariant:
1226  *   dst_ofs + n_bits <= dst_len * 8
1227  */
1228 void
1229 bitwise_zero(void *dst_, unsigned int dst_len, unsigned dst_ofs,
1230              unsigned int n_bits)
1231 {
1232     uint8_t *dst = dst_;
1233
1234     if (!n_bits) {
1235         return;
1236     }
1237
1238     dst += dst_len - (dst_ofs / 8 + 1);
1239     dst_ofs %= 8;
1240
1241     if (dst_ofs) {
1242         unsigned int chunk = MIN(n_bits, 8 - dst_ofs);
1243
1244         *dst &= ~(((1 << chunk) - 1) << dst_ofs);
1245
1246         n_bits -= chunk;
1247         if (!n_bits) {
1248             return;
1249         }
1250
1251         dst--;
1252     }
1253
1254     while (n_bits >= 8) {
1255         *dst-- = 0;
1256         n_bits -= 8;
1257     }
1258
1259     if (n_bits) {
1260         *dst &= ~((1 << n_bits) - 1);
1261     }
1262 }
1263
1264 /* Sets to 1 all of the 'n_bits' bits starting from bit 'dst_ofs' in 'dst'.
1265  * 'dst' is 'dst_len' bytes long.
1266  *
1267  * If you consider all of 'dst' to be a single unsigned integer in network byte
1268  * order, then bit N is the bit with value 2**N.  That is, bit 0 is the bit
1269  * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
1270  * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
1271  * 2], and so on.
1272  *
1273  * Required invariant:
1274  *   dst_ofs + n_bits <= dst_len * 8
1275  */
1276 void
1277 bitwise_one(void *dst_, unsigned int dst_len, unsigned dst_ofs,
1278             unsigned int n_bits)
1279 {
1280     uint8_t *dst = dst_;
1281
1282     if (!n_bits) {
1283         return;
1284     }
1285
1286     dst += dst_len - (dst_ofs / 8 + 1);
1287     dst_ofs %= 8;
1288
1289     if (dst_ofs) {
1290         unsigned int chunk = MIN(n_bits, 8 - dst_ofs);
1291
1292         *dst |= ((1 << chunk) - 1) << dst_ofs;
1293
1294         n_bits -= chunk;
1295         if (!n_bits) {
1296             return;
1297         }
1298
1299         dst--;
1300     }
1301
1302     while (n_bits >= 8) {
1303         *dst-- = 0xff;
1304         n_bits -= 8;
1305     }
1306
1307     if (n_bits) {
1308         *dst |= (1 << n_bits) - 1;
1309     }
1310 }
1311
1312 /* Scans the 'n_bits' bits starting from bit 'dst_ofs' in 'dst' for 1-bits.
1313  * Returns false if any 1-bits are found, otherwise true.  'dst' is 'dst_len'
1314  * bytes long.
1315  *
1316  * If you consider all of 'dst' to be a single unsigned integer in network byte
1317  * order, then bit N is the bit with value 2**N.  That is, bit 0 is the bit
1318  * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
1319  * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
1320  * 2], and so on.
1321  *
1322  * Required invariant:
1323  *   dst_ofs + n_bits <= dst_len * 8
1324  */
1325 bool
1326 bitwise_is_all_zeros(const void *p_, unsigned int len, unsigned int ofs,
1327                      unsigned int n_bits)
1328 {
1329     const uint8_t *p = p_;
1330
1331     if (!n_bits) {
1332         return true;
1333     }
1334
1335     p += len - (ofs / 8 + 1);
1336     ofs %= 8;
1337
1338     if (ofs) {
1339         unsigned int chunk = MIN(n_bits, 8 - ofs);
1340
1341         if (*p & (((1 << chunk) - 1) << ofs)) {
1342             return false;
1343         }
1344
1345         n_bits -= chunk;
1346         if (!n_bits) {
1347             return true;
1348         }
1349
1350         p--;
1351     }
1352
1353     while (n_bits >= 8) {
1354         if (*p) {
1355             return false;
1356         }
1357         n_bits -= 8;
1358         p--;
1359     }
1360
1361     if (n_bits && *p & ((1 << n_bits) - 1)) {
1362         return false;
1363     }
1364
1365     return true;
1366 }
1367
1368 /* Scans the bits in 'p' that have bit offsets 'start' through 'end'
1369  * (inclusive) for the first bit with value 'target'.  If one is found, returns
1370  * its offset, otherwise 'end'.  'p' is 'len' bytes long.
1371  *
1372  * If you consider all of 'p' to be a single unsigned integer in network byte
1373  * order, then bit N is the bit with value 2**N.  That is, bit 0 is the bit
1374  * with value 1 in p[len - 1], bit 1 is the bit with value 2, bit 2 is the bit
1375  * with value 4, ..., bit 8 is the bit with value 1 in p[len - 2], and so on.
1376  *
1377  * Required invariant:
1378  *   start <= end
1379  */
1380 unsigned int
1381 bitwise_scan(const void *p_, unsigned int len, bool target, unsigned int start,
1382              unsigned int end)
1383 {
1384     const uint8_t *p = p_;
1385     unsigned int ofs;
1386
1387     for (ofs = start; ofs < end; ofs++) {
1388         bool bit = (p[len - (ofs / 8 + 1)] & (1u << (ofs % 8))) != 0;
1389         if (bit == target) {
1390             break;
1391         }
1392     }
1393     return ofs;
1394 }
1395
1396
1397 /* Copies the 'n_bits' low-order bits of 'value' into the 'n_bits' bits
1398  * starting at bit 'dst_ofs' in 'dst', which is 'dst_len' bytes long.
1399  *
1400  * If you consider all of 'dst' to be a single unsigned integer in network byte
1401  * order, then bit N is the bit with value 2**N.  That is, bit 0 is the bit
1402  * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
1403  * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
1404  * 2], and so on.
1405  *
1406  * Required invariants:
1407  *   dst_ofs + n_bits <= dst_len * 8
1408  *   n_bits <= 64
1409  */
1410 void
1411 bitwise_put(uint64_t value,
1412             void *dst, unsigned int dst_len, unsigned int dst_ofs,
1413             unsigned int n_bits)
1414 {
1415     ovs_be64 n_value = htonll(value);
1416     bitwise_copy(&n_value, sizeof n_value, 0,
1417                  dst, dst_len, dst_ofs,
1418                  n_bits);
1419 }
1420
1421 /* Returns the value of the 'n_bits' bits starting at bit 'src_ofs' in 'src',
1422  * which is 'src_len' bytes long.
1423  *
1424  * If you consider all of 'src' to be a single unsigned integer in network byte
1425  * order, then bit N is the bit with value 2**N.  That is, bit 0 is the bit
1426  * with value 1 in src[src_len - 1], bit 1 is the bit with value 2, bit 2 is
1427  * the bit with value 4, ..., bit 8 is the bit with value 1 in src[src_len -
1428  * 2], and so on.
1429  *
1430  * Required invariants:
1431  *   src_ofs + n_bits <= src_len * 8
1432  *   n_bits <= 64
1433  */
1434 uint64_t
1435 bitwise_get(const void *src, unsigned int src_len,
1436             unsigned int src_ofs, unsigned int n_bits)
1437 {
1438     ovs_be64 value = htonll(0);
1439
1440     bitwise_copy(src, src_len, src_ofs,
1441                  &value, sizeof value, 0,
1442                  n_bits);
1443     return ntohll(value);
1444 }
1445 \f
1446 /* ovs_scan */
1447
1448 struct scan_spec {
1449     unsigned int width;
1450     enum {
1451         SCAN_DISCARD,
1452         SCAN_CHAR,
1453         SCAN_SHORT,
1454         SCAN_INT,
1455         SCAN_LONG,
1456         SCAN_LLONG,
1457         SCAN_INTMAX_T,
1458         SCAN_PTRDIFF_T,
1459         SCAN_SIZE_T
1460     } type;
1461 };
1462
1463 static const char *
1464 skip_spaces(const char *s)
1465 {
1466     while (isspace((unsigned char) *s)) {
1467         s++;
1468     }
1469     return s;
1470 }
1471
1472 static const char *
1473 scan_int(const char *s, const struct scan_spec *spec, int base, va_list *args)
1474 {
1475     const char *start = s;
1476     uintmax_t value;
1477     bool negative;
1478     int n_digits;
1479
1480     negative = *s == '-';
1481     s += *s == '-' || *s == '+';
1482
1483     if ((!base || base == 16) && *s == '0' && (s[1] == 'x' || s[1] == 'X')) {
1484         base = 16;
1485         s += 2;
1486     } else if (!base) {
1487         base = *s == '0' ? 8 : 10;
1488     }
1489
1490     if (s - start >= spec->width) {
1491         return NULL;
1492     }
1493
1494     value = 0;
1495     n_digits = 0;
1496     while (s - start < spec->width) {
1497         int digit = hexit_value(*s);
1498
1499         if (digit < 0 || digit >= base) {
1500             break;
1501         }
1502         value = value * base + digit;
1503         n_digits++;
1504         s++;
1505     }
1506     if (!n_digits) {
1507         return NULL;
1508     }
1509
1510     if (negative) {
1511         value = -value;
1512     }
1513
1514     switch (spec->type) {
1515     case SCAN_DISCARD:
1516         break;
1517     case SCAN_CHAR:
1518         *va_arg(*args, char *) = value;
1519         break;
1520     case SCAN_SHORT:
1521         *va_arg(*args, short int *) = value;
1522         break;
1523     case SCAN_INT:
1524         *va_arg(*args, int *) = value;
1525         break;
1526     case SCAN_LONG:
1527         *va_arg(*args, long int *) = value;
1528         break;
1529     case SCAN_LLONG:
1530         *va_arg(*args, long long int *) = value;
1531         break;
1532     case SCAN_INTMAX_T:
1533         *va_arg(*args, intmax_t *) = value;
1534         break;
1535     case SCAN_PTRDIFF_T:
1536         *va_arg(*args, ptrdiff_t *) = value;
1537         break;
1538     case SCAN_SIZE_T:
1539         *va_arg(*args, size_t *) = value;
1540         break;
1541     }
1542     return s;
1543 }
1544
1545 static const char *
1546 skip_digits(const char *s)
1547 {
1548     while (*s >= '0' && *s <= '9') {
1549         s++;
1550     }
1551     return s;
1552 }
1553
1554 static const char *
1555 scan_float(const char *s, const struct scan_spec *spec, va_list *args)
1556 {
1557     const char *start = s;
1558     long double value;
1559     char *tail;
1560     char *copy;
1561     bool ok;
1562
1563     s += *s == '+' || *s == '-';
1564     s = skip_digits(s);
1565     if (*s == '.') {
1566         s = skip_digits(s + 1);
1567     }
1568     if (*s == 'e' || *s == 'E') {
1569         s++;
1570         s += *s == '+' || *s == '-';
1571         s = skip_digits(s);
1572     }
1573
1574     if (s - start > spec->width) {
1575         s = start + spec->width;
1576     }
1577
1578     copy = xmemdup0(start, s - start);
1579     value = strtold(copy, &tail);
1580     ok = *tail == '\0';
1581     free(copy);
1582     if (!ok) {
1583         return NULL;
1584     }
1585
1586     switch (spec->type) {
1587     case SCAN_DISCARD:
1588         break;
1589     case SCAN_INT:
1590         *va_arg(*args, float *) = value;
1591         break;
1592     case SCAN_LONG:
1593         *va_arg(*args, double *) = value;
1594         break;
1595     case SCAN_LLONG:
1596         *va_arg(*args, long double *) = value;
1597         break;
1598
1599     case SCAN_CHAR:
1600     case SCAN_SHORT:
1601     case SCAN_INTMAX_T:
1602     case SCAN_PTRDIFF_T:
1603     case SCAN_SIZE_T:
1604         OVS_NOT_REACHED();
1605     }
1606     return s;
1607 }
1608
1609 static void
1610 scan_output_string(const struct scan_spec *spec,
1611                    const char *s, size_t n,
1612                    va_list *args)
1613 {
1614     if (spec->type != SCAN_DISCARD) {
1615         char *out = va_arg(*args, char *);
1616         memcpy(out, s, n);
1617         out[n] = '\0';
1618     }
1619 }
1620
1621 static const char *
1622 scan_string(const char *s, const struct scan_spec *spec, va_list *args)
1623 {
1624     size_t n;
1625
1626     for (n = 0; n < spec->width; n++) {
1627         if (!s[n] || isspace((unsigned char) s[n])) {
1628             break;
1629         }
1630     }
1631     if (!n) {
1632         return NULL;
1633     }
1634
1635     scan_output_string(spec, s, n, args);
1636     return s + n;
1637 }
1638
1639 static const char *
1640 parse_scanset(const char *p_, unsigned long *set, bool *complemented)
1641 {
1642     const uint8_t *p = (const uint8_t *) p_;
1643
1644     *complemented = *p == '^';
1645     p += *complemented;
1646
1647     if (*p == ']') {
1648         bitmap_set1(set, ']');
1649         p++;
1650     }
1651
1652     while (*p && *p != ']') {
1653         if (p[1] == '-' && p[2] != ']' && p[2] > *p) {
1654             bitmap_set_multiple(set, *p, p[2] - *p + 1, true);
1655             p += 3;
1656         } else {
1657             bitmap_set1(set, *p++);
1658         }
1659     }
1660     if (*p == ']') {
1661         p++;
1662     }
1663     return (const char *) p;
1664 }
1665
1666 static const char *
1667 scan_set(const char *s, const struct scan_spec *spec, const char **pp,
1668          va_list *args)
1669 {
1670     unsigned long set[BITMAP_N_LONGS(UCHAR_MAX + 1)];
1671     bool complemented;
1672     unsigned int n;
1673
1674     /* Parse the scan set. */
1675     memset(set, 0, sizeof set);
1676     *pp = parse_scanset(*pp, set, &complemented);
1677
1678     /* Parse the data. */
1679     n = 0;
1680     while (s[n]
1681            && bitmap_is_set(set, (unsigned char) s[n]) == !complemented
1682            && n < spec->width) {
1683         n++;
1684     }
1685     if (!n) {
1686         return NULL;
1687     }
1688     scan_output_string(spec, s, n, args);
1689     return s + n;
1690 }
1691
1692 static const char *
1693 scan_chars(const char *s, const struct scan_spec *spec, va_list *args)
1694 {
1695     unsigned int n = spec->width == UINT_MAX ? 1 : spec->width;
1696
1697     if (strlen(s) < n) {
1698         return NULL;
1699     }
1700     if (spec->type != SCAN_DISCARD) {
1701         memcpy(va_arg(*args, char *), s, n);
1702     }
1703     return s + n;
1704 }
1705
1706 static bool
1707 ovs_scan__(const char *s, int *n, const char *format, va_list *args)
1708 {
1709     const char *const start = s;
1710     bool ok = false;
1711     const char *p;
1712
1713     p = format;
1714     while (*p != '\0') {
1715         struct scan_spec spec;
1716         unsigned char c = *p++;
1717         bool discard;
1718
1719         if (isspace(c)) {
1720             s = skip_spaces(s);
1721             continue;
1722         } else if (c != '%') {
1723             if (*s != c) {
1724                 goto exit;
1725             }
1726             s++;
1727             continue;
1728         } else if (*p == '%') {
1729             if (*s++ != '%') {
1730                 goto exit;
1731             }
1732             p++;
1733             continue;
1734         }
1735
1736         /* Parse '*' flag. */
1737         discard = *p == '*';
1738         p += discard;
1739
1740         /* Parse field width. */
1741         spec.width = 0;
1742         while (*p >= '0' && *p <= '9') {
1743             spec.width = spec.width * 10 + (*p++ - '0');
1744         }
1745         if (spec.width == 0) {
1746             spec.width = UINT_MAX;
1747         }
1748
1749         /* Parse type modifier. */
1750         switch (*p) {
1751         case 'h':
1752             if (p[1] == 'h') {
1753                 spec.type = SCAN_CHAR;
1754                 p += 2;
1755             } else {
1756                 spec.type = SCAN_SHORT;
1757                 p++;
1758             }
1759             break;
1760
1761         case 'j':
1762             spec.type = SCAN_INTMAX_T;
1763             p++;
1764             break;
1765
1766         case 'l':
1767             if (p[1] == 'l') {
1768                 spec.type = SCAN_LLONG;
1769                 p += 2;
1770             } else {
1771                 spec.type = SCAN_LONG;
1772                 p++;
1773             }
1774             break;
1775
1776         case 'L':
1777         case 'q':
1778             spec.type = SCAN_LLONG;
1779             p++;
1780             break;
1781
1782         case 't':
1783             spec.type = SCAN_PTRDIFF_T;
1784             p++;
1785             break;
1786
1787         case 'z':
1788             spec.type = SCAN_SIZE_T;
1789             p++;
1790             break;
1791
1792         default:
1793             spec.type = SCAN_INT;
1794             break;
1795         }
1796
1797         if (discard) {
1798             spec.type = SCAN_DISCARD;
1799         }
1800
1801         c = *p++;
1802         if (c != 'c' && c != 'n' && c != '[') {
1803             s = skip_spaces(s);
1804         }
1805         switch (c) {
1806         case 'd':
1807             s = scan_int(s, &spec, 10, args);
1808             break;
1809
1810         case 'i':
1811             s = scan_int(s, &spec, 0, args);
1812             break;
1813
1814         case 'o':
1815             s = scan_int(s, &spec, 8, args);
1816             break;
1817
1818         case 'u':
1819             s = scan_int(s, &spec, 10, args);
1820             break;
1821
1822         case 'x':
1823         case 'X':
1824             s = scan_int(s, &spec, 16, args);
1825             break;
1826
1827         case 'e':
1828         case 'f':
1829         case 'g':
1830         case 'E':
1831         case 'G':
1832             s = scan_float(s, &spec, args);
1833             break;
1834
1835         case 's':
1836             s = scan_string(s, &spec, args);
1837             break;
1838
1839         case '[':
1840             s = scan_set(s, &spec, &p, args);
1841             break;
1842
1843         case 'c':
1844             s = scan_chars(s, &spec, args);
1845             break;
1846
1847         case 'n':
1848             if (spec.type != SCAN_DISCARD) {
1849                 *va_arg(*args, int *) = s - start;
1850             }
1851             break;
1852         }
1853
1854         if (!s) {
1855             goto exit;
1856         }
1857     }
1858     if (n) {
1859         *n = s - start;
1860     }
1861
1862     ok = true;
1863 exit:
1864     return ok;
1865 }
1866
1867 /* This is an implementation of the standard sscanf() function, with the
1868  * following exceptions:
1869  *
1870  *   - It returns true if the entire format was successfully scanned and
1871  *     converted, false if any conversion failed.
1872  *
1873  *   - The standard doesn't define sscanf() behavior when an out-of-range value
1874  *     is scanned, e.g. if a "%"PRIi8 conversion scans "-1" or "0x1ff".  Some
1875  *     implementations consider this an error and stop scanning.  This
1876  *     implementation never considers an out-of-range value an error; instead,
1877  *     it stores the least-significant bits of the converted value in the
1878  *     destination, e.g. the value 255 for both examples earlier.
1879  *
1880  *   - Only single-byte characters are supported, that is, the 'l' modifier
1881  *     on %s, %[, and %c is not supported.  The GNU extension 'a' modifier is
1882  *     also not supported.
1883  *
1884  *   - %p is not supported.
1885  */
1886 bool
1887 ovs_scan(const char *s, const char *format, ...)
1888 {
1889     va_list args;
1890     bool res;
1891
1892     va_start(args, format);
1893     res = ovs_scan__(s, NULL, format, &args);
1894     va_end(args);
1895     return res;
1896 }
1897
1898 /*
1899  * This function is similar to ovs_scan(), with an extra parameter `n` added to
1900  * return the number of scanned characters.
1901  */
1902 bool
1903 ovs_scan_len(const char *s, int *n, const char *format, ...)
1904 {
1905     va_list args;
1906     bool success;
1907     int n1;
1908
1909     va_start(args, format);
1910     success = ovs_scan__(s + *n, &n1, format, &args);
1911     va_end(args);
1912     if (success) {
1913         *n = *n + n1;
1914     }
1915     return success;
1916 }
1917
1918 void
1919 xsleep(unsigned int seconds)
1920 {
1921     ovsrcu_quiesce_start();
1922 #ifdef _WIN32
1923     Sleep(seconds * 1000);
1924 #else
1925     sleep(seconds);
1926 #endif
1927     ovsrcu_quiesce_end();
1928 }
1929
1930 #ifdef _WIN32
1931 \f
1932 char *
1933 ovs_format_message(int error)
1934 {
1935     enum { BUFSIZE = sizeof strerror_buffer_get()->s };
1936     char *buffer = strerror_buffer_get()->s;
1937
1938     FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
1939                   NULL, error, 0, buffer, BUFSIZE, NULL);
1940     return buffer;
1941 }
1942
1943 /* Returns a null-terminated string that explains the last error.
1944  * Use this function to get the error string for WINAPI calls. */
1945 char *
1946 ovs_lasterror_to_string(void)
1947 {
1948     return ovs_format_message(GetLastError());
1949 }
1950
1951 int
1952 ftruncate(int fd, off_t length)
1953 {
1954     int error;
1955
1956     error = _chsize_s(fd, length);
1957     if (error) {
1958         return -1;
1959     }
1960     return 0;
1961 }
1962
1963 OVS_CONSTRUCTOR(winsock_start) {
1964     WSADATA wsaData;
1965     int error;
1966
1967     error = WSAStartup(MAKEWORD(2, 2), &wsaData);
1968     if (error != 0) {
1969         VLOG_FATAL("WSAStartup failed: %s", sock_strerror(sock_errno()));
1970    }
1971 }
1972 #endif