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