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