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