2 * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015 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 xvasprintf(const char *format, va_list args)
161 va_copy(args2, args);
162 needed = vsnprintf(NULL, 0, format, args);
164 s = xmalloc(needed + 1);
166 vsnprintf(s, needed + 1, format, args2);
173 x2nrealloc(void *p, size_t *n, size_t s)
175 *n = *n == 0 ? 1 : 2 * *n;
176 return xrealloc(p, *n * s);
179 /* The desired minimum alignment for an allocated block of memory. */
180 #define MEM_ALIGN MAX(sizeof(void *), 8)
181 BUILD_ASSERT_DECL(IS_POW2(MEM_ALIGN));
182 BUILD_ASSERT_DECL(CACHE_LINE_SIZE >= MEM_ALIGN);
184 /* Allocates and returns 'size' bytes of memory in dedicated cache lines. That
185 * is, the memory block returned will not share a cache line with other data,
186 * avoiding "false sharing". (The memory returned will not be at the start of
187 * a cache line, though, so don't assume such alignment.)
189 * Use free_cacheline() to free the returned memory block. */
191 xmalloc_cacheline(size_t size)
193 #ifdef HAVE_POSIX_MEMALIGN
197 COVERAGE_INC(util_xalloc);
198 error = posix_memalign(&p, CACHE_LINE_SIZE, size ? size : 1);
207 /* Allocate room for:
209 * - Up to CACHE_LINE_SIZE - 1 bytes before the payload, so that the
210 * start of the payload doesn't potentially share a cache line.
212 * - A payload consisting of a void *, followed by padding out to
213 * MEM_ALIGN bytes, followed by 'size' bytes of user data.
215 * - Space following the payload up to the end of the cache line, so
216 * that the end of the payload doesn't potentially share a cache line
217 * with some following block. */
218 base = xmalloc((CACHE_LINE_SIZE - 1)
219 + ROUND_UP(MEM_ALIGN + size, CACHE_LINE_SIZE));
221 /* Locate the payload and store a pointer to the base at the beginning. */
222 payload = (void **) ROUND_UP((uintptr_t) base, CACHE_LINE_SIZE);
225 return (char *) payload + MEM_ALIGN;
229 /* Like xmalloc_cacheline() but clears the allocated memory to all zero
232 xzalloc_cacheline(size_t size)
234 void *p = xmalloc_cacheline(size);
239 /* Frees a memory block allocated with xmalloc_cacheline() or
240 * xzalloc_cacheline(). */
242 free_cacheline(void *p)
244 #ifdef HAVE_POSIX_MEMALIGN
248 free(*(void **) ((uintptr_t) p - MEM_ALIGN));
254 xasprintf(const char *format, ...)
259 va_start(args, format);
260 s = xvasprintf(format, args);
266 /* Similar to strlcpy() from OpenBSD, but it never reads more than 'size - 1'
267 * bytes from 'src' and doesn't return anything. */
269 ovs_strlcpy(char *dst, const char *src, size_t size)
272 size_t len = strnlen(src, size - 1);
273 memcpy(dst, src, len);
278 /* Copies 'src' to 'dst'. Reads no more than 'size - 1' bytes from 'src'.
279 * Always null-terminates 'dst' (if 'size' is nonzero), and writes a zero byte
280 * to every otherwise unused byte in 'dst'.
282 * Except for performance, the following call:
283 * ovs_strzcpy(dst, src, size);
284 * is equivalent to these two calls:
285 * memset(dst, '\0', size);
286 * ovs_strlcpy(dst, src, size);
288 * (Thus, ovs_strzcpy() is similar to strncpy() without some of the pitfalls.)
291 ovs_strzcpy(char *dst, const char *src, size_t size)
294 size_t len = strnlen(src, size - 1);
295 memcpy(dst, src, len);
296 memset(dst + len, '\0', size - len);
300 /* Prints 'format' on stderr, formatting it like printf() does. If 'err_no' is
301 * nonzero, then it is formatted with ovs_retval_to_string() and appended to
302 * the message inside parentheses. Then, terminates with abort().
304 * This function is preferred to ovs_fatal() in a situation where it would make
305 * sense for a monitoring process to restart the daemon.
307 * 'format' should not end with a new-line, because this function will add one
310 ovs_abort(int err_no, const char *format, ...)
314 va_start(args, format);
315 ovs_abort_valist(err_no, format, args);
318 /* Same as ovs_abort() except that the arguments are supplied as a va_list. */
320 ovs_abort_valist(int err_no, const char *format, va_list args)
322 ovs_error_valist(err_no, format, args);
326 /* Prints 'format' on stderr, formatting it like printf() does. If 'err_no' is
327 * nonzero, then it is formatted with ovs_retval_to_string() and appended to
328 * the message inside parentheses. Then, terminates with EXIT_FAILURE.
330 * 'format' should not end with a new-line, because this function will add one
333 ovs_fatal(int err_no, const char *format, ...)
337 va_start(args, format);
338 ovs_fatal_valist(err_no, format, args);
341 /* Same as ovs_fatal() except that the arguments are supplied as a va_list. */
343 ovs_fatal_valist(int err_no, const char *format, va_list args)
345 ovs_error_valist(err_no, format, args);
349 /* Prints 'format' on stderr, formatting it like printf() does. If 'err_no' is
350 * nonzero, then it is formatted with ovs_retval_to_string() and appended to
351 * the message inside parentheses.
353 * 'format' should not end with a new-line, because this function will add one
356 ovs_error(int err_no, const char *format, ...)
360 va_start(args, format);
361 ovs_error_valist(err_no, format, args);
365 /* Same as ovs_error() except that the arguments are supplied as a va_list. */
367 ovs_error_valist(int err_no, const char *format, va_list args)
369 const char *subprogram_name = get_subprogram_name();
370 int save_errno = errno;
372 if (subprogram_name[0]) {
373 fprintf(stderr, "%s(%s): ", program_name, subprogram_name);
375 fprintf(stderr, "%s: ", program_name);
378 vfprintf(stderr, format, args);
380 fprintf(stderr, " (%s)", ovs_retval_to_string(err_no));
387 /* Many OVS functions return an int which is one of:
390 * - EOF: end of file (not necessarily an error; depends on the function called)
392 * Returns the appropriate human-readable string. The caller must copy the
393 * string if it wants to hold onto it, as the storage may be overwritten on
394 * subsequent function calls.
397 ovs_retval_to_string(int retval)
400 : retval == EOF ? "End of file"
401 : ovs_strerror(retval));
404 /* This function returns the string describing the error number in 'error'
405 * for POSIX platforms. For Windows, this function can be used for C library
406 * calls. For socket calls that are also used in Windows, use sock_strerror()
407 * instead. For WINAPI calls, look at ovs_lasterror_to_string(). */
409 ovs_strerror(int error)
411 enum { BUFSIZE = sizeof strerror_buffer_get()->s };
417 buffer = strerror_buffer_get()->s;
419 #if STRERROR_R_CHAR_P
420 /* GNU style strerror_r() might return an immutable static string, or it
421 * might write and return 'buffer', but in either case we can pass the
422 * returned string directly to the caller. */
423 s = strerror_r(error, buffer, BUFSIZE);
424 #else /* strerror_r() returns an int. */
426 if (strerror_r(error, buffer, BUFSIZE)) {
427 /* strerror_r() is only allowed to fail on ERANGE (because the buffer
428 * is too short). We don't check the actual failure reason because
429 * POSIX requires strerror_r() to return the error but old glibc
430 * (before 2.13) returns -1 and sets errno. */
431 snprintf(buffer, BUFSIZE, "Unknown error %d", error);
440 /* Sets global "program_name" and "program_version" variables. Should
441 * be called at the beginning of main() with "argv[0]" as the argument
444 * 'version' should contain the version of the caller's program. If 'version'
445 * is the same as the VERSION #define, the caller is assumed to be part of Open
446 * vSwitch. Otherwise, it is assumed to be an external program linking against
447 * the Open vSwitch libraries.
449 * The 'date' and 'time' arguments should likely be called with
450 * "__DATE__" and "__TIME__" to use the time the binary was built.
451 * Alternatively, the "ovs_set_program_name" macro may be called to do this
455 ovs_set_program_name__(const char *argv0, const char *version, const char *date,
460 size_t max_len = strlen(argv0) + 1;
462 SetErrorMode(GetErrorMode() | SEM_NOGPFAULTERRORBOX);
463 _set_output_format(_TWO_DIGIT_EXPONENT);
465 basename = xmalloc(max_len);
466 _splitpath_s(argv0, NULL, 0, NULL, 0, basename, max_len, NULL, 0);
468 const char *slash = strrchr(argv0, '/');
469 basename = xstrdup(slash ? slash + 1 : argv0);
472 assert_single_threaded();
474 /* Remove libtool prefix, if it is there */
475 if (strncmp(basename, "lt-", 3) == 0) {
476 char *tmp_name = basename;
477 basename = xstrdup(basename + 3);
480 program_name = basename;
482 free(program_version);
483 if (!strcmp(version, VERSION)) {
484 program_version = xasprintf("%s (Open vSwitch) "VERSION"\n"
486 program_name, date, time);
488 program_version = xasprintf("%s %s\n"
489 "Open vSwitch Library "VERSION"\n"
491 program_name, version, date, time);
495 /* Returns the name of the currently running thread or process. */
497 get_subprogram_name(void)
499 const char *name = subprogram_name_get();
500 return name ? name : "";
503 /* Sets 'subprogram_name' as the name of the currently running thread or
504 * process. (This appears in log messages and may also be visible in system
505 * process listings and debuggers.) */
507 set_subprogram_name(const char *subprogram_name)
509 char *pname = xstrdup(subprogram_name ? subprogram_name : program_name);
510 free(subprogram_name_set(pname));
512 #if HAVE_GLIBC_PTHREAD_SETNAME_NP
513 pthread_setname_np(pthread_self(), pname);
514 #elif HAVE_NETBSD_PTHREAD_SETNAME_NP
515 pthread_setname_np(pthread_self(), "%s", pname);
516 #elif HAVE_PTHREAD_SET_NAME_NP
517 pthread_set_name_np(pthread_self(), pname);
521 /* Returns a pointer to a string describing the program version. The
522 * caller must not modify or free the returned string.
525 ovs_get_program_version(void)
527 return program_version;
530 /* Returns a pointer to a string describing the program name. The
531 * caller must not modify or free the returned string.
534 ovs_get_program_name(void)
539 /* Print the version information for the program. */
541 ovs_print_version(uint8_t min_ofp, uint8_t max_ofp)
543 printf("%s", program_version);
544 if (min_ofp || max_ofp) {
545 printf("OpenFlow versions %#x:%#x\n", min_ofp, max_ofp);
549 /* Writes the 'size' bytes in 'buf' to 'stream' as hex bytes arranged 16 per
550 * line. Numeric offsets are also included, starting at 'ofs' for the first
551 * byte in 'buf'. If 'ascii' is true then the corresponding ASCII characters
552 * are also rendered alongside. */
554 ovs_hex_dump(FILE *stream, const void *buf_, size_t size,
555 uintptr_t ofs, bool ascii)
557 const uint8_t *buf = buf_;
558 const size_t per_line = 16; /* Maximum bytes per line. */
562 size_t start, end, n;
565 /* Number of bytes on this line. */
566 start = ofs % per_line;
568 if (end - start > size)
573 fprintf(stream, "%08"PRIxMAX" ", (uintmax_t) ROUND_DOWN(ofs, per_line));
574 for (i = 0; i < start; i++)
575 fprintf(stream, " ");
577 fprintf(stream, "%02x%c",
578 buf[i - start], i == per_line / 2 - 1? '-' : ' ');
581 for (; i < per_line; i++)
582 fprintf(stream, " ");
583 fprintf(stream, "|");
584 for (i = 0; i < start; i++)
585 fprintf(stream, " ");
586 for (; i < end; i++) {
587 int c = buf[i - start];
588 putc(c >= 32 && c < 127 ? c : '.', stream);
590 for (; i < per_line; i++)
591 fprintf(stream, " ");
592 fprintf(stream, "|");
594 fprintf(stream, "\n");
603 str_to_int(const char *s, int base, int *i)
606 bool ok = str_to_llong(s, base, &ll);
612 str_to_long(const char *s, int base, long *li)
615 bool ok = str_to_llong(s, base, &ll);
621 str_to_llong(const char *s, int base, long long *x)
623 int save_errno = errno;
626 *x = strtoll(s, &tail, base);
627 if (errno == EINVAL || errno == ERANGE || tail == s || *tail != '\0') {
638 str_to_uint(const char *s, int base, unsigned int *u)
641 bool ok = str_to_llong(s, base, &ll);
642 if (!ok || ll < 0 || ll > UINT_MAX) {
651 /* Converts floating-point string 's' into a double. If successful, stores
652 * the double in '*d' and returns true; on failure, stores 0 in '*d' and
655 * Underflow (e.g. "1e-9999") is not considered an error, but overflow
656 * (e.g. "1e9999)" is. */
658 str_to_double(const char *s, double *d)
660 int save_errno = errno;
663 *d = strtod(s, &tail);
664 if (errno == EINVAL || (errno == ERANGE && *d != 0)
665 || tail == s || *tail != '\0') {
675 /* Returns the value of 'c' as a hexadecimal digit. */
680 case '0': case '1': case '2': case '3': case '4':
681 case '5': case '6': case '7': case '8': case '9':
707 /* Returns the integer value of the 'n' hexadecimal digits starting at 's', or
708 * UINTMAX_MAX if one of those "digits" is not really a hex digit. Sets '*ok'
709 * to true if the conversion succeeds or to false if a non-hex digit is
712 hexits_value(const char *s, size_t n, bool *ok)
718 for (i = 0; i < n; i++) {
719 int hexit = hexit_value(s[i]);
724 value = (value << 4) + hexit;
730 /* Parses the string in 's' as an integer in either hex or decimal format and
731 * puts the result right justified in the array 'valuep' that is 'field_width'
732 * big. If the string is in hex format, the value may be arbitrarily large;
733 * integers are limited to 64-bit values. (The rationale is that decimal is
734 * likely to represent a number and 64 bits is a reasonable maximum whereas
735 * hex could either be a number or a byte string.)
737 * On return 'tail' points to the first character in the string that was
738 * not parsed as part of the value. ERANGE is returned if the value is too
739 * large to fit in the given field. */
741 parse_int_string(const char *s, uint8_t *valuep, int field_width, char **tail)
743 unsigned long long int integer;
746 if (!strncmp(s, "0x", 2) || !strncmp(s, "0X", 2)) {
753 hexit_str = xmalloc(field_width * 2);
759 s += strspn(s, " \t\r\n");
760 hexit = hexits_value(s, 1, &ok);
762 *tail = CONST_CAST(char *, s);
766 if (hexit != 0 || len) {
767 if (DIV_ROUND_UP(len + 1, 2) > field_width) {
772 hexit_str[len] = hexit;
778 val_idx = field_width;
779 for (i = len - 1; i >= 0; i -= 2) {
781 valuep[val_idx] = hexit_str[i];
783 valuep[val_idx] += hexit_str[i - 1] << 4;
787 memset(valuep, 0, val_idx);
795 integer = strtoull(s, tail, 0);
800 for (i = field_width - 1; i >= 0; i--) {
811 /* Returns the current working directory as a malloc()'d string, or a null
812 * pointer if the current working directory cannot be determined. */
819 /* Get maximum path length or at least a reasonable estimate. */
821 path_max = pathconf(".", _PC_PATH_MAX);
825 size = (path_max < 0 ? 1024
826 : path_max > 10240 ? 10240
829 /* Get current working directory. */
831 char *buf = xmalloc(size);
832 if (getcwd(buf, size)) {
833 return xrealloc(buf, strlen(buf) + 1);
837 if (error != ERANGE) {
838 VLOG_WARN("getcwd failed (%s)", ovs_strerror(error));
847 all_slashes_name(const char *s)
849 return xstrdup(s[0] == '/' && s[1] == '/' && s[2] != '/' ? "//"
855 /* Returns the directory name portion of 'file_name' as a malloc()'d string,
856 * similar to the POSIX dirname() function but thread-safe. */
858 dir_name(const char *file_name)
860 size_t len = strlen(file_name);
861 while (len > 0 && file_name[len - 1] == '/') {
864 while (len > 0 && file_name[len - 1] != '/') {
867 while (len > 0 && file_name[len - 1] == '/') {
870 return len ? xmemdup0(file_name, len) : all_slashes_name(file_name);
873 /* Returns the file name portion of 'file_name' as a malloc()'d string,
874 * similar to the POSIX basename() function but thread-safe. */
876 base_name(const char *file_name)
880 end = strlen(file_name);
881 while (end > 0 && file_name[end - 1] == '/') {
886 return all_slashes_name(file_name);
890 while (start > 0 && file_name[start - 1] != '/') {
894 return xmemdup0(file_name + start, end - start);
898 /* If 'file_name' starts with '/', returns a copy of 'file_name'. Otherwise,
899 * returns an absolute path to 'file_name' considering it relative to 'dir',
900 * which itself must be absolute. 'dir' may be null or the empty string, in
901 * which case the current working directory is used.
903 * Returns a null pointer if 'dir' is null and getcwd() fails. */
905 abs_file_name(const char *dir, const char *file_name)
907 if (file_name[0] == '/') {
908 return xstrdup(file_name);
909 } else if (dir && dir[0]) {
910 char *separator = dir[strlen(dir) - 1] == '/' ? "" : "/";
911 return xasprintf("%s%s%s", dir, separator, file_name);
913 char *cwd = get_cwd();
915 char *abs_name = xasprintf("%s/%s", cwd, file_name);
924 /* Like readlink(), but returns the link name as a null-terminated string in
925 * allocated memory that the caller must eventually free (with free()).
926 * Returns NULL on error, in which case errno is set appropriately. */
928 xreadlink(const char *filename)
932 for (size = 64; ; size *= 2) {
933 char *buf = xmalloc(size);
934 ssize_t retval = readlink(filename, buf, size);
937 if (retval >= 0 && retval < size) {
950 /* Returns a version of 'filename' with symlinks in the final component
951 * dereferenced. This differs from realpath() in that:
953 * - 'filename' need not exist.
955 * - If 'filename' does exist as a symlink, its referent need not exist.
957 * - Only symlinks in the final component of 'filename' are dereferenced.
959 * For Windows platform, this function returns a string that has the same
960 * value as the passed string.
962 * The caller must eventually free the returned string (with free()). */
964 follow_symlinks(const char *filename)
971 fn = xstrdup(filename);
972 for (i = 0; i < 10; i++) {
976 if (lstat(fn, &s) != 0 || !S_ISLNK(s.st_mode)) {
980 linkname = xreadlink(fn);
982 VLOG_WARN("%s: readlink failed (%s)",
983 filename, ovs_strerror(errno));
987 if (linkname[0] == '/') {
988 /* Target of symlink is absolute so use it raw. */
991 /* Target of symlink is relative so add to 'fn''s directory. */
992 char *dir = dir_name(fn);
994 if (!strcmp(dir, ".")) {
997 char *separator = dir[strlen(dir) - 1] == '/' ? "" : "/";
998 next_fn = xasprintf("%s%s%s", dir, separator, linkname);
1009 VLOG_WARN("%s: too many levels of symlinks", filename);
1012 return xstrdup(filename);
1015 /* Pass a value to this function if it is marked with
1016 * __attribute__((warn_unused_result)) and you genuinely want to ignore
1017 * its return value. (Note that every scalar type can be implicitly
1018 * converted to bool.) */
1019 void ignore(bool x OVS_UNUSED) { }
1021 /* Returns an appropriate delimiter for inserting just before the 0-based item
1022 * 'index' in a list that has 'total' items in it. */
1024 english_list_delimiter(size_t index, size_t total)
1026 return (index == 0 ? ""
1027 : index < total - 1 ? ", "
1028 : total > 2 ? ", and "
1032 /* Returns the number of trailing 0-bits in 'n'. Undefined if 'n' == 0. */
1033 #if __GNUC__ >= 4 || _MSC_VER
1034 /* Defined inline in util.h. */
1036 /* Returns the number of trailing 0-bits in 'n'. Undefined if 'n' == 0. */
1043 #define CTZ_STEP(X) \
1060 /* Returns the number of leading 0-bits in 'n'. Undefined if 'n' == 0. */
1062 raw_clz64(uint64_t n)
1067 #define CLZ_STEP(X) \
1085 #if NEED_COUNT_1BITS_8
1087 ((((X) & (1 << 0)) != 0) + \
1088 (((X) & (1 << 1)) != 0) + \
1089 (((X) & (1 << 2)) != 0) + \
1090 (((X) & (1 << 3)) != 0) + \
1091 (((X) & (1 << 4)) != 0) + \
1092 (((X) & (1 << 5)) != 0) + \
1093 (((X) & (1 << 6)) != 0) + \
1094 (((X) & (1 << 7)) != 0))
1095 #define INIT2(X) INIT1(X), INIT1((X) + 1)
1096 #define INIT4(X) INIT2(X), INIT2((X) + 2)
1097 #define INIT8(X) INIT4(X), INIT4((X) + 4)
1098 #define INIT16(X) INIT8(X), INIT8((X) + 8)
1099 #define INIT32(X) INIT16(X), INIT16((X) + 16)
1100 #define INIT64(X) INIT32(X), INIT32((X) + 32)
1102 const uint8_t count_1bits_8[256] = {
1103 INIT64(0), INIT64(64), INIT64(128), INIT64(192)
1107 /* Returns true if the 'n' bytes starting at 'p' are zeros. */
1109 is_all_zeros(const void *p_, size_t n)
1111 const uint8_t *p = p_;
1114 for (i = 0; i < n; i++) {
1122 /* Returns true if the 'n' bytes starting at 'p' are 0xff. */
1124 is_all_ones(const void *p_, size_t n)
1126 const uint8_t *p = p_;
1129 for (i = 0; i < n; i++) {
1137 /* Copies 'n_bits' bits starting from bit 'src_ofs' in 'src' to the 'n_bits'
1138 * starting from bit 'dst_ofs' in 'dst'. 'src' is 'src_len' bytes long and
1139 * 'dst' is 'dst_len' bytes long.
1141 * If you consider all of 'src' to be a single unsigned integer in network byte
1142 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1143 * with value 1 in src[src_len - 1], bit 1 is the bit with value 2, bit 2 is
1144 * the bit with value 4, ..., bit 8 is the bit with value 1 in src[src_len -
1145 * 2], and so on. Similarly for 'dst'.
1147 * Required invariants:
1148 * src_ofs + n_bits <= src_len * 8
1149 * dst_ofs + n_bits <= dst_len * 8
1150 * 'src' and 'dst' must not overlap.
1153 bitwise_copy(const void *src_, unsigned int src_len, unsigned int src_ofs,
1154 void *dst_, unsigned int dst_len, unsigned int dst_ofs,
1155 unsigned int n_bits)
1157 const uint8_t *src = src_;
1158 uint8_t *dst = dst_;
1160 src += src_len - (src_ofs / 8 + 1);
1163 dst += dst_len - (dst_ofs / 8 + 1);
1166 if (src_ofs == 0 && dst_ofs == 0) {
1167 unsigned int n_bytes = n_bits / 8;
1171 memcpy(dst, src, n_bytes);
1178 uint8_t mask = (1 << n_bits) - 1;
1179 *dst = (*dst & ~mask) | (*src & mask);
1182 while (n_bits > 0) {
1183 unsigned int max_copy = 8 - MAX(src_ofs, dst_ofs);
1184 unsigned int chunk = MIN(n_bits, max_copy);
1185 uint8_t mask = ((1 << chunk) - 1) << dst_ofs;
1188 *dst |= ((*src >> src_ofs) << dst_ofs) & mask;
1205 /* Zeros the 'n_bits' bits starting from bit 'dst_ofs' in 'dst'. 'dst' is
1206 * 'dst_len' bytes long.
1208 * If you consider all of 'dst' to be a single unsigned integer in network byte
1209 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1210 * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
1211 * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
1214 * Required invariant:
1215 * dst_ofs + n_bits <= dst_len * 8
1218 bitwise_zero(void *dst_, unsigned int dst_len, unsigned dst_ofs,
1219 unsigned int n_bits)
1221 uint8_t *dst = dst_;
1227 dst += dst_len - (dst_ofs / 8 + 1);
1231 unsigned int chunk = MIN(n_bits, 8 - dst_ofs);
1233 *dst &= ~(((1 << chunk) - 1) << dst_ofs);
1243 while (n_bits >= 8) {
1249 *dst &= ~((1 << n_bits) - 1);
1253 /* Sets to 1 all of the 'n_bits' bits starting from bit 'dst_ofs' in 'dst'.
1254 * 'dst' is 'dst_len' bytes long.
1256 * If you consider all of 'dst' to be a single unsigned integer in network byte
1257 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1258 * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
1259 * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
1262 * Required invariant:
1263 * dst_ofs + n_bits <= dst_len * 8
1266 bitwise_one(void *dst_, unsigned int dst_len, unsigned dst_ofs,
1267 unsigned int n_bits)
1269 uint8_t *dst = dst_;
1275 dst += dst_len - (dst_ofs / 8 + 1);
1279 unsigned int chunk = MIN(n_bits, 8 - dst_ofs);
1281 *dst |= ((1 << chunk) - 1) << dst_ofs;
1291 while (n_bits >= 8) {
1297 *dst |= (1 << n_bits) - 1;
1301 /* Scans the 'n_bits' bits starting from bit 'dst_ofs' in 'dst' for 1-bits.
1302 * Returns false if any 1-bits are found, otherwise true. 'dst' is 'dst_len'
1305 * If you consider all of 'dst' to be a single unsigned integer in network byte
1306 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1307 * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
1308 * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
1311 * Required invariant:
1312 * dst_ofs + n_bits <= dst_len * 8
1315 bitwise_is_all_zeros(const void *p_, unsigned int len, unsigned int ofs,
1316 unsigned int n_bits)
1318 const uint8_t *p = p_;
1324 p += len - (ofs / 8 + 1);
1328 unsigned int chunk = MIN(n_bits, 8 - ofs);
1330 if (*p & (((1 << chunk) - 1) << ofs)) {
1342 while (n_bits >= 8) {
1350 if (n_bits && *p & ((1 << n_bits) - 1)) {
1357 /* Scans the bits in 'p' that have bit offsets 'start' (inclusive) through
1358 * 'end' (exclusive) for the first bit with value 'target'. If one is found,
1359 * returns its offset, otherwise 'end'. 'p' is 'len' bytes long.
1361 * If you consider all of 'p' to be a single unsigned integer in network byte
1362 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1363 * with value 1 in p[len - 1], bit 1 is the bit with value 2, bit 2 is the bit
1364 * with value 4, ..., bit 8 is the bit with value 1 in p[len - 2], and so on.
1366 * Required invariant:
1370 bitwise_scan(const void *p, unsigned int len, bool target, unsigned int start,
1375 for (ofs = start; ofs < end; ofs++) {
1376 if (bitwise_get_bit(p, len, ofs) == target) {
1383 /* Scans the bits in 'p' that have bit offsets 'start' (inclusive) through
1384 * 'end' (exclusive) for the first bit with value 'target', in reverse order.
1385 * If one is found, returns its offset, otherwise 'end'. 'p' is 'len' bytes
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 * To scan an entire bit array in reverse order, specify start == len * 8 - 1
1394 * and end == -1, in which case the return value is nonnegative if successful
1395 * and -1 if no 'target' match is found.
1397 * Required invariant:
1401 bitwise_rscan(const void *p, unsigned int len, bool target, int start, int end)
1405 for (ofs = start; ofs > end; ofs--) {
1406 if (bitwise_get_bit(p, len, ofs) == target) {
1413 /* Copies the 'n_bits' low-order bits of 'value' into the 'n_bits' bits
1414 * starting at bit 'dst_ofs' in 'dst', which is 'dst_len' bytes long.
1416 * If you consider all of 'dst' to be a single unsigned integer in network byte
1417 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1418 * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
1419 * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
1422 * Required invariants:
1423 * dst_ofs + n_bits <= dst_len * 8
1427 bitwise_put(uint64_t value,
1428 void *dst, unsigned int dst_len, unsigned int dst_ofs,
1429 unsigned int n_bits)
1431 ovs_be64 n_value = htonll(value);
1432 bitwise_copy(&n_value, sizeof n_value, 0,
1433 dst, dst_len, dst_ofs,
1437 /* Returns the value of the 'n_bits' bits starting at bit 'src_ofs' in 'src',
1438 * which is 'src_len' bytes long.
1440 * If you consider all of 'src' to be a single unsigned integer in network byte
1441 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1442 * with value 1 in src[src_len - 1], bit 1 is the bit with value 2, bit 2 is
1443 * the bit with value 4, ..., bit 8 is the bit with value 1 in src[src_len -
1446 * Required invariants:
1447 * src_ofs + n_bits <= src_len * 8
1451 bitwise_get(const void *src, unsigned int src_len,
1452 unsigned int src_ofs, unsigned int n_bits)
1454 ovs_be64 value = htonll(0);
1456 bitwise_copy(src, src_len, src_ofs,
1457 &value, sizeof value, 0,
1459 return ntohll(value);
1462 /* Returns the value of the bit with offset 'ofs' in 'src', which is 'len'
1465 * If you consider all of 'src' to be a single unsigned integer in network byte
1466 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1467 * with value 1 in src[len - 1], bit 1 is the bit with value 2, bit 2 is the
1468 * bit with value 4, ..., bit 8 is the bit with value 1 in src[len - 2], and so
1471 * Required invariants:
1475 bitwise_get_bit(const void *src_, unsigned int len, unsigned int ofs)
1477 const uint8_t *src = src_;
1479 return (src[len - (ofs / 8 + 1)] & (1u << (ofs % 8))) != 0;
1482 /* Sets the bit with offset 'ofs' in 'dst', which is 'len' bytes long, to 0.
1484 * If you consider all of 'dst' to be a single unsigned integer in network byte
1485 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1486 * with value 1 in dst[len - 1], bit 1 is the bit with value 2, bit 2 is the
1487 * bit with value 4, ..., bit 8 is the bit with value 1 in dst[len - 2], and so
1490 * Required invariants:
1494 bitwise_put0(void *dst_, unsigned int len, unsigned int ofs)
1496 uint8_t *dst = dst_;
1498 dst[len - (ofs / 8 + 1)] &= ~(1u << (ofs % 8));
1501 /* Sets the bit with offset 'ofs' in 'dst', which is 'len' bytes long, to 1.
1503 * If you consider all of 'dst' to be a single unsigned integer in network byte
1504 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1505 * with value 1 in dst[len - 1], bit 1 is the bit with value 2, bit 2 is the
1506 * bit with value 4, ..., bit 8 is the bit with value 1 in dst[len - 2], and so
1509 * Required invariants:
1513 bitwise_put1(void *dst_, unsigned int len, unsigned int ofs)
1515 uint8_t *dst = dst_;
1517 dst[len - (ofs / 8 + 1)] |= 1u << (ofs % 8);
1520 /* Sets the bit with offset 'ofs' in 'dst', which is 'len' bytes long, to 'b'.
1522 * If you consider all of 'dst' to be a single unsigned integer in network byte
1523 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1524 * with value 1 in dst[len - 1], bit 1 is the bit with value 2, bit 2 is the
1525 * bit with value 4, ..., bit 8 is the bit with value 1 in dst[len - 2], and so
1528 * Required invariants:
1532 bitwise_put_bit(void *dst, unsigned int len, unsigned int ofs, bool b)
1535 bitwise_put1(dst, len, ofs);
1537 bitwise_put0(dst, len, ofs);
1541 /* Flips the bit with offset 'ofs' in 'dst', which is 'len' bytes long.
1543 * If you consider all of 'dst' to be a single unsigned integer in network byte
1544 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1545 * with value 1 in dst[len - 1], bit 1 is the bit with value 2, bit 2 is the
1546 * bit with value 4, ..., bit 8 is the bit with value 1 in dst[len - 2], and so
1549 * Required invariants:
1553 bitwise_toggle_bit(void *dst_, unsigned int len, unsigned int ofs)
1555 uint8_t *dst = dst_;
1557 dst[len - (ofs / 8 + 1)] ^= 1u << (ofs % 8);
1578 skip_spaces(const char *s)
1580 while (isspace((unsigned char) *s)) {
1587 scan_int(const char *s, const struct scan_spec *spec, int base, va_list *args)
1589 const char *start = s;
1594 negative = *s == '-';
1595 s += *s == '-' || *s == '+';
1597 if ((!base || base == 16) && *s == '0' && (s[1] == 'x' || s[1] == 'X')) {
1601 base = *s == '0' ? 8 : 10;
1604 if (s - start >= spec->width) {
1610 while (s - start < spec->width) {
1611 int digit = hexit_value(*s);
1613 if (digit < 0 || digit >= base) {
1616 value = value * base + digit;
1628 switch (spec->type) {
1632 *va_arg(*args, char *) = value;
1635 *va_arg(*args, short int *) = value;
1638 *va_arg(*args, int *) = value;
1641 *va_arg(*args, long int *) = value;
1644 *va_arg(*args, long long int *) = value;
1647 *va_arg(*args, intmax_t *) = value;
1649 case SCAN_PTRDIFF_T:
1650 *va_arg(*args, ptrdiff_t *) = value;
1653 *va_arg(*args, size_t *) = value;
1660 skip_digits(const char *s)
1662 while (*s >= '0' && *s <= '9') {
1669 scan_float(const char *s, const struct scan_spec *spec, va_list *args)
1671 const char *start = s;
1677 s += *s == '+' || *s == '-';
1680 s = skip_digits(s + 1);
1682 if (*s == 'e' || *s == 'E') {
1684 s += *s == '+' || *s == '-';
1688 if (s - start > spec->width) {
1689 s = start + spec->width;
1692 copy = xmemdup0(start, s - start);
1693 value = strtold(copy, &tail);
1700 switch (spec->type) {
1704 *va_arg(*args, float *) = value;
1707 *va_arg(*args, double *) = value;
1710 *va_arg(*args, long double *) = value;
1716 case SCAN_PTRDIFF_T:
1724 scan_output_string(const struct scan_spec *spec,
1725 const char *s, size_t n,
1728 if (spec->type != SCAN_DISCARD) {
1729 char *out = va_arg(*args, char *);
1736 scan_string(const char *s, const struct scan_spec *spec, va_list *args)
1740 for (n = 0; n < spec->width; n++) {
1741 if (!s[n] || isspace((unsigned char) s[n])) {
1749 scan_output_string(spec, s, n, args);
1754 parse_scanset(const char *p_, unsigned long *set, bool *complemented)
1756 const uint8_t *p = (const uint8_t *) p_;
1758 *complemented = *p == '^';
1762 bitmap_set1(set, ']');
1766 while (*p && *p != ']') {
1767 if (p[1] == '-' && p[2] != ']' && p[2] > *p) {
1768 bitmap_set_multiple(set, *p, p[2] - *p + 1, true);
1771 bitmap_set1(set, *p++);
1777 return (const char *) p;
1781 scan_set(const char *s, const struct scan_spec *spec, const char **pp,
1784 unsigned long set[BITMAP_N_LONGS(UCHAR_MAX + 1)];
1788 /* Parse the scan set. */
1789 memset(set, 0, sizeof set);
1790 *pp = parse_scanset(*pp, set, &complemented);
1792 /* Parse the data. */
1795 && bitmap_is_set(set, (unsigned char) s[n]) == !complemented
1796 && n < spec->width) {
1802 scan_output_string(spec, s, n, args);
1807 scan_chars(const char *s, const struct scan_spec *spec, va_list *args)
1809 unsigned int n = spec->width == UINT_MAX ? 1 : spec->width;
1811 if (strlen(s) < n) {
1814 if (spec->type != SCAN_DISCARD) {
1815 memcpy(va_arg(*args, char *), s, n);
1821 ovs_scan__(const char *s, int *n, const char *format, va_list *args)
1823 const char *const start = s;
1828 while (*p != '\0') {
1829 struct scan_spec spec;
1830 unsigned char c = *p++;
1836 } else if (c != '%') {
1842 } else if (*p == '%') {
1850 /* Parse '*' flag. */
1851 discard = *p == '*';
1854 /* Parse field width. */
1856 while (*p >= '0' && *p <= '9') {
1857 spec.width = spec.width * 10 + (*p++ - '0');
1859 if (spec.width == 0) {
1860 spec.width = UINT_MAX;
1863 /* Parse type modifier. */
1867 spec.type = SCAN_CHAR;
1870 spec.type = SCAN_SHORT;
1876 spec.type = SCAN_INTMAX_T;
1882 spec.type = SCAN_LLONG;
1885 spec.type = SCAN_LONG;
1892 spec.type = SCAN_LLONG;
1897 spec.type = SCAN_PTRDIFF_T;
1902 spec.type = SCAN_SIZE_T;
1907 spec.type = SCAN_INT;
1912 spec.type = SCAN_DISCARD;
1916 if (c != 'c' && c != 'n' && c != '[') {
1921 s = scan_int(s, &spec, 10, args);
1925 s = scan_int(s, &spec, 0, args);
1929 s = scan_int(s, &spec, 8, args);
1933 s = scan_int(s, &spec, 10, args);
1938 s = scan_int(s, &spec, 16, args);
1946 s = scan_float(s, &spec, args);
1950 s = scan_string(s, &spec, args);
1954 s = scan_set(s, &spec, &p, args);
1958 s = scan_chars(s, &spec, args);
1962 if (spec.type != SCAN_DISCARD) {
1963 *va_arg(*args, int *) = s - start;
1981 /* This is an implementation of the standard sscanf() function, with the
1982 * following exceptions:
1984 * - It returns true if the entire format was successfully scanned and
1985 * converted, false if any conversion failed.
1987 * - The standard doesn't define sscanf() behavior when an out-of-range value
1988 * is scanned, e.g. if a "%"PRIi8 conversion scans "-1" or "0x1ff". Some
1989 * implementations consider this an error and stop scanning. This
1990 * implementation never considers an out-of-range value an error; instead,
1991 * it stores the least-significant bits of the converted value in the
1992 * destination, e.g. the value 255 for both examples earlier.
1994 * - Only single-byte characters are supported, that is, the 'l' modifier
1995 * on %s, %[, and %c is not supported. The GNU extension 'a' modifier is
1996 * also not supported.
1998 * - %p is not supported.
2001 ovs_scan(const char *s, const char *format, ...)
2006 va_start(args, format);
2007 res = ovs_scan__(s, NULL, format, &args);
2013 * This function is similar to ovs_scan(), with an extra parameter `n` added to
2014 * return the number of scanned characters.
2017 ovs_scan_len(const char *s, int *n, const char *format, ...)
2023 va_start(args, format);
2024 success = ovs_scan__(s + *n, &n1, format, &args);
2033 xsleep(unsigned int seconds)
2035 ovsrcu_quiesce_start();
2037 Sleep(seconds * 1000);
2041 ovsrcu_quiesce_end();
2047 ovs_format_message(int error)
2049 enum { BUFSIZE = sizeof strerror_buffer_get()->s };
2050 char *buffer = strerror_buffer_get()->s;
2052 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
2053 NULL, error, 0, buffer, BUFSIZE, NULL);
2057 /* Returns a null-terminated string that explains the last error.
2058 * Use this function to get the error string for WINAPI calls. */
2060 ovs_lasterror_to_string(void)
2062 return ovs_format_message(GetLastError());
2066 ftruncate(int fd, off_t length)
2070 error = _chsize_s(fd, length);
2077 OVS_CONSTRUCTOR(winsock_start) {
2081 error = WSAStartup(MAKEWORD(2, 2), &wsaData);
2083 VLOG_FATAL("WSAStartup failed: %s", sock_strerror(sock_errno()));