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