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