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