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