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