2 * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013 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"
33 #include "ovs-thread.h"
35 #ifdef HAVE_PTHREAD_SET_NAME_NP
36 #include <pthread_np.h>
39 VLOG_DEFINE_THIS_MODULE(util);
41 COVERAGE_DEFINE(util_xalloc);
43 /* argv[0] without directory names. */
44 const char *program_name;
46 /* Name for the currently running thread or process, for log messages, process
47 * listings, and debuggers. */
48 DEFINE_PER_THREAD_MALLOCED_DATA(char *, subprogram_name);
50 /* --version option output. */
51 static char *program_version;
53 /* Buffer used by ovs_strerror() and ovs_format_message(). */
54 DEFINE_STATIC_PER_THREAD_DATA(struct { char s[128]; },
58 static char *xreadlink(const char *filename);
61 ovs_assert_failure(const char *where, const char *function,
62 const char *condition)
64 /* Prevent an infinite loop (or stack overflow) in case VLOG_ABORT happens
65 * to trigger an assertion failure of its own. */
66 static int reentry = 0;
70 VLOG_ABORT("%s: assertion %s failed in %s()",
71 where, condition, function);
75 fprintf(stderr, "%s: assertion %s failed in %s()",
76 where, condition, function);
87 ovs_abort(0, "virtual memory exhausted");
91 xcalloc(size_t count, size_t size)
93 void *p = count && size ? calloc(count, size) : malloc(1);
94 COVERAGE_INC(util_xalloc);
104 return xcalloc(1, size);
110 void *p = malloc(size ? size : 1);
111 COVERAGE_INC(util_xalloc);
119 xrealloc(void *p, size_t size)
121 p = realloc(p, size ? size : 1);
122 COVERAGE_INC(util_xalloc);
130 xmemdup(const void *p_, size_t size)
132 void *p = xmalloc(size);
138 xmemdup0(const char *p_, size_t length)
140 char *p = xmalloc(length + 1);
141 memcpy(p, p_, length);
147 xstrdup(const char *s)
149 return xmemdup0(s, strlen(s));
153 xvasprintf(const char *format, va_list args)
159 va_copy(args2, args);
160 needed = vsnprintf(NULL, 0, format, args);
162 s = xmalloc(needed + 1);
164 vsnprintf(s, needed + 1, format, args2);
171 x2nrealloc(void *p, size_t *n, size_t s)
173 *n = *n == 0 ? 1 : 2 * *n;
174 return xrealloc(p, *n * s);
178 xasprintf(const char *format, ...)
183 va_start(args, format);
184 s = xvasprintf(format, args);
190 /* Similar to strlcpy() from OpenBSD, but it never reads more than 'size - 1'
191 * bytes from 'src' and doesn't return anything. */
193 ovs_strlcpy(char *dst, const char *src, size_t size)
196 size_t len = strnlen(src, size - 1);
197 memcpy(dst, src, len);
202 /* Copies 'src' to 'dst'. Reads no more than 'size - 1' bytes from 'src'.
203 * Always null-terminates 'dst' (if 'size' is nonzero), and writes a zero byte
204 * to every otherwise unused byte in 'dst'.
206 * Except for performance, the following call:
207 * ovs_strzcpy(dst, src, size);
208 * is equivalent to these two calls:
209 * memset(dst, '\0', size);
210 * ovs_strlcpy(dst, src, size);
212 * (Thus, ovs_strzcpy() is similar to strncpy() without some of the pitfalls.)
215 ovs_strzcpy(char *dst, const char *src, size_t size)
218 size_t len = strnlen(src, size - 1);
219 memcpy(dst, src, len);
220 memset(dst + len, '\0', size - len);
224 /* Prints 'format' on stderr, formatting it like printf() does. If 'err_no' is
225 * nonzero, then it is formatted with ovs_retval_to_string() and appended to
226 * the message inside parentheses. Then, terminates with abort().
228 * This function is preferred to ovs_fatal() in a situation where it would make
229 * sense for a monitoring process to restart the daemon.
231 * 'format' should not end with a new-line, because this function will add one
234 ovs_abort(int err_no, const char *format, ...)
238 va_start(args, format);
239 ovs_abort_valist(err_no, format, args);
242 /* Same as ovs_abort() except that the arguments are supplied as a va_list. */
244 ovs_abort_valist(int err_no, const char *format, va_list args)
246 ovs_error_valist(err_no, format, args);
250 /* Prints 'format' on stderr, formatting it like printf() does. If 'err_no' is
251 * nonzero, then it is formatted with ovs_retval_to_string() and appended to
252 * the message inside parentheses. Then, terminates with EXIT_FAILURE.
254 * 'format' should not end with a new-line, because this function will add one
257 ovs_fatal(int err_no, const char *format, ...)
261 va_start(args, format);
262 ovs_fatal_valist(err_no, format, args);
265 /* Same as ovs_fatal() except that the arguments are supplied as a va_list. */
267 ovs_fatal_valist(int err_no, const char *format, va_list args)
269 ovs_error_valist(err_no, format, args);
273 /* Prints 'format' on stderr, formatting it like printf() does. If 'err_no' is
274 * nonzero, then it is formatted with ovs_retval_to_string() and appended to
275 * the message inside parentheses.
277 * 'format' should not end with a new-line, because this function will add one
280 ovs_error(int err_no, const char *format, ...)
284 va_start(args, format);
285 ovs_error_valist(err_no, format, args);
289 /* Same as ovs_error() except that the arguments are supplied as a va_list. */
291 ovs_error_valist(int err_no, const char *format, va_list args)
293 const char *subprogram_name = get_subprogram_name();
294 int save_errno = errno;
296 if (subprogram_name[0]) {
297 fprintf(stderr, "%s(%s): ", program_name, subprogram_name);
299 fprintf(stderr, "%s: ", program_name);
302 vfprintf(stderr, format, args);
304 fprintf(stderr, " (%s)", ovs_retval_to_string(err_no));
311 /* Many OVS functions return an int which is one of:
314 * - EOF: end of file (not necessarily an error; depends on the function called)
316 * Returns the appropriate human-readable string. The caller must copy the
317 * string if it wants to hold onto it, as the storage may be overwritten on
318 * subsequent function calls.
321 ovs_retval_to_string(int retval)
324 : retval == EOF ? "End of file"
325 : ovs_strerror(retval));
328 /* This function returns the string describing the error number in 'error'
329 * for POSIX platforms. For Windows, this function can be used for C library
330 * calls. For socket calls that are also used in Windows, use sock_strerror()
331 * instead. For WINAPI calls, look at ovs_lasterror_to_string(). */
333 ovs_strerror(int error)
335 enum { BUFSIZE = sizeof strerror_buffer_get()->s };
341 buffer = strerror_buffer_get()->s;
343 #if STRERROR_R_CHAR_P
344 /* GNU style strerror_r() might return an immutable static string, or it
345 * might write and return 'buffer', but in either case we can pass the
346 * returned string directly to the caller. */
347 s = strerror_r(error, buffer, BUFSIZE);
348 #else /* strerror_r() returns an int. */
350 if (strerror_r(error, buffer, BUFSIZE)) {
351 /* strerror_r() is only allowed to fail on ERANGE (because the buffer
352 * is too short). We don't check the actual failure reason because
353 * POSIX requires strerror_r() to return the error but old glibc
354 * (before 2.13) returns -1 and sets errno. */
355 snprintf(buffer, BUFSIZE, "Unknown error %d", error);
364 /* Sets global "program_name" and "program_version" variables. Should
365 * be called at the beginning of main() with "argv[0]" as the argument
368 * 'version' should contain the version of the caller's program. If 'version'
369 * is the same as the VERSION #define, the caller is assumed to be part of Open
370 * vSwitch. Otherwise, it is assumed to be an external program linking against
371 * the Open vSwitch libraries.
373 * The 'date' and 'time' arguments should likely be called with
374 * "__DATE__" and "__TIME__" to use the time the binary was built.
375 * Alternatively, the "set_program_name" macro may be called to do this
379 set_program_name__(const char *argv0, const char *version, const char *date,
384 size_t max_len = strlen(argv0) + 1;
389 basename = xmalloc(max_len);
390 _splitpath_s(argv0, NULL, 0, NULL, 0, basename, max_len, NULL, 0);
391 assert_single_threaded();
392 program_name = basename;
394 const char *slash = strrchr(argv0, '/');
395 assert_single_threaded();
396 program_name = slash ? slash + 1 : argv0;
399 free(program_version);
401 if (!strcmp(version, VERSION)) {
402 program_version = xasprintf("%s (Open vSwitch) "VERSION"\n"
404 program_name, date, time);
406 program_version = xasprintf("%s %s\n"
407 "Open vSwitch Library "VERSION"\n"
409 program_name, version, date, time);
413 /* Returns the name of the currently running thread or process. */
415 get_subprogram_name(void)
417 const char *name = subprogram_name_get();
418 return name ? name : "";
421 /* Sets the formatted value of 'format' as the name of the currently running
422 * thread or process. (This appears in log messages and may also be visible in
423 * system process listings and debuggers.) */
425 set_subprogram_name(const char *format, ...)
432 va_start(args, format);
433 pname = xvasprintf(format, args);
436 pname = xstrdup(program_name);
439 free(subprogram_name_set(pname));
441 #if HAVE_GLIBC_PTHREAD_SETNAME_NP
442 pthread_setname_np(pthread_self(), pname);
443 #elif HAVE_NETBSD_PTHREAD_SETNAME_NP
444 pthread_setname_np(pthread_self(), "%s", pname);
445 #elif HAVE_PTHREAD_SET_NAME_NP
446 pthread_set_name_np(pthread_self(), pname);
450 /* Returns a pointer to a string describing the program version. The
451 * caller must not modify or free the returned string.
454 get_program_version(void)
456 return program_version;
459 /* Print the version information for the program. */
461 ovs_print_version(uint8_t min_ofp, uint8_t max_ofp)
463 printf("%s", program_version);
464 if (min_ofp || max_ofp) {
465 printf("OpenFlow versions %#x:%#x\n", min_ofp, max_ofp);
469 /* Writes the 'size' bytes in 'buf' to 'stream' as hex bytes arranged 16 per
470 * line. Numeric offsets are also included, starting at 'ofs' for the first
471 * byte in 'buf'. If 'ascii' is true then the corresponding ASCII characters
472 * are also rendered alongside. */
474 ovs_hex_dump(FILE *stream, const void *buf_, size_t size,
475 uintptr_t ofs, bool ascii)
477 const uint8_t *buf = buf_;
478 const size_t per_line = 16; /* Maximum bytes per line. */
482 size_t start, end, n;
485 /* Number of bytes on this line. */
486 start = ofs % per_line;
488 if (end - start > size)
493 fprintf(stream, "%08"PRIxMAX" ", (uintmax_t) ROUND_DOWN(ofs, per_line));
494 for (i = 0; i < start; i++)
495 fprintf(stream, " ");
497 fprintf(stream, "%02x%c",
498 buf[i - start], i == per_line / 2 - 1? '-' : ' ');
501 for (; i < per_line; i++)
502 fprintf(stream, " ");
503 fprintf(stream, "|");
504 for (i = 0; i < start; i++)
505 fprintf(stream, " ");
506 for (; i < end; i++) {
507 int c = buf[i - start];
508 putc(c >= 32 && c < 127 ? c : '.', stream);
510 for (; i < per_line; i++)
511 fprintf(stream, " ");
512 fprintf(stream, "|");
514 fprintf(stream, "\n");
523 str_to_int(const char *s, int base, int *i)
526 bool ok = str_to_llong(s, base, &ll);
532 str_to_long(const char *s, int base, long *li)
535 bool ok = str_to_llong(s, base, &ll);
541 str_to_llong(const char *s, int base, long long *x)
543 int save_errno = errno;
546 *x = strtoll(s, &tail, base);
547 if (errno == EINVAL || errno == ERANGE || tail == s || *tail != '\0') {
557 /* Converts floating-point string 's' into a double. If successful, stores
558 * the double in '*d' and returns true; on failure, stores 0 in '*d' and
561 * Underflow (e.g. "1e-9999") is not considered an error, but overflow
562 * (e.g. "1e9999)" is. */
564 str_to_double(const char *s, double *d)
566 int save_errno = errno;
569 *d = strtod(s, &tail);
570 if (errno == EINVAL || (errno == ERANGE && *d != 0)
571 || tail == s || *tail != '\0') {
581 /* Returns the value of 'c' as a hexadecimal digit. */
586 case '0': case '1': case '2': case '3': case '4':
587 case '5': case '6': case '7': case '8': case '9':
613 /* Returns the integer value of the 'n' hexadecimal digits starting at 's', or
614 * UINT_MAX if one of those "digits" is not really a hex digit. If 'ok' is
615 * nonnull, '*ok' is set to true if the conversion succeeds or to false if a
616 * non-hex digit is detected. */
618 hexits_value(const char *s, size_t n, bool *ok)
624 for (i = 0; i < n; i++) {
625 int hexit = hexit_value(s[i]);
632 value = (value << 4) + hexit;
640 /* Returns the current working directory as a malloc()'d string, or a null
641 * pointer if the current working directory cannot be determined. */
648 /* Get maximum path length or at least a reasonable estimate. */
649 path_max = pathconf(".", _PC_PATH_MAX);
650 size = (path_max < 0 ? 1024
651 : path_max > 10240 ? 10240
654 /* Get current working directory. */
656 char *buf = xmalloc(size);
657 if (getcwd(buf, size)) {
658 return xrealloc(buf, strlen(buf) + 1);
662 if (error != ERANGE) {
663 VLOG_WARN("getcwd failed (%s)", ovs_strerror(error));
672 all_slashes_name(const char *s)
674 return xstrdup(s[0] == '/' && s[1] == '/' && s[2] != '/' ? "//"
679 /* Returns the directory name portion of 'file_name' as a malloc()'d string,
680 * similar to the POSIX dirname() function but thread-safe. */
682 dir_name(const char *file_name)
684 size_t len = strlen(file_name);
685 while (len > 0 && file_name[len - 1] == '/') {
688 while (len > 0 && file_name[len - 1] != '/') {
691 while (len > 0 && file_name[len - 1] == '/') {
694 return len ? xmemdup0(file_name, len) : all_slashes_name(file_name);
697 /* Returns the file name portion of 'file_name' as a malloc()'d string,
698 * similar to the POSIX basename() function but thread-safe. */
700 base_name(const char *file_name)
704 end = strlen(file_name);
705 while (end > 0 && file_name[end - 1] == '/') {
710 return all_slashes_name(file_name);
714 while (start > 0 && file_name[start - 1] != '/') {
718 return xmemdup0(file_name + start, end - start);
721 /* If 'file_name' starts with '/', returns a copy of 'file_name'. Otherwise,
722 * returns an absolute path to 'file_name' considering it relative to 'dir',
723 * which itself must be absolute. 'dir' may be null or the empty string, in
724 * which case the current working directory is used.
726 * Returns a null pointer if 'dir' is null and getcwd() fails. */
728 abs_file_name(const char *dir, const char *file_name)
730 if (file_name[0] == '/') {
731 return xstrdup(file_name);
732 } else if (dir && dir[0]) {
733 char *separator = dir[strlen(dir) - 1] == '/' ? "" : "/";
734 return xasprintf("%s%s%s", dir, separator, file_name);
736 char *cwd = get_cwd();
738 char *abs_name = xasprintf("%s/%s", cwd, file_name);
747 /* Like readlink(), but returns the link name as a null-terminated string in
748 * allocated memory that the caller must eventually free (with free()).
749 * Returns NULL on error, in which case errno is set appropriately. */
751 xreadlink(const char *filename)
755 for (size = 64; ; size *= 2) {
756 char *buf = xmalloc(size);
757 ssize_t retval = readlink(filename, buf, size);
760 if (retval >= 0 && retval < size) {
773 /* Returns a version of 'filename' with symlinks in the final component
774 * dereferenced. This differs from realpath() in that:
776 * - 'filename' need not exist.
778 * - If 'filename' does exist as a symlink, its referent need not exist.
780 * - Only symlinks in the final component of 'filename' are dereferenced.
782 * For Windows platform, this function returns a string that has the same
783 * value as the passed string.
785 * The caller must eventually free the returned string (with free()). */
787 follow_symlinks(const char *filename)
794 fn = xstrdup(filename);
795 for (i = 0; i < 10; i++) {
799 if (lstat(fn, &s) != 0 || !S_ISLNK(s.st_mode)) {
803 linkname = xreadlink(fn);
805 VLOG_WARN("%s: readlink failed (%s)",
806 filename, ovs_strerror(errno));
810 if (linkname[0] == '/') {
811 /* Target of symlink is absolute so use it raw. */
814 /* Target of symlink is relative so add to 'fn''s directory. */
815 char *dir = dir_name(fn);
817 if (!strcmp(dir, ".")) {
820 char *separator = dir[strlen(dir) - 1] == '/' ? "" : "/";
821 next_fn = xasprintf("%s%s%s", dir, separator, linkname);
832 VLOG_WARN("%s: too many levels of symlinks", filename);
835 return xstrdup(filename);
838 /* Pass a value to this function if it is marked with
839 * __attribute__((warn_unused_result)) and you genuinely want to ignore
840 * its return value. (Note that every scalar type can be implicitly
841 * converted to bool.) */
842 void ignore(bool x OVS_UNUSED) { }
844 /* Returns an appropriate delimiter for inserting just before the 0-based item
845 * 'index' in a list that has 'total' items in it. */
847 english_list_delimiter(size_t index, size_t total)
849 return (index == 0 ? ""
850 : index < total - 1 ? ", "
851 : total > 2 ? ", and "
855 /* Returns the number of trailing 0-bits in 'n'. Undefined if 'n' == 0. */
857 /* Defined inline in util.h. */
859 /* Returns the number of trailing 0-bits in 'n'. Undefined if 'n' == 0. */
866 #define CTZ_STEP(X) \
883 /* Returns the number of leading 0-bits in 'n'. Undefined if 'n' == 0. */
885 raw_clz64(uint64_t n)
890 #define CLZ_STEP(X) \
908 #if NEED_COUNT_1BITS_8
910 ((((X) & (1 << 0)) != 0) + \
911 (((X) & (1 << 1)) != 0) + \
912 (((X) & (1 << 2)) != 0) + \
913 (((X) & (1 << 3)) != 0) + \
914 (((X) & (1 << 4)) != 0) + \
915 (((X) & (1 << 5)) != 0) + \
916 (((X) & (1 << 6)) != 0) + \
917 (((X) & (1 << 7)) != 0))
918 #define INIT2(X) INIT1(X), INIT1((X) + 1)
919 #define INIT4(X) INIT2(X), INIT2((X) + 2)
920 #define INIT8(X) INIT4(X), INIT4((X) + 4)
921 #define INIT16(X) INIT8(X), INIT8((X) + 8)
922 #define INIT32(X) INIT16(X), INIT16((X) + 16)
923 #define INIT64(X) INIT32(X), INIT32((X) + 32)
925 const uint8_t count_1bits_8[256] = {
926 INIT64(0), INIT64(64), INIT64(128), INIT64(192)
930 /* Returns true if the 'n' bytes starting at 'p' are zeros. */
932 is_all_zeros(const uint8_t *p, size_t n)
936 for (i = 0; i < n; i++) {
944 /* Returns true if the 'n' bytes starting at 'p' are 0xff. */
946 is_all_ones(const uint8_t *p, size_t n)
950 for (i = 0; i < n; i++) {
958 /* Copies 'n_bits' bits starting from bit 'src_ofs' in 'src' to the 'n_bits'
959 * starting from bit 'dst_ofs' in 'dst'. 'src' is 'src_len' bytes long and
960 * 'dst' is 'dst_len' bytes long.
962 * If you consider all of 'src' to be a single unsigned integer in network byte
963 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
964 * with value 1 in src[src_len - 1], bit 1 is the bit with value 2, bit 2 is
965 * the bit with value 4, ..., bit 8 is the bit with value 1 in src[src_len -
966 * 2], and so on. Similarly for 'dst'.
968 * Required invariants:
969 * src_ofs + n_bits <= src_len * 8
970 * dst_ofs + n_bits <= dst_len * 8
971 * 'src' and 'dst' must not overlap.
974 bitwise_copy(const void *src_, unsigned int src_len, unsigned int src_ofs,
975 void *dst_, unsigned int dst_len, unsigned int dst_ofs,
978 const uint8_t *src = src_;
981 src += src_len - (src_ofs / 8 + 1);
984 dst += dst_len - (dst_ofs / 8 + 1);
987 if (src_ofs == 0 && dst_ofs == 0) {
988 unsigned int n_bytes = n_bits / 8;
992 memcpy(dst, src, n_bytes);
999 uint8_t mask = (1 << n_bits) - 1;
1000 *dst = (*dst & ~mask) | (*src & mask);
1003 while (n_bits > 0) {
1004 unsigned int max_copy = 8 - MAX(src_ofs, dst_ofs);
1005 unsigned int chunk = MIN(n_bits, max_copy);
1006 uint8_t mask = ((1 << chunk) - 1) << dst_ofs;
1009 *dst |= ((*src >> src_ofs) << dst_ofs) & mask;
1026 /* Zeros the 'n_bits' bits starting from bit 'dst_ofs' in 'dst'. 'dst' is
1027 * 'dst_len' bytes long.
1029 * If you consider all of 'dst' to be a single unsigned integer in network byte
1030 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1031 * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
1032 * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
1035 * Required invariant:
1036 * dst_ofs + n_bits <= dst_len * 8
1039 bitwise_zero(void *dst_, unsigned int dst_len, unsigned dst_ofs,
1040 unsigned int n_bits)
1042 uint8_t *dst = dst_;
1048 dst += dst_len - (dst_ofs / 8 + 1);
1052 unsigned int chunk = MIN(n_bits, 8 - dst_ofs);
1054 *dst &= ~(((1 << chunk) - 1) << dst_ofs);
1064 while (n_bits >= 8) {
1070 *dst &= ~((1 << n_bits) - 1);
1074 /* Sets to 1 all of the 'n_bits' bits starting from bit 'dst_ofs' in 'dst'.
1075 * 'dst' is 'dst_len' bytes long.
1077 * If you consider all of 'dst' to be a single unsigned integer in network byte
1078 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1079 * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
1080 * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
1083 * Required invariant:
1084 * dst_ofs + n_bits <= dst_len * 8
1087 bitwise_one(void *dst_, unsigned int dst_len, unsigned dst_ofs,
1088 unsigned int n_bits)
1090 uint8_t *dst = dst_;
1096 dst += dst_len - (dst_ofs / 8 + 1);
1100 unsigned int chunk = MIN(n_bits, 8 - dst_ofs);
1102 *dst |= ((1 << chunk) - 1) << dst_ofs;
1112 while (n_bits >= 8) {
1118 *dst |= (1 << n_bits) - 1;
1122 /* Scans the 'n_bits' bits starting from bit 'dst_ofs' in 'dst' for 1-bits.
1123 * Returns false if any 1-bits are found, otherwise true. 'dst' is 'dst_len'
1126 * If you consider all of 'dst' to be a single unsigned integer in network byte
1127 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1128 * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
1129 * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
1132 * Required invariant:
1133 * dst_ofs + n_bits <= dst_len * 8
1136 bitwise_is_all_zeros(const void *p_, unsigned int len, unsigned int ofs,
1137 unsigned int n_bits)
1139 const uint8_t *p = p_;
1145 p += len - (ofs / 8 + 1);
1149 unsigned int chunk = MIN(n_bits, 8 - ofs);
1151 if (*p & (((1 << chunk) - 1) << ofs)) {
1163 while (n_bits >= 8) {
1171 if (n_bits && *p & ((1 << n_bits) - 1)) {
1178 /* Copies the 'n_bits' low-order bits of 'value' into the 'n_bits' bits
1179 * starting at bit 'dst_ofs' in 'dst', which is 'dst_len' bytes long.
1181 * If you consider all of 'dst' to be a single unsigned integer in network byte
1182 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1183 * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
1184 * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
1187 * Required invariants:
1188 * dst_ofs + n_bits <= dst_len * 8
1192 bitwise_put(uint64_t value,
1193 void *dst, unsigned int dst_len, unsigned int dst_ofs,
1194 unsigned int n_bits)
1196 ovs_be64 n_value = htonll(value);
1197 bitwise_copy(&n_value, sizeof n_value, 0,
1198 dst, dst_len, dst_ofs,
1202 /* Returns the value of the 'n_bits' bits starting at bit 'src_ofs' in 'src',
1203 * which is 'src_len' bytes long.
1205 * If you consider all of 'src' to be a single unsigned integer in network byte
1206 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1207 * with value 1 in src[src_len - 1], bit 1 is the bit with value 2, bit 2 is
1208 * the bit with value 4, ..., bit 8 is the bit with value 1 in src[src_len -
1211 * Required invariants:
1212 * src_ofs + n_bits <= src_len * 8
1216 bitwise_get(const void *src, unsigned int src_len,
1217 unsigned int src_ofs, unsigned int n_bits)
1219 ovs_be64 value = htonll(0);
1221 bitwise_copy(src, src_len, src_ofs,
1222 &value, sizeof value, 0,
1224 return ntohll(value);
1245 skip_spaces(const char *s)
1247 while (isspace((unsigned char) *s)) {
1254 scan_int(const char *s, const struct scan_spec *spec, int base, va_list *args)
1256 const char *start = s;
1261 negative = *s == '-';
1262 s += *s == '-' || *s == '+';
1264 if ((!base || base == 16) && *s == '0' && (s[1] == 'x' || s[1] == 'X')) {
1268 base = *s == '0' ? 8 : 10;
1271 if (s - start >= spec->width) {
1277 while (s - start < spec->width) {
1278 int digit = hexit_value(*s);
1280 if (digit < 0 || digit >= base) {
1283 value = value * base + digit;
1295 switch (spec->type) {
1299 *va_arg(*args, char *) = value;
1302 *va_arg(*args, short int *) = value;
1305 *va_arg(*args, int *) = value;
1308 *va_arg(*args, long int *) = value;
1311 *va_arg(*args, long long int *) = value;
1314 *va_arg(*args, intmax_t *) = value;
1316 case SCAN_PTRDIFF_T:
1317 *va_arg(*args, ptrdiff_t *) = value;
1320 *va_arg(*args, size_t *) = value;
1327 skip_digits(const char *s)
1329 while (*s >= '0' && *s <= '9') {
1336 scan_float(const char *s, const struct scan_spec *spec, va_list *args)
1338 const char *start = s;
1344 s += *s == '+' || *s == '-';
1347 s = skip_digits(s + 1);
1349 if (*s == 'e' || *s == 'E') {
1351 s += *s == '+' || *s == '-';
1355 if (s - start > spec->width) {
1356 s = start + spec->width;
1359 copy = xmemdup0(start, s - start);
1360 value = strtold(copy, &tail);
1367 switch (spec->type) {
1371 *va_arg(*args, float *) = value;
1374 *va_arg(*args, double *) = value;
1377 *va_arg(*args, long double *) = value;
1383 case SCAN_PTRDIFF_T:
1391 scan_output_string(const struct scan_spec *spec,
1392 const char *s, size_t n,
1395 if (spec->type != SCAN_DISCARD) {
1396 char *out = va_arg(*args, char *);
1403 scan_string(const char *s, const struct scan_spec *spec, va_list *args)
1407 for (n = 0; n < spec->width; n++) {
1408 if (!s[n] || isspace((unsigned char) s[n])) {
1416 scan_output_string(spec, s, n, args);
1421 parse_scanset(const char *p_, unsigned long *set, bool *complemented)
1423 const uint8_t *p = (const uint8_t *) p_;
1425 *complemented = *p == '^';
1429 bitmap_set1(set, ']');
1433 while (*p && *p != ']') {
1434 if (p[1] == '-' && p[2] != ']' && p[2] > *p) {
1435 bitmap_set_multiple(set, *p, p[2] - *p + 1, true);
1438 bitmap_set1(set, *p++);
1444 return (const char *) p;
1448 scan_set(const char *s, const struct scan_spec *spec, const char **pp,
1451 unsigned long set[BITMAP_N_LONGS(UCHAR_MAX + 1)];
1455 /* Parse the scan set. */
1456 memset(set, 0, sizeof set);
1457 *pp = parse_scanset(*pp, set, &complemented);
1459 /* Parse the data. */
1462 && bitmap_is_set(set, (unsigned char) s[n]) == !complemented
1463 && n < spec->width) {
1469 scan_output_string(spec, s, n, args);
1474 scan_chars(const char *s, const struct scan_spec *spec, va_list *args)
1476 unsigned int n = spec->width == UINT_MAX ? 1 : spec->width;
1478 if (strlen(s) < n) {
1481 if (spec->type != SCAN_DISCARD) {
1482 memcpy(va_arg(*args, char *), s, n);
1487 /* This is an implementation of the standard sscanf() function, with the
1488 * following exceptions:
1490 * - It returns true if the entire format was successfully scanned and
1491 * converted, false if any conversion failed.
1493 * - The standard doesn't define sscanf() behavior when an out-of-range value
1494 * is scanned, e.g. if a "%"PRIi8 conversion scans "-1" or "0x1ff". Some
1495 * implementations consider this an error and stop scanning. This
1496 * implementation never considers an out-of-range value an error; instead,
1497 * it stores the least-significant bits of the converted value in the
1498 * destination, e.g. the value 255 for both examples earlier.
1500 * - Only single-byte characters are supported, that is, the 'l' modifier
1501 * on %s, %[, and %c is not supported. The GNU extension 'a' modifier is
1502 * also not supported.
1504 * - %p is not supported.
1507 ovs_scan(const char *s, const char *format, ...)
1509 const char *const start = s;
1514 va_start(args, format);
1516 while (*p != '\0') {
1517 struct scan_spec spec;
1518 unsigned char c = *p++;
1524 } else if (c != '%') {
1530 } else if (*p == '%') {
1538 /* Parse '*' flag. */
1539 discard = *p == '*';
1542 /* Parse field width. */
1544 while (*p >= '0' && *p <= '9') {
1545 spec.width = spec.width * 10 + (*p++ - '0');
1547 if (spec.width == 0) {
1548 spec.width = UINT_MAX;
1551 /* Parse type modifier. */
1555 spec.type = SCAN_CHAR;
1558 spec.type = SCAN_SHORT;
1564 spec.type = SCAN_INTMAX_T;
1570 spec.type = SCAN_LLONG;
1573 spec.type = SCAN_LONG;
1580 spec.type = SCAN_LLONG;
1585 spec.type = SCAN_PTRDIFF_T;
1590 spec.type = SCAN_SIZE_T;
1595 spec.type = SCAN_INT;
1600 spec.type = SCAN_DISCARD;
1604 if (c != 'c' && c != 'n' && c != '[') {
1609 s = scan_int(s, &spec, 10, &args);
1613 s = scan_int(s, &spec, 0, &args);
1617 s = scan_int(s, &spec, 8, &args);
1621 s = scan_int(s, &spec, 10, &args);
1626 s = scan_int(s, &spec, 16, &args);
1634 s = scan_float(s, &spec, &args);
1638 s = scan_string(s, &spec, &args);
1642 s = scan_set(s, &spec, &p, &args);
1646 s = scan_chars(s, &spec, &args);
1650 if (spec.type != SCAN_DISCARD) {
1651 *va_arg(args, int *) = s - start;
1670 ovs_format_message(int error)
1672 enum { BUFSIZE = sizeof strerror_buffer_get()->s };
1673 char *buffer = strerror_buffer_get()->s;
1675 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
1676 NULL, error, 0, buffer, BUFSIZE, NULL);
1680 /* Returns a null-terminated string that explains the last error.
1681 * Use this function to get the error string for WINAPI calls. */
1683 ovs_lasterror_to_string(void)
1685 return ovs_format_message(GetLastError());