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