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