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