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