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