2 * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016 Nicira, Inc.
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:
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
31 #include "byte-order.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>
41 VLOG_DEFINE_THIS_MODULE(util
);
43 COVERAGE_DEFINE(util_xalloc
);
45 /* argv[0] without directory names. */
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
);
52 /* --version option output. */
53 static char *program_version
;
55 /* Buffer used by ovs_strerror() and ovs_format_message(). */
56 DEFINE_STATIC_PER_THREAD_DATA(struct { char s
[128]; },
60 static char *xreadlink(const char *filename
);
63 ovs_assert_failure(const char *where
, const char *function
,
64 const char *condition
)
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;
72 VLOG_ABORT("%s: assertion %s failed in %s()",
73 where
, condition
, function
);
77 fprintf(stderr
, "%s: assertion %s failed in %s()",
78 where
, condition
, function
);
89 ovs_abort(0, "virtual memory exhausted");
93 xcalloc(size_t count
, size_t size
)
95 void *p
= count
&& size
? calloc(count
, size
) : malloc(1);
96 COVERAGE_INC(util_xalloc
);
106 return xcalloc(1, size
);
112 void *p
= malloc(size
? size
: 1);
113 COVERAGE_INC(util_xalloc
);
121 xrealloc(void *p
, size_t size
)
123 p
= realloc(p
, size
? size
: 1);
124 COVERAGE_INC(util_xalloc
);
132 xmemdup(const void *p_
, size_t size
)
134 void *p
= xmalloc(size
);
140 xmemdup0(const char *p_
, size_t length
)
142 char *p
= xmalloc(length
+ 1);
143 memcpy(p
, p_
, length
);
149 xstrdup(const char *s
)
151 return xmemdup0(s
, strlen(s
));
155 nullable_xstrdup(const char *s
)
157 return s
? xstrdup(s
) : NULL
;
161 nullable_string_is_equal(const char *a
, const char *b
)
163 return a
? b
&& !strcmp(a
, b
) : !b
;
167 xvasprintf(const char *format
, va_list args
)
173 va_copy(args2
, args
);
174 needed
= vsnprintf(NULL
, 0, format
, args
);
176 s
= xmalloc(needed
+ 1);
178 vsnprintf(s
, needed
+ 1, format
, args2
);
185 x2nrealloc(void *p
, size_t *n
, size_t s
)
187 *n
= *n
== 0 ? 1 : 2 * *n
;
188 return xrealloc(p
, *n
* s
);
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
);
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.)
201 * Use free_cacheline() to free the returned memory block. */
203 xmalloc_cacheline(size_t size
)
205 #ifdef HAVE_POSIX_MEMALIGN
209 COVERAGE_INC(util_xalloc
);
210 error
= posix_memalign(&p
, CACHE_LINE_SIZE
, size
? size
: 1);
219 /* Allocate room for:
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.
224 * - A payload consisting of a void *, followed by padding out to
225 * MEM_ALIGN bytes, followed by 'size' bytes of user data.
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
));
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
);
237 return (char *) payload
+ MEM_ALIGN
;
241 /* Like xmalloc_cacheline() but clears the allocated memory to all zero
244 xzalloc_cacheline(size_t size
)
246 void *p
= xmalloc_cacheline(size
);
251 /* Frees a memory block allocated with xmalloc_cacheline() or
252 * xzalloc_cacheline(). */
254 free_cacheline(void *p
)
256 #ifdef HAVE_POSIX_MEMALIGN
260 free(*(void **) ((uintptr_t) p
- MEM_ALIGN
));
266 xasprintf(const char *format
, ...)
271 va_start(args
, format
);
272 s
= xvasprintf(format
, args
);
278 /* Similar to strlcpy() from OpenBSD, but it never reads more than 'size - 1'
279 * bytes from 'src' and doesn't return anything. */
281 ovs_strlcpy(char *dst
, const char *src
, size_t size
)
284 size_t len
= strnlen(src
, size
- 1);
285 memcpy(dst
, src
, len
);
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'.
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);
300 * (Thus, ovs_strzcpy() is similar to strncpy() without some of the pitfalls.)
303 ovs_strzcpy(char *dst
, const char *src
, size_t size
)
306 size_t len
= strnlen(src
, size
- 1);
307 memcpy(dst
, src
, len
);
308 memset(dst
+ len
, '\0', size
- len
);
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().
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.
319 * 'format' should not end with a new-line, because this function will add one
322 ovs_abort(int err_no
, const char *format
, ...)
326 va_start(args
, format
);
327 ovs_abort_valist(err_no
, format
, args
);
330 /* Same as ovs_abort() except that the arguments are supplied as a va_list. */
332 ovs_abort_valist(int err_no
, const char *format
, va_list args
)
334 ovs_error_valist(err_no
, format
, args
);
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.
342 * 'format' should not end with a new-line, because this function will add one
345 ovs_fatal(int err_no
, const char *format
, ...)
349 va_start(args
, format
);
350 ovs_fatal_valist(err_no
, format
, args
);
353 /* Same as ovs_fatal() except that the arguments are supplied as a va_list. */
355 ovs_fatal_valist(int err_no
, const char *format
, va_list args
)
357 ovs_error_valist(err_no
, format
, args
);
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.
365 * 'format' should not end with a new-line, because this function will add one
368 ovs_error(int err_no
, const char *format
, ...)
372 va_start(args
, format
);
373 ovs_error_valist(err_no
, format
, args
);
377 /* Same as ovs_error() except that the arguments are supplied as a va_list. */
379 ovs_error_valist(int err_no
, const char *format
, va_list args
)
381 const char *subprogram_name
= get_subprogram_name();
382 int save_errno
= errno
;
384 if (subprogram_name
[0]) {
385 fprintf(stderr
, "%s(%s): ", program_name
, subprogram_name
);
387 fprintf(stderr
, "%s: ", program_name
);
390 vfprintf(stderr
, format
, args
);
392 fprintf(stderr
, " (%s)", ovs_retval_to_string(err_no
));
399 /* Many OVS functions return an int which is one of:
402 * - EOF: end of file (not necessarily an error; depends on the function called)
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.
409 ovs_retval_to_string(int retval
)
412 : retval
== EOF
? "End of file"
413 : ovs_strerror(retval
));
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(). */
421 ovs_strerror(int error
)
423 enum { BUFSIZE
= sizeof strerror_buffer_get()->s
};
430 * strerror(0) varies among platforms:
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.
444 buffer
= strerror_buffer_get()->s
;
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. */
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
);
467 /* Sets global "program_name" and "program_version" variables. Should
468 * be called at the beginning of main() with "argv[0]" as the argument
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.
478 ovs_set_program_name(const char *argv0
, const char *version
)
482 size_t max_len
= strlen(argv0
) + 1;
484 SetErrorMode(GetErrorMode() | SEM_NOGPFAULTERRORBOX
);
485 _set_output_format(_TWO_DIGIT_EXPONENT
);
487 basename
= xmalloc(max_len
);
488 _splitpath_s(argv0
, NULL
, 0, NULL
, 0, basename
, max_len
, NULL
, 0);
490 const char *slash
= strrchr(argv0
, '/');
491 basename
= xstrdup(slash
? slash
+ 1 : argv0
);
494 assert_single_threaded();
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);
502 program_name
= basename
;
504 free(program_version
);
505 if (!strcmp(version
, VERSION
)) {
506 program_version
= xasprintf("%s (Open vSwitch) "VERSION
"\n",
509 program_version
= xasprintf("%s %s\n"
510 "Open vSwitch Library "VERSION
"\n",
511 program_name
, version
);
515 /* Returns the name of the currently running thread or process. */
517 get_subprogram_name(void)
519 const char *name
= subprogram_name_get();
520 return name
? name
: "";
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.) */
527 set_subprogram_name(const char *subprogram_name
)
529 char *pname
= xstrdup(subprogram_name
? subprogram_name
: program_name
);
530 free(subprogram_name_set(pname
));
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
);
541 /* Returns a pointer to a string describing the program version. The
542 * caller must not modify or free the returned string.
545 ovs_get_program_version(void)
547 return program_version
;
550 /* Returns a pointer to a string describing the program name. The
551 * caller must not modify or free the returned string.
554 ovs_get_program_name(void)
559 /* Print the version information for the program. */
561 ovs_print_version(uint8_t min_ofp
, uint8_t max_ofp
)
563 printf("%s", program_version
);
564 if (min_ofp
|| max_ofp
) {
565 printf("OpenFlow versions %#x:%#x\n", min_ofp
, max_ofp
);
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. */
574 ovs_hex_dump(FILE *stream
, const void *buf_
, size_t size
,
575 uintptr_t ofs
, bool ascii
)
577 const uint8_t *buf
= buf_
;
578 const size_t per_line
= 16; /* Maximum bytes per line. */
582 size_t start
, end
, n
;
585 /* Number of bytes on this line. */
586 start
= ofs
% per_line
;
588 if (end
- start
> size
)
593 fprintf(stream
, "%08"PRIxMAX
" ", (uintmax_t) ROUND_DOWN(ofs
, per_line
));
594 for (i
= 0; i
< start
; i
++)
595 fprintf(stream
, " ");
597 fprintf(stream
, "%02x%c",
598 buf
[i
- start
], i
== per_line
/ 2 - 1? '-' : ' ');
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
);
610 for (; i
< per_line
; i
++)
611 fprintf(stream
, " ");
612 fprintf(stream
, "|");
614 fprintf(stream
, "\n");
623 str_to_int(const char *s
, int base
, int *i
)
626 bool ok
= str_to_llong(s
, base
, &ll
);
632 str_to_long(const char *s
, int base
, long *li
)
635 bool ok
= str_to_llong(s
, base
, &ll
);
641 str_to_llong(const char *s
, int base
, long long *x
)
643 int save_errno
= errno
;
646 *x
= strtoll(s
, &tail
, base
);
647 if (errno
== EINVAL
|| errno
== ERANGE
|| tail
== s
|| *tail
!= '\0') {
658 str_to_uint(const char *s
, int base
, unsigned int *u
)
661 bool ok
= str_to_llong(s
, base
, &ll
);
662 if (!ok
|| ll
< 0 || ll
> UINT_MAX
) {
671 /* Converts floating-point string 's' into a double. If successful, stores
672 * the double in '*d' and returns true; on failure, stores 0 in '*d' and
675 * Underflow (e.g. "1e-9999") is not considered an error, but overflow
676 * (e.g. "1e9999)" is. */
678 str_to_double(const char *s
, double *d
)
680 int save_errno
= errno
;
683 *d
= strtod(s
, &tail
);
684 if (errno
== EINVAL
|| (errno
== ERANGE
&& *d
!= 0)
685 || tail
== s
|| *tail
!= '\0') {
695 /* Returns the value of 'c' as a hexadecimal digit. */
700 case '0': case '1': case '2': case '3': case '4':
701 case '5': case '6': case '7': case '8': case '9':
727 /* Returns the integer value of the 'n' hexadecimal digits starting at 's', or
728 * UINTMAX_MAX if one of those "digits" is not really a hex digit. Sets '*ok'
729 * to true if the conversion succeeds or to false if a non-hex digit is
732 hexits_value(const char *s
, size_t n
, bool *ok
)
738 for (i
= 0; i
< n
; i
++) {
739 int hexit
= hexit_value(s
[i
]);
744 value
= (value
<< 4) + hexit
;
750 /* Parses the string in 's' as an integer in either hex or decimal format and
751 * puts the result right justified in the array 'valuep' that is 'field_width'
752 * big. If the string is in hex format, the value may be arbitrarily large;
753 * integers are limited to 64-bit values. (The rationale is that decimal is
754 * likely to represent a number and 64 bits is a reasonable maximum whereas
755 * hex could either be a number or a byte string.)
757 * On return 'tail' points to the first character in the string that was
758 * not parsed as part of the value. ERANGE is returned if the value is too
759 * large to fit in the given field. */
761 parse_int_string(const char *s
, uint8_t *valuep
, int field_width
, char **tail
)
763 unsigned long long int integer
;
766 if (!strncmp(s
, "0x", 2) || !strncmp(s
, "0X", 2)) {
773 hexit_str
= xmalloc(field_width
* 2);
779 s
+= strspn(s
, " \t\r\n");
780 hexit
= hexits_value(s
, 1, &ok
);
782 *tail
= CONST_CAST(char *, s
);
786 if (hexit
!= 0 || len
) {
787 if (DIV_ROUND_UP(len
+ 1, 2) > field_width
) {
792 hexit_str
[len
] = hexit
;
798 val_idx
= field_width
;
799 for (i
= len
- 1; i
>= 0; i
-= 2) {
801 valuep
[val_idx
] = hexit_str
[i
];
803 valuep
[val_idx
] += hexit_str
[i
- 1] << 4;
807 memset(valuep
, 0, val_idx
);
815 integer
= strtoull(s
, tail
, 0);
820 for (i
= field_width
- 1; i
>= 0; i
--) {
831 /* Returns the current working directory as a malloc()'d string, or a null
832 * pointer if the current working directory cannot be determined. */
839 /* Get maximum path length or at least a reasonable estimate. */
841 path_max
= pathconf(".", _PC_PATH_MAX
);
845 size
= (path_max
< 0 ? 1024
846 : path_max
> 10240 ? 10240
849 /* Get current working directory. */
851 char *buf
= xmalloc(size
);
852 if (getcwd(buf
, size
)) {
853 return xrealloc(buf
, strlen(buf
) + 1);
857 if (error
!= ERANGE
) {
858 VLOG_WARN("getcwd failed (%s)", ovs_strerror(error
));
867 all_slashes_name(const char *s
)
869 return xstrdup(s
[0] == '/' && s
[1] == '/' && s
[2] != '/' ? "//"
875 /* Returns the directory name portion of 'file_name' as a malloc()'d string,
876 * similar to the POSIX dirname() function but thread-safe. */
878 dir_name(const char *file_name
)
880 size_t len
= strlen(file_name
);
881 while (len
> 0 && file_name
[len
- 1] == '/') {
884 while (len
> 0 && file_name
[len
- 1] != '/') {
887 while (len
> 0 && file_name
[len
- 1] == '/') {
890 return len
? xmemdup0(file_name
, len
) : all_slashes_name(file_name
);
893 /* Returns the file name portion of 'file_name' as a malloc()'d string,
894 * similar to the POSIX basename() function but thread-safe. */
896 base_name(const char *file_name
)
900 end
= strlen(file_name
);
901 while (end
> 0 && file_name
[end
- 1] == '/') {
906 return all_slashes_name(file_name
);
910 while (start
> 0 && file_name
[start
- 1] != '/') {
914 return xmemdup0(file_name
+ start
, end
- start
);
918 /* If 'file_name' starts with '/', returns a copy of 'file_name'. Otherwise,
919 * returns an absolute path to 'file_name' considering it relative to 'dir',
920 * which itself must be absolute. 'dir' may be null or the empty string, in
921 * which case the current working directory is used.
923 * Additionally on Windows, if 'file_name' has a ':', returns a copy of
926 * Returns a null pointer if 'dir' is null and getcwd() fails. */
928 abs_file_name(const char *dir
, const char *file_name
)
930 if (file_name
[0] == '/') {
931 return xstrdup(file_name
);
933 } else if (strchr(file_name
, ':')) {
934 return xstrdup(file_name
);
936 } else if (dir
&& dir
[0]) {
937 char *separator
= dir
[strlen(dir
) - 1] == '/' ? "" : "/";
938 return xasprintf("%s%s%s", dir
, separator
, file_name
);
940 char *cwd
= get_cwd();
942 char *abs_name
= xasprintf("%s/%s", cwd
, file_name
);
951 /* Like readlink(), but returns the link name as a null-terminated string in
952 * allocated memory that the caller must eventually free (with free()).
953 * Returns NULL on error, in which case errno is set appropriately. */
955 xreadlink(const char *filename
)
959 for (size
= 64; ; size
*= 2) {
960 char *buf
= xmalloc(size
);
961 ssize_t retval
= readlink(filename
, buf
, size
);
964 if (retval
>= 0 && retval
< size
) {
977 /* Returns a version of 'filename' with symlinks in the final component
978 * dereferenced. This differs from realpath() in that:
980 * - 'filename' need not exist.
982 * - If 'filename' does exist as a symlink, its referent need not exist.
984 * - Only symlinks in the final component of 'filename' are dereferenced.
986 * For Windows platform, this function returns a string that has the same
987 * value as the passed string.
989 * The caller must eventually free the returned string (with free()). */
991 follow_symlinks(const char *filename
)
998 fn
= xstrdup(filename
);
999 for (i
= 0; i
< 10; i
++) {
1003 if (lstat(fn
, &s
) != 0 || !S_ISLNK(s
.st_mode
)) {
1007 linkname
= xreadlink(fn
);
1009 VLOG_WARN("%s: readlink failed (%s)",
1010 filename
, ovs_strerror(errno
));
1014 if (linkname
[0] == '/') {
1015 /* Target of symlink is absolute so use it raw. */
1018 /* Target of symlink is relative so add to 'fn''s directory. */
1019 char *dir
= dir_name(fn
);
1021 if (!strcmp(dir
, ".")) {
1024 char *separator
= dir
[strlen(dir
) - 1] == '/' ? "" : "/";
1025 next_fn
= xasprintf("%s%s%s", dir
, separator
, linkname
);
1036 VLOG_WARN("%s: too many levels of symlinks", filename
);
1039 return xstrdup(filename
);
1042 /* Pass a value to this function if it is marked with
1043 * __attribute__((warn_unused_result)) and you genuinely want to ignore
1044 * its return value. (Note that every scalar type can be implicitly
1045 * converted to bool.) */
1046 void ignore(bool x OVS_UNUSED
) { }
1048 /* Returns an appropriate delimiter for inserting just before the 0-based item
1049 * 'index' in a list that has 'total' items in it. */
1051 english_list_delimiter(size_t index
, size_t total
)
1053 return (index
== 0 ? ""
1054 : index
< total
- 1 ? ", "
1055 : total
> 2 ? ", and "
1059 /* Returns the number of trailing 0-bits in 'n'. Undefined if 'n' == 0. */
1060 #if __GNUC__ >= 4 || _MSC_VER
1061 /* Defined inline in util.h. */
1063 /* Returns the number of trailing 0-bits in 'n'. Undefined if 'n' == 0. */
1070 #define CTZ_STEP(X) \
1087 /* Returns the number of leading 0-bits in 'n'. Undefined if 'n' == 0. */
1089 raw_clz64(uint64_t n
)
1094 #define CLZ_STEP(X) \
1112 #if NEED_COUNT_1BITS_8
1114 ((((X) & (1 << 0)) != 0) + \
1115 (((X) & (1 << 1)) != 0) + \
1116 (((X) & (1 << 2)) != 0) + \
1117 (((X) & (1 << 3)) != 0) + \
1118 (((X) & (1 << 4)) != 0) + \
1119 (((X) & (1 << 5)) != 0) + \
1120 (((X) & (1 << 6)) != 0) + \
1121 (((X) & (1 << 7)) != 0))
1122 #define INIT2(X) INIT1(X), INIT1((X) + 1)
1123 #define INIT4(X) INIT2(X), INIT2((X) + 2)
1124 #define INIT8(X) INIT4(X), INIT4((X) + 4)
1125 #define INIT16(X) INIT8(X), INIT8((X) + 8)
1126 #define INIT32(X) INIT16(X), INIT16((X) + 16)
1127 #define INIT64(X) INIT32(X), INIT32((X) + 32)
1129 const uint8_t count_1bits_8
[256] = {
1130 INIT64(0), INIT64(64), INIT64(128), INIT64(192)
1134 /* Returns true if the 'n' bytes starting at 'p' are zeros. */
1136 is_all_zeros(const void *p_
, size_t n
)
1138 const uint8_t *p
= p_
;
1141 for (i
= 0; i
< n
; i
++) {
1149 /* Returns true if the 'n' bytes starting at 'p' are 0xff. */
1151 is_all_ones(const void *p_
, size_t n
)
1153 const uint8_t *p
= p_
;
1156 for (i
= 0; i
< n
; i
++) {
1164 /* Copies 'n_bits' bits starting from bit 'src_ofs' in 'src' to the 'n_bits'
1165 * starting from bit 'dst_ofs' in 'dst'. 'src' is 'src_len' bytes long and
1166 * 'dst' is 'dst_len' bytes long.
1168 * If you consider all of 'src' to be a single unsigned integer in network byte
1169 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1170 * with value 1 in src[src_len - 1], bit 1 is the bit with value 2, bit 2 is
1171 * the bit with value 4, ..., bit 8 is the bit with value 1 in src[src_len -
1172 * 2], and so on. Similarly for 'dst'.
1174 * Required invariants:
1175 * src_ofs + n_bits <= src_len * 8
1176 * dst_ofs + n_bits <= dst_len * 8
1177 * 'src' and 'dst' must not overlap.
1180 bitwise_copy(const void *src_
, unsigned int src_len
, unsigned int src_ofs
,
1181 void *dst_
, unsigned int dst_len
, unsigned int dst_ofs
,
1182 unsigned int n_bits
)
1184 const uint8_t *src
= src_
;
1185 uint8_t *dst
= dst_
;
1187 src
+= src_len
- (src_ofs
/ 8 + 1);
1190 dst
+= dst_len
- (dst_ofs
/ 8 + 1);
1193 if (src_ofs
== 0 && dst_ofs
== 0) {
1194 unsigned int n_bytes
= n_bits
/ 8;
1198 memcpy(dst
, src
, n_bytes
);
1205 uint8_t mask
= (1 << n_bits
) - 1;
1206 *dst
= (*dst
& ~mask
) | (*src
& mask
);
1209 while (n_bits
> 0) {
1210 unsigned int max_copy
= 8 - MAX(src_ofs
, dst_ofs
);
1211 unsigned int chunk
= MIN(n_bits
, max_copy
);
1212 uint8_t mask
= ((1 << chunk
) - 1) << dst_ofs
;
1215 *dst
|= ((*src
>> src_ofs
) << dst_ofs
) & mask
;
1232 /* Zeros the 'n_bits' bits starting from bit 'dst_ofs' in 'dst'. 'dst' is
1233 * 'dst_len' bytes long.
1235 * If you consider all of 'dst' to be a single unsigned integer in network byte
1236 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1237 * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
1238 * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
1241 * Required invariant:
1242 * dst_ofs + n_bits <= dst_len * 8
1245 bitwise_zero(void *dst_
, unsigned int dst_len
, unsigned dst_ofs
,
1246 unsigned int n_bits
)
1248 uint8_t *dst
= dst_
;
1254 dst
+= dst_len
- (dst_ofs
/ 8 + 1);
1258 unsigned int chunk
= MIN(n_bits
, 8 - dst_ofs
);
1260 *dst
&= ~(((1 << chunk
) - 1) << dst_ofs
);
1270 while (n_bits
>= 8) {
1276 *dst
&= ~((1 << n_bits
) - 1);
1280 /* Sets to 1 all of the 'n_bits' bits starting from bit 'dst_ofs' in 'dst'.
1281 * 'dst' is 'dst_len' bytes long.
1283 * If you consider all of 'dst' to be a single unsigned integer in network byte
1284 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1285 * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
1286 * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
1289 * Required invariant:
1290 * dst_ofs + n_bits <= dst_len * 8
1293 bitwise_one(void *dst_
, unsigned int dst_len
, unsigned dst_ofs
,
1294 unsigned int n_bits
)
1296 uint8_t *dst
= dst_
;
1302 dst
+= dst_len
- (dst_ofs
/ 8 + 1);
1306 unsigned int chunk
= MIN(n_bits
, 8 - dst_ofs
);
1308 *dst
|= ((1 << chunk
) - 1) << dst_ofs
;
1318 while (n_bits
>= 8) {
1324 *dst
|= (1 << n_bits
) - 1;
1328 /* Scans the 'n_bits' bits starting from bit 'dst_ofs' in 'dst' for 1-bits.
1329 * Returns false if any 1-bits are found, otherwise true. 'dst' is 'dst_len'
1332 * If you consider all of 'dst' to be a single unsigned integer in network byte
1333 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1334 * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
1335 * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
1338 * Required invariant:
1339 * dst_ofs + n_bits <= dst_len * 8
1342 bitwise_is_all_zeros(const void *p_
, unsigned int len
, unsigned int ofs
,
1343 unsigned int n_bits
)
1345 const uint8_t *p
= p_
;
1351 p
+= len
- (ofs
/ 8 + 1);
1355 unsigned int chunk
= MIN(n_bits
, 8 - ofs
);
1357 if (*p
& (((1 << chunk
) - 1) << ofs
)) {
1369 while (n_bits
>= 8) {
1377 if (n_bits
&& *p
& ((1 << n_bits
) - 1)) {
1384 /* Scans the bits in 'p' that have bit offsets 'start' (inclusive) through
1385 * 'end' (exclusive) for the first bit with value 'target'. If one is found,
1386 * returns its offset, otherwise 'end'. 'p' is 'len' bytes long.
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.
1393 * Required invariant:
1397 bitwise_scan(const void *p
, unsigned int len
, bool target
, unsigned int start
,
1402 for (ofs
= start
; ofs
< end
; ofs
++) {
1403 if (bitwise_get_bit(p
, len
, ofs
) == target
) {
1410 /* Scans the bits in 'p' that have bit offsets 'start' (inclusive) through
1411 * 'end' (exclusive) for the first bit with value 'target', in reverse order.
1412 * If one is found, returns its offset, otherwise 'end'. 'p' is 'len' bytes
1415 * If you consider all of 'p' to be a single unsigned integer in network byte
1416 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1417 * with value 1 in p[len - 1], bit 1 is the bit with value 2, bit 2 is the bit
1418 * with value 4, ..., bit 8 is the bit with value 1 in p[len - 2], and so on.
1420 * To scan an entire bit array in reverse order, specify start == len * 8 - 1
1421 * and end == -1, in which case the return value is nonnegative if successful
1422 * and -1 if no 'target' match is found.
1424 * Required invariant:
1428 bitwise_rscan(const void *p
, unsigned int len
, bool target
, int start
, int end
)
1430 const uint8_t *s
= p
;
1431 int start_byte
= len
- (start
/ 8 + 1);
1432 int end_byte
= len
- (end
/ 8 + 1);
1437 /* Find the target in the start_byte from starting offset */
1438 ofs_byte
= start_byte
;
1439 the_byte
= s
[ofs_byte
];
1440 for (ofs
= start
% 8; ofs
>= 0; ofs
--) {
1441 if (((the_byte
& (1u << ofs
)) != 0) == target
) {
1446 /* Target not found in start byte, continue searching byte by byte */
1447 for (ofs_byte
= start_byte
+ 1; ofs_byte
<= end_byte
; ofs_byte
++) {
1448 if ((target
&& s
[ofs_byte
])
1449 || (!target
&& (s
[ofs_byte
] != 0xff))) {
1453 if (ofs_byte
> end_byte
) {
1456 the_byte
= s
[ofs_byte
];
1457 /* Target is in the_byte, find it bit by bit */
1458 for (ofs
= 7; ofs
>= 0; ofs
--) {
1459 if (((the_byte
& (1u << ofs
)) != 0) == target
) {
1464 int ret
= (len
- ofs_byte
) * 8 - (8 - ofs
);
1471 /* Copies the 'n_bits' low-order bits of 'value' into the 'n_bits' bits
1472 * starting at bit 'dst_ofs' in 'dst', which is 'dst_len' bytes long.
1474 * If you consider all of 'dst' to be a single unsigned integer in network byte
1475 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1476 * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
1477 * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
1480 * Required invariants:
1481 * dst_ofs + n_bits <= dst_len * 8
1485 bitwise_put(uint64_t value
,
1486 void *dst
, unsigned int dst_len
, unsigned int dst_ofs
,
1487 unsigned int n_bits
)
1489 ovs_be64 n_value
= htonll(value
);
1490 bitwise_copy(&n_value
, sizeof n_value
, 0,
1491 dst
, dst_len
, dst_ofs
,
1495 /* Returns the value of the 'n_bits' bits starting at bit 'src_ofs' in 'src',
1496 * which is 'src_len' bytes long.
1498 * If you consider all of 'src' to be a single unsigned integer in network byte
1499 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1500 * with value 1 in src[src_len - 1], bit 1 is the bit with value 2, bit 2 is
1501 * the bit with value 4, ..., bit 8 is the bit with value 1 in src[src_len -
1504 * Required invariants:
1505 * src_ofs + n_bits <= src_len * 8
1509 bitwise_get(const void *src
, unsigned int src_len
,
1510 unsigned int src_ofs
, unsigned int n_bits
)
1512 ovs_be64 value
= htonll(0);
1514 bitwise_copy(src
, src_len
, src_ofs
,
1515 &value
, sizeof value
, 0,
1517 return ntohll(value
);
1520 /* Returns the value of the bit with offset 'ofs' in 'src', which is 'len'
1523 * If you consider all of 'src' to be a single unsigned integer in network byte
1524 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1525 * with value 1 in src[len - 1], bit 1 is the bit with value 2, bit 2 is the
1526 * bit with value 4, ..., bit 8 is the bit with value 1 in src[len - 2], and so
1529 * Required invariants:
1533 bitwise_get_bit(const void *src_
, unsigned int len
, unsigned int ofs
)
1535 const uint8_t *src
= src_
;
1537 return (src
[len
- (ofs
/ 8 + 1)] & (1u << (ofs
% 8))) != 0;
1540 /* Sets the bit with offset 'ofs' in 'dst', which is 'len' bytes long, to 0.
1542 * If you consider all of 'dst' to be a single unsigned integer in network byte
1543 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1544 * with value 1 in dst[len - 1], bit 1 is the bit with value 2, bit 2 is the
1545 * bit with value 4, ..., bit 8 is the bit with value 1 in dst[len - 2], and so
1548 * Required invariants:
1552 bitwise_put0(void *dst_
, unsigned int len
, unsigned int ofs
)
1554 uint8_t *dst
= dst_
;
1556 dst
[len
- (ofs
/ 8 + 1)] &= ~(1u << (ofs
% 8));
1559 /* Sets the bit with offset 'ofs' in 'dst', which is 'len' bytes long, to 1.
1561 * If you consider all of 'dst' to be a single unsigned integer in network byte
1562 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1563 * with value 1 in dst[len - 1], bit 1 is the bit with value 2, bit 2 is the
1564 * bit with value 4, ..., bit 8 is the bit with value 1 in dst[len - 2], and so
1567 * Required invariants:
1571 bitwise_put1(void *dst_
, unsigned int len
, unsigned int ofs
)
1573 uint8_t *dst
= dst_
;
1575 dst
[len
- (ofs
/ 8 + 1)] |= 1u << (ofs
% 8);
1578 /* Sets the bit with offset 'ofs' in 'dst', which is 'len' bytes long, to 'b'.
1580 * If you consider all of 'dst' to be a single unsigned integer in network byte
1581 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1582 * with value 1 in dst[len - 1], bit 1 is the bit with value 2, bit 2 is the
1583 * bit with value 4, ..., bit 8 is the bit with value 1 in dst[len - 2], and so
1586 * Required invariants:
1590 bitwise_put_bit(void *dst
, unsigned int len
, unsigned int ofs
, bool b
)
1593 bitwise_put1(dst
, len
, ofs
);
1595 bitwise_put0(dst
, len
, ofs
);
1599 /* Flips the bit with offset 'ofs' in 'dst', which is 'len' bytes long.
1601 * If you consider all of 'dst' to be a single unsigned integer in network byte
1602 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1603 * with value 1 in dst[len - 1], bit 1 is the bit with value 2, bit 2 is the
1604 * bit with value 4, ..., bit 8 is the bit with value 1 in dst[len - 2], and so
1607 * Required invariants:
1611 bitwise_toggle_bit(void *dst_
, unsigned int len
, unsigned int ofs
)
1613 uint8_t *dst
= dst_
;
1615 dst
[len
- (ofs
/ 8 + 1)] ^= 1u << (ofs
% 8);
1636 skip_spaces(const char *s
)
1638 while (isspace((unsigned char) *s
)) {
1645 scan_int(const char *s
, const struct scan_spec
*spec
, int base
, va_list *args
)
1647 const char *start
= s
;
1652 negative
= *s
== '-';
1653 s
+= *s
== '-' || *s
== '+';
1655 if ((!base
|| base
== 16) && *s
== '0' && (s
[1] == 'x' || s
[1] == 'X')) {
1659 base
= *s
== '0' ? 8 : 10;
1662 if (s
- start
>= spec
->width
) {
1668 while (s
- start
< spec
->width
) {
1669 int digit
= hexit_value(*s
);
1671 if (digit
< 0 || digit
>= base
) {
1674 value
= value
* base
+ digit
;
1686 switch (spec
->type
) {
1690 *va_arg(*args
, char *) = value
;
1693 *va_arg(*args
, short int *) = value
;
1696 *va_arg(*args
, int *) = value
;
1699 *va_arg(*args
, long int *) = value
;
1702 *va_arg(*args
, long long int *) = value
;
1705 *va_arg(*args
, intmax_t *) = value
;
1707 case SCAN_PTRDIFF_T
:
1708 *va_arg(*args
, ptrdiff_t *) = value
;
1711 *va_arg(*args
, size_t *) = value
;
1718 skip_digits(const char *s
)
1720 while (*s
>= '0' && *s
<= '9') {
1727 scan_float(const char *s
, const struct scan_spec
*spec
, va_list *args
)
1729 const char *start
= s
;
1735 s
+= *s
== '+' || *s
== '-';
1738 s
= skip_digits(s
+ 1);
1740 if (*s
== 'e' || *s
== 'E') {
1742 s
+= *s
== '+' || *s
== '-';
1746 if (s
- start
> spec
->width
) {
1747 s
= start
+ spec
->width
;
1750 copy
= xmemdup0(start
, s
- start
);
1751 value
= strtold(copy
, &tail
);
1758 switch (spec
->type
) {
1762 *va_arg(*args
, float *) = value
;
1765 *va_arg(*args
, double *) = value
;
1768 *va_arg(*args
, long double *) = value
;
1774 case SCAN_PTRDIFF_T
:
1782 scan_output_string(const struct scan_spec
*spec
,
1783 const char *s
, size_t n
,
1786 if (spec
->type
!= SCAN_DISCARD
) {
1787 char *out
= va_arg(*args
, char *);
1794 scan_string(const char *s
, const struct scan_spec
*spec
, va_list *args
)
1798 for (n
= 0; n
< spec
->width
; n
++) {
1799 if (!s
[n
] || isspace((unsigned char) s
[n
])) {
1807 scan_output_string(spec
, s
, n
, args
);
1812 parse_scanset(const char *p_
, unsigned long *set
, bool *complemented
)
1814 const uint8_t *p
= (const uint8_t *) p_
;
1816 *complemented
= *p
== '^';
1820 bitmap_set1(set
, ']');
1824 while (*p
&& *p
!= ']') {
1825 if (p
[1] == '-' && p
[2] != ']' && p
[2] > *p
) {
1826 bitmap_set_multiple(set
, *p
, p
[2] - *p
+ 1, true);
1829 bitmap_set1(set
, *p
++);
1835 return (const char *) p
;
1839 scan_set(const char *s
, const struct scan_spec
*spec
, const char **pp
,
1842 unsigned long set
[BITMAP_N_LONGS(UCHAR_MAX
+ 1)];
1846 /* Parse the scan set. */
1847 memset(set
, 0, sizeof set
);
1848 *pp
= parse_scanset(*pp
, set
, &complemented
);
1850 /* Parse the data. */
1853 && bitmap_is_set(set
, (unsigned char) s
[n
]) == !complemented
1854 && n
< spec
->width
) {
1860 scan_output_string(spec
, s
, n
, args
);
1865 scan_chars(const char *s
, const struct scan_spec
*spec
, va_list *args
)
1867 unsigned int n
= spec
->width
== UINT_MAX
? 1 : spec
->width
;
1869 if (strlen(s
) < n
) {
1872 if (spec
->type
!= SCAN_DISCARD
) {
1873 memcpy(va_arg(*args
, char *), s
, n
);
1879 ovs_scan__(const char *s
, int *n
, const char *format
, va_list *args
)
1881 const char *const start
= s
;
1886 while (*p
!= '\0') {
1887 struct scan_spec spec
;
1888 unsigned char c
= *p
++;
1894 } else if (c
!= '%') {
1900 } else if (*p
== '%') {
1908 /* Parse '*' flag. */
1909 discard
= *p
== '*';
1912 /* Parse field width. */
1914 while (*p
>= '0' && *p
<= '9') {
1915 spec
.width
= spec
.width
* 10 + (*p
++ - '0');
1917 if (spec
.width
== 0) {
1918 spec
.width
= UINT_MAX
;
1921 /* Parse type modifier. */
1925 spec
.type
= SCAN_CHAR
;
1928 spec
.type
= SCAN_SHORT
;
1934 spec
.type
= SCAN_INTMAX_T
;
1940 spec
.type
= SCAN_LLONG
;
1943 spec
.type
= SCAN_LONG
;
1950 spec
.type
= SCAN_LLONG
;
1955 spec
.type
= SCAN_PTRDIFF_T
;
1960 spec
.type
= SCAN_SIZE_T
;
1965 spec
.type
= SCAN_INT
;
1970 spec
.type
= SCAN_DISCARD
;
1974 if (c
!= 'c' && c
!= 'n' && c
!= '[') {
1979 s
= scan_int(s
, &spec
, 10, args
);
1983 s
= scan_int(s
, &spec
, 0, args
);
1987 s
= scan_int(s
, &spec
, 8, args
);
1991 s
= scan_int(s
, &spec
, 10, args
);
1996 s
= scan_int(s
, &spec
, 16, args
);
2004 s
= scan_float(s
, &spec
, args
);
2008 s
= scan_string(s
, &spec
, args
);
2012 s
= scan_set(s
, &spec
, &p
, args
);
2016 s
= scan_chars(s
, &spec
, args
);
2020 if (spec
.type
!= SCAN_DISCARD
) {
2021 *va_arg(*args
, int *) = s
- start
;
2039 /* This is an implementation of the standard sscanf() function, with the
2040 * following exceptions:
2042 * - It returns true if the entire format was successfully scanned and
2043 * converted, false if any conversion failed.
2045 * - The standard doesn't define sscanf() behavior when an out-of-range value
2046 * is scanned, e.g. if a "%"PRIi8 conversion scans "-1" or "0x1ff". Some
2047 * implementations consider this an error and stop scanning. This
2048 * implementation never considers an out-of-range value an error; instead,
2049 * it stores the least-significant bits of the converted value in the
2050 * destination, e.g. the value 255 for both examples earlier.
2052 * - Only single-byte characters are supported, that is, the 'l' modifier
2053 * on %s, %[, and %c is not supported. The GNU extension 'a' modifier is
2054 * also not supported.
2056 * - %p is not supported.
2059 ovs_scan(const char *s
, const char *format
, ...)
2064 va_start(args
, format
);
2065 res
= ovs_scan__(s
, NULL
, format
, &args
);
2071 * This function is similar to ovs_scan(), with an extra parameter `n` added to
2072 * return the number of scanned characters.
2075 ovs_scan_len(const char *s
, int *n
, const char *format
, ...)
2081 va_start(args
, format
);
2082 success
= ovs_scan__(s
+ *n
, &n1
, format
, &args
);
2091 xsleep(unsigned int seconds
)
2093 ovsrcu_quiesce_start();
2095 Sleep(seconds
* 1000);
2099 ovsrcu_quiesce_end();
2102 /* Determine whether standard output is a tty or not. This is useful to decide
2103 * whether to use color output or not when --color option for utilities is set
2107 is_stdout_a_tty(void)
2109 char const *t
= getenv("TERM");
2110 return (isatty(STDOUT_FILENO
) && t
&& strcmp(t
, "dumb") != 0);
2116 ovs_format_message(int error
)
2118 enum { BUFSIZE
= sizeof strerror_buffer_get()->s
};
2119 char *buffer
= strerror_buffer_get()->s
;
2122 /* See ovs_strerror */
2126 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM
| FORMAT_MESSAGE_IGNORE_INSERTS
,
2127 NULL
, error
, 0, buffer
, BUFSIZE
, NULL
);
2131 /* Returns a null-terminated string that explains the last error.
2132 * Use this function to get the error string for WINAPI calls. */
2134 ovs_lasterror_to_string(void)
2136 return ovs_format_message(GetLastError());
2140 ftruncate(int fd
, off_t length
)
2144 error
= _chsize_s(fd
, length
);
2151 OVS_CONSTRUCTOR(winsock_start
) {
2155 error
= WSAStartup(MAKEWORD(2, 2), &wsaData
);
2157 VLOG_FATAL("WSAStartup failed: %s", sock_strerror(sock_errno()));