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(). */
54 DEFINE_STATIC_PER_THREAD_DATA(struct { char s[128]; },
59 ovs_assert_failure(const char *where, const char *function,
60 const char *condition)
62 /* Prevent an infinite loop (or stack overflow) in case VLOG_ABORT happens
63 * to trigger an assertion failure of its own. */
64 static int reentry = 0;
68 VLOG_ABORT("%s: assertion %s failed in %s()",
69 where, condition, function);
73 fprintf(stderr, "%s: assertion %s failed in %s()",
74 where, condition, function);
85 ovs_abort(0, "virtual memory exhausted");
89 xcalloc(size_t count, size_t size)
91 void *p = count && size ? calloc(count, size) : malloc(1);
92 COVERAGE_INC(util_xalloc);
102 return xcalloc(1, size);
108 void *p = malloc(size ? size : 1);
109 COVERAGE_INC(util_xalloc);
117 xrealloc(void *p, size_t size)
119 p = realloc(p, size ? size : 1);
120 COVERAGE_INC(util_xalloc);
128 xmemdup(const void *p_, size_t size)
130 void *p = xmalloc(size);
136 xmemdup0(const char *p_, size_t length)
138 char *p = xmalloc(length + 1);
139 memcpy(p, p_, length);
145 xstrdup(const char *s)
147 return xmemdup0(s, strlen(s));
151 xvasprintf(const char *format, va_list args)
157 va_copy(args2, args);
158 needed = vsnprintf(NULL, 0, format, args);
160 s = xmalloc(needed + 1);
162 vsnprintf(s, needed + 1, format, args2);
169 x2nrealloc(void *p, size_t *n, size_t s)
171 *n = *n == 0 ? 1 : 2 * *n;
172 return xrealloc(p, *n * s);
176 xasprintf(const char *format, ...)
181 va_start(args, format);
182 s = xvasprintf(format, args);
188 /* Similar to strlcpy() from OpenBSD, but it never reads more than 'size - 1'
189 * bytes from 'src' and doesn't return anything. */
191 ovs_strlcpy(char *dst, const char *src, size_t size)
194 size_t len = strnlen(src, size - 1);
195 memcpy(dst, src, len);
200 /* Copies 'src' to 'dst'. Reads no more than 'size - 1' bytes from 'src'.
201 * Always null-terminates 'dst' (if 'size' is nonzero), and writes a zero byte
202 * to every otherwise unused byte in 'dst'.
204 * Except for performance, the following call:
205 * ovs_strzcpy(dst, src, size);
206 * is equivalent to these two calls:
207 * memset(dst, '\0', size);
208 * ovs_strlcpy(dst, src, size);
210 * (Thus, ovs_strzcpy() is similar to strncpy() without some of the pitfalls.)
213 ovs_strzcpy(char *dst, const char *src, size_t size)
216 size_t len = strnlen(src, size - 1);
217 memcpy(dst, src, len);
218 memset(dst + len, '\0', size - len);
222 /* Prints 'format' on stderr, formatting it like printf() does. If 'err_no' is
223 * nonzero, then it is formatted with ovs_retval_to_string() and appended to
224 * the message inside parentheses. Then, terminates with abort().
226 * This function is preferred to ovs_fatal() in a situation where it would make
227 * sense for a monitoring process to restart the daemon.
229 * 'format' should not end with a new-line, because this function will add one
232 ovs_abort(int err_no, const char *format, ...)
236 va_start(args, format);
237 ovs_abort_valist(err_no, format, args);
240 /* Same as ovs_abort() except that the arguments are supplied as a va_list. */
242 ovs_abort_valist(int err_no, const char *format, va_list args)
244 ovs_error_valist(err_no, format, args);
248 /* Prints 'format' on stderr, formatting it like printf() does. If 'err_no' is
249 * nonzero, then it is formatted with ovs_retval_to_string() and appended to
250 * the message inside parentheses. Then, terminates with EXIT_FAILURE.
252 * 'format' should not end with a new-line, because this function will add one
255 ovs_fatal(int err_no, const char *format, ...)
259 va_start(args, format);
260 ovs_fatal_valist(err_no, format, args);
263 /* Same as ovs_fatal() except that the arguments are supplied as a va_list. */
265 ovs_fatal_valist(int err_no, const char *format, va_list args)
267 ovs_error_valist(err_no, format, args);
271 /* Prints 'format' on stderr, formatting it like printf() does. If 'err_no' is
272 * nonzero, then it is formatted with ovs_retval_to_string() and appended to
273 * the message inside parentheses.
275 * 'format' should not end with a new-line, because this function will add one
278 ovs_error(int err_no, const char *format, ...)
282 va_start(args, format);
283 ovs_error_valist(err_no, format, args);
287 /* Same as ovs_error() except that the arguments are supplied as a va_list. */
289 ovs_error_valist(int err_no, const char *format, va_list args)
291 const char *subprogram_name = get_subprogram_name();
292 int save_errno = errno;
294 if (subprogram_name[0]) {
295 fprintf(stderr, "%s(%s): ", program_name, subprogram_name);
297 fprintf(stderr, "%s: ", program_name);
300 vfprintf(stderr, format, args);
302 fprintf(stderr, " (%s)", ovs_retval_to_string(err_no));
309 /* Many OVS functions return an int which is one of:
312 * - EOF: end of file (not necessarily an error; depends on the function called)
314 * Returns the appropriate human-readable string. The caller must copy the
315 * string if it wants to hold onto it, as the storage may be overwritten on
316 * subsequent function calls.
319 ovs_retval_to_string(int retval)
322 : retval == EOF ? "End of file"
323 : ovs_strerror(retval));
326 /* This function returns the string describing the error number in 'error'
327 * for POSIX platforms. For Windows, this function can be used for C library
328 * calls. For socket calls that are also used in Windows, use sock_strerror()
329 * instead. For WINAPI calls, look at ovs_lasterror_to_string(). */
331 ovs_strerror(int error)
333 enum { BUFSIZE = sizeof strerror_buffer_get()->s };
339 buffer = strerror_buffer_get()->s;
341 #if STRERROR_R_CHAR_P
342 /* GNU style strerror_r() might return an immutable static string, or it
343 * might write and return 'buffer', but in either case we can pass the
344 * returned string directly to the caller. */
345 s = strerror_r(error, buffer, BUFSIZE);
346 #else /* strerror_r() returns an int. */
348 if (strerror_r(error, buffer, BUFSIZE)) {
349 /* strerror_r() is only allowed to fail on ERANGE (because the buffer
350 * is too short). We don't check the actual failure reason because
351 * POSIX requires strerror_r() to return the error but old glibc
352 * (before 2.13) returns -1 and sets errno. */
353 snprintf(buffer, BUFSIZE, "Unknown error %d", error);
362 /* Sets global "program_name" and "program_version" variables. Should
363 * be called at the beginning of main() with "argv[0]" as the argument
366 * 'version' should contain the version of the caller's program. If 'version'
367 * is the same as the VERSION #define, the caller is assumed to be part of Open
368 * vSwitch. Otherwise, it is assumed to be an external program linking against
369 * the Open vSwitch libraries.
371 * The 'date' and 'time' arguments should likely be called with
372 * "__DATE__" and "__TIME__" to use the time the binary was built.
373 * Alternatively, the "set_program_name" macro may be called to do this
377 set_program_name__(const char *argv0, const char *version, const char *date,
382 size_t max_len = strlen(argv0) + 1;
387 basename = xmalloc(max_len);
388 _splitpath_s(argv0, NULL, 0, NULL, 0, basename, max_len, NULL, 0);
389 assert_single_threaded();
390 program_name = basename;
392 const char *slash = strrchr(argv0, '/');
393 assert_single_threaded();
394 program_name = slash ? slash + 1 : argv0;
397 free(program_version);
399 if (!strcmp(version, VERSION)) {
400 program_version = xasprintf("%s (Open vSwitch) "VERSION"\n"
402 program_name, date, time);
404 program_version = xasprintf("%s %s\n"
405 "Open vSwitch Library "VERSION"\n"
407 program_name, version, date, time);
411 /* Returns the name of the currently running thread or process. */
413 get_subprogram_name(void)
415 const char *name = subprogram_name_get();
416 return name ? name : "";
419 /* Sets the formatted value of 'format' as the name of the currently running
420 * thread or process. (This appears in log messages and may also be visible in
421 * system process listings and debuggers.) */
423 set_subprogram_name(const char *format, ...)
430 va_start(args, format);
431 pname = xvasprintf(format, args);
434 pname = xstrdup(program_name);
437 free(subprogram_name_set(pname));
439 #if HAVE_GLIBC_PTHREAD_SETNAME_NP
440 pthread_setname_np(pthread_self(), pname);
441 #elif HAVE_NETBSD_PTHREAD_SETNAME_NP
442 pthread_setname_np(pthread_self(), "%s", pname);
443 #elif HAVE_PTHREAD_SET_NAME_NP
444 pthread_set_name_np(pthread_self(), pname);
448 /* Returns a pointer to a string describing the program version. The
449 * caller must not modify or free the returned string.
452 get_program_version(void)
454 return program_version;
457 /* Print the version information for the program. */
459 ovs_print_version(uint8_t min_ofp, uint8_t max_ofp)
461 printf("%s", program_version);
462 if (min_ofp || max_ofp) {
463 printf("OpenFlow versions %#x:%#x\n", min_ofp, max_ofp);
467 /* Writes the 'size' bytes in 'buf' to 'stream' as hex bytes arranged 16 per
468 * line. Numeric offsets are also included, starting at 'ofs' for the first
469 * byte in 'buf'. If 'ascii' is true then the corresponding ASCII characters
470 * are also rendered alongside. */
472 ovs_hex_dump(FILE *stream, const void *buf_, size_t size,
473 uintptr_t ofs, bool ascii)
475 const uint8_t *buf = buf_;
476 const size_t per_line = 16; /* Maximum bytes per line. */
480 size_t start, end, n;
483 /* Number of bytes on this line. */
484 start = ofs % per_line;
486 if (end - start > size)
491 fprintf(stream, "%08"PRIxMAX" ", (uintmax_t) ROUND_DOWN(ofs, per_line));
492 for (i = 0; i < start; i++)
493 fprintf(stream, " ");
495 fprintf(stream, "%02x%c",
496 buf[i - start], i == per_line / 2 - 1? '-' : ' ');
499 for (; i < per_line; i++)
500 fprintf(stream, " ");
501 fprintf(stream, "|");
502 for (i = 0; i < start; i++)
503 fprintf(stream, " ");
504 for (; i < end; i++) {
505 int c = buf[i - start];
506 putc(c >= 32 && c < 127 ? c : '.', stream);
508 for (; i < per_line; i++)
509 fprintf(stream, " ");
510 fprintf(stream, "|");
512 fprintf(stream, "\n");
521 str_to_int(const char *s, int base, int *i)
524 bool ok = str_to_llong(s, base, &ll);
530 str_to_long(const char *s, int base, long *li)
533 bool ok = str_to_llong(s, base, &ll);
539 str_to_llong(const char *s, int base, long long *x)
541 int save_errno = errno;
544 *x = strtoll(s, &tail, base);
545 if (errno == EINVAL || errno == ERANGE || tail == s || *tail != '\0') {
555 /* Converts floating-point string 's' into a double. If successful, stores
556 * the double in '*d' and returns true; on failure, stores 0 in '*d' and
559 * Underflow (e.g. "1e-9999") is not considered an error, but overflow
560 * (e.g. "1e9999)" is. */
562 str_to_double(const char *s, double *d)
564 int save_errno = errno;
567 *d = strtod(s, &tail);
568 if (errno == EINVAL || (errno == ERANGE && *d != 0)
569 || tail == s || *tail != '\0') {
579 /* Returns the value of 'c' as a hexadecimal digit. */
584 case '0': case '1': case '2': case '3': case '4':
585 case '5': case '6': case '7': case '8': case '9':
611 /* Returns the integer value of the 'n' hexadecimal digits starting at 's', or
612 * UINT_MAX if one of those "digits" is not really a hex digit. If 'ok' is
613 * nonnull, '*ok' is set to true if the conversion succeeds or to false if a
614 * non-hex digit is detected. */
616 hexits_value(const char *s, size_t n, bool *ok)
622 for (i = 0; i < n; i++) {
623 int hexit = hexit_value(s[i]);
630 value = (value << 4) + hexit;
638 /* Returns the current working directory as a malloc()'d string, or a null
639 * pointer if the current working directory cannot be determined. */
646 /* Get maximum path length or at least a reasonable estimate. */
647 path_max = pathconf(".", _PC_PATH_MAX);
648 size = (path_max < 0 ? 1024
649 : path_max > 10240 ? 10240
652 /* Get current working directory. */
654 char *buf = xmalloc(size);
655 if (getcwd(buf, size)) {
656 return xrealloc(buf, strlen(buf) + 1);
660 if (error != ERANGE) {
661 VLOG_WARN("getcwd failed (%s)", ovs_strerror(error));
670 all_slashes_name(const char *s)
672 return xstrdup(s[0] == '/' && s[1] == '/' && s[2] != '/' ? "//"
677 /* Returns the directory name portion of 'file_name' as a malloc()'d string,
678 * similar to the POSIX dirname() function but thread-safe. */
680 dir_name(const char *file_name)
682 size_t len = strlen(file_name);
683 while (len > 0 && file_name[len - 1] == '/') {
686 while (len > 0 && file_name[len - 1] != '/') {
689 while (len > 0 && file_name[len - 1] == '/') {
692 return len ? xmemdup0(file_name, len) : all_slashes_name(file_name);
695 /* Returns the file name portion of 'file_name' as a malloc()'d string,
696 * similar to the POSIX basename() function but thread-safe. */
698 base_name(const char *file_name)
702 end = strlen(file_name);
703 while (end > 0 && file_name[end - 1] == '/') {
708 return all_slashes_name(file_name);
712 while (start > 0 && file_name[start - 1] != '/') {
716 return xmemdup0(file_name + start, end - start);
719 /* If 'file_name' starts with '/', returns a copy of 'file_name'. Otherwise,
720 * returns an absolute path to 'file_name' considering it relative to 'dir',
721 * which itself must be absolute. 'dir' may be null or the empty string, in
722 * which case the current working directory is used.
724 * Returns a null pointer if 'dir' is null and getcwd() fails. */
726 abs_file_name(const char *dir, const char *file_name)
728 if (file_name[0] == '/') {
729 return xstrdup(file_name);
730 } else if (dir && dir[0]) {
731 char *separator = dir[strlen(dir) - 1] == '/' ? "" : "/";
732 return xasprintf("%s%s%s", dir, separator, file_name);
734 char *cwd = get_cwd();
736 char *abs_name = xasprintf("%s/%s", cwd, file_name);
745 /* Like readlink(), but returns the link name as a null-terminated string in
746 * allocated memory that the caller must eventually free (with free()).
747 * Returns NULL on error, in which case errno is set appropriately. */
749 xreadlink(const char *filename)
753 for (size = 64; ; size *= 2) {
754 char *buf = xmalloc(size);
755 ssize_t retval = readlink(filename, buf, size);
758 if (retval >= 0 && retval < size) {
771 /* Returns a version of 'filename' with symlinks in the final component
772 * dereferenced. This differs from realpath() in that:
774 * - 'filename' need not exist.
776 * - If 'filename' does exist as a symlink, its referent need not exist.
778 * - Only symlinks in the final component of 'filename' are dereferenced.
780 * The caller must eventually free the returned string (with free()). */
782 follow_symlinks(const char *filename)
788 fn = xstrdup(filename);
789 for (i = 0; i < 10; i++) {
793 if (lstat(fn, &s) != 0 || !S_ISLNK(s.st_mode)) {
797 linkname = xreadlink(fn);
799 VLOG_WARN("%s: readlink failed (%s)",
800 filename, ovs_strerror(errno));
804 if (linkname[0] == '/') {
805 /* Target of symlink is absolute so use it raw. */
808 /* Target of symlink is relative so add to 'fn''s directory. */
809 char *dir = dir_name(fn);
811 if (!strcmp(dir, ".")) {
814 char *separator = dir[strlen(dir) - 1] == '/' ? "" : "/";
815 next_fn = xasprintf("%s%s%s", dir, separator, linkname);
826 VLOG_WARN("%s: too many levels of symlinks", filename);
828 return xstrdup(filename);
831 /* Pass a value to this function if it is marked with
832 * __attribute__((warn_unused_result)) and you genuinely want to ignore
833 * its return value. (Note that every scalar type can be implicitly
834 * converted to bool.) */
835 void ignore(bool x OVS_UNUSED) { }
837 /* Returns an appropriate delimiter for inserting just before the 0-based item
838 * 'index' in a list that has 'total' items in it. */
840 english_list_delimiter(size_t index, size_t total)
842 return (index == 0 ? ""
843 : index < total - 1 ? ", "
844 : total > 2 ? ", and "
848 /* Returns the number of trailing 0-bits in 'n'. Undefined if 'n' == 0. */
850 /* Defined inline in util.h. */
852 /* Returns the number of trailing 0-bits in 'n'. Undefined if 'n' == 0. */
859 #define CTZ_STEP(X) \
876 /* Returns the number of leading 0-bits in 'n'. Undefined if 'n' == 0. */
878 raw_clz64(uint64_t n)
883 #define CLZ_STEP(X) \
901 #if NEED_COUNT_1BITS_8
903 ((((X) & (1 << 0)) != 0) + \
904 (((X) & (1 << 1)) != 0) + \
905 (((X) & (1 << 2)) != 0) + \
906 (((X) & (1 << 3)) != 0) + \
907 (((X) & (1 << 4)) != 0) + \
908 (((X) & (1 << 5)) != 0) + \
909 (((X) & (1 << 6)) != 0) + \
910 (((X) & (1 << 7)) != 0))
911 #define INIT2(X) INIT1(X), INIT1((X) + 1)
912 #define INIT4(X) INIT2(X), INIT2((X) + 2)
913 #define INIT8(X) INIT4(X), INIT4((X) + 4)
914 #define INIT16(X) INIT8(X), INIT8((X) + 8)
915 #define INIT32(X) INIT16(X), INIT16((X) + 16)
916 #define INIT64(X) INIT32(X), INIT32((X) + 32)
918 const uint8_t count_1bits_8[256] = {
919 INIT64(0), INIT64(64), INIT64(128), INIT64(192)
923 /* Returns true if the 'n' bytes starting at 'p' are zeros. */
925 is_all_zeros(const uint8_t *p, size_t n)
929 for (i = 0; i < n; i++) {
937 /* Returns true if the 'n' bytes starting at 'p' are 0xff. */
939 is_all_ones(const uint8_t *p, size_t n)
943 for (i = 0; i < n; i++) {
951 /* Copies 'n_bits' bits starting from bit 'src_ofs' in 'src' to the 'n_bits'
952 * starting from bit 'dst_ofs' in 'dst'. 'src' is 'src_len' bytes long and
953 * 'dst' is 'dst_len' bytes long.
955 * If you consider all of 'src' to be a single unsigned integer in network byte
956 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
957 * with value 1 in src[src_len - 1], bit 1 is the bit with value 2, bit 2 is
958 * the bit with value 4, ..., bit 8 is the bit with value 1 in src[src_len -
959 * 2], and so on. Similarly for 'dst'.
961 * Required invariants:
962 * src_ofs + n_bits <= src_len * 8
963 * dst_ofs + n_bits <= dst_len * 8
964 * 'src' and 'dst' must not overlap.
967 bitwise_copy(const void *src_, unsigned int src_len, unsigned int src_ofs,
968 void *dst_, unsigned int dst_len, unsigned int dst_ofs,
971 const uint8_t *src = src_;
974 src += src_len - (src_ofs / 8 + 1);
977 dst += dst_len - (dst_ofs / 8 + 1);
980 if (src_ofs == 0 && dst_ofs == 0) {
981 unsigned int n_bytes = n_bits / 8;
985 memcpy(dst, src, n_bytes);
992 uint8_t mask = (1 << n_bits) - 1;
993 *dst = (*dst & ~mask) | (*src & mask);
997 unsigned int max_copy = 8 - MAX(src_ofs, dst_ofs);
998 unsigned int chunk = MIN(n_bits, max_copy);
999 uint8_t mask = ((1 << chunk) - 1) << dst_ofs;
1002 *dst |= ((*src >> src_ofs) << dst_ofs) & mask;
1019 /* Zeros the 'n_bits' bits starting from bit 'dst_ofs' in 'dst'. 'dst' is
1020 * 'dst_len' bytes long.
1022 * If you consider all of 'dst' to be a single unsigned integer in network byte
1023 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1024 * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
1025 * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
1028 * Required invariant:
1029 * dst_ofs + n_bits <= dst_len * 8
1032 bitwise_zero(void *dst_, unsigned int dst_len, unsigned dst_ofs,
1033 unsigned int n_bits)
1035 uint8_t *dst = dst_;
1041 dst += dst_len - (dst_ofs / 8 + 1);
1045 unsigned int chunk = MIN(n_bits, 8 - dst_ofs);
1047 *dst &= ~(((1 << chunk) - 1) << dst_ofs);
1057 while (n_bits >= 8) {
1063 *dst &= ~((1 << n_bits) - 1);
1067 /* Sets to 1 all of the 'n_bits' bits starting from bit 'dst_ofs' in 'dst'.
1068 * 'dst' is 'dst_len' bytes long.
1070 * If you consider all of 'dst' to be a single unsigned integer in network byte
1071 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1072 * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
1073 * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
1076 * Required invariant:
1077 * dst_ofs + n_bits <= dst_len * 8
1080 bitwise_one(void *dst_, unsigned int dst_len, unsigned dst_ofs,
1081 unsigned int n_bits)
1083 uint8_t *dst = dst_;
1089 dst += dst_len - (dst_ofs / 8 + 1);
1093 unsigned int chunk = MIN(n_bits, 8 - dst_ofs);
1095 *dst |= ((1 << chunk) - 1) << dst_ofs;
1105 while (n_bits >= 8) {
1111 *dst |= (1 << n_bits) - 1;
1115 /* Scans the 'n_bits' bits starting from bit 'dst_ofs' in 'dst' for 1-bits.
1116 * Returns false if any 1-bits are found, otherwise true. 'dst' is 'dst_len'
1119 * If you consider all of 'dst' to be a single unsigned integer in network byte
1120 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1121 * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
1122 * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
1125 * Required invariant:
1126 * dst_ofs + n_bits <= dst_len * 8
1129 bitwise_is_all_zeros(const void *p_, unsigned int len, unsigned int ofs,
1130 unsigned int n_bits)
1132 const uint8_t *p = p_;
1138 p += len - (ofs / 8 + 1);
1142 unsigned int chunk = MIN(n_bits, 8 - ofs);
1144 if (*p & (((1 << chunk) - 1) << ofs)) {
1156 while (n_bits >= 8) {
1164 if (n_bits && *p & ((1 << n_bits) - 1)) {
1171 /* Copies the 'n_bits' low-order bits of 'value' into the 'n_bits' bits
1172 * starting at bit 'dst_ofs' in 'dst', which is 'dst_len' bytes long.
1174 * If you consider all of 'dst' to be a single unsigned integer in network byte
1175 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1176 * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
1177 * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
1180 * Required invariants:
1181 * dst_ofs + n_bits <= dst_len * 8
1185 bitwise_put(uint64_t value,
1186 void *dst, unsigned int dst_len, unsigned int dst_ofs,
1187 unsigned int n_bits)
1189 ovs_be64 n_value = htonll(value);
1190 bitwise_copy(&n_value, sizeof n_value, 0,
1191 dst, dst_len, dst_ofs,
1195 /* Returns the value of the 'n_bits' bits starting at bit 'src_ofs' in 'src',
1196 * which is 'src_len' bytes long.
1198 * If you consider all of 'src' to be a single unsigned integer in network byte
1199 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1200 * with value 1 in src[src_len - 1], bit 1 is the bit with value 2, bit 2 is
1201 * the bit with value 4, ..., bit 8 is the bit with value 1 in src[src_len -
1204 * Required invariants:
1205 * src_ofs + n_bits <= src_len * 8
1209 bitwise_get(const void *src, unsigned int src_len,
1210 unsigned int src_ofs, unsigned int n_bits)
1212 ovs_be64 value = htonll(0);
1214 bitwise_copy(src, src_len, src_ofs,
1215 &value, sizeof value, 0,
1217 return ntohll(value);
1238 skip_spaces(const char *s)
1240 while (isspace((unsigned char) *s)) {
1247 scan_int(const char *s, const struct scan_spec *spec, int base, va_list *args)
1249 const char *start = s;
1254 negative = *s == '-';
1255 s += *s == '-' || *s == '+';
1257 if ((!base || base == 16) && *s == '0' && (s[1] == 'x' || s[1] == 'X')) {
1261 base = *s == '0' ? 8 : 10;
1264 if (s - start >= spec->width) {
1270 while (s - start < spec->width) {
1271 int digit = hexit_value(*s);
1273 if (digit < 0 || digit >= base) {
1276 value = value * base + digit;
1288 switch (spec->type) {
1292 *va_arg(*args, char *) = value;
1295 *va_arg(*args, short int *) = value;
1298 *va_arg(*args, int *) = value;
1301 *va_arg(*args, long int *) = value;
1304 *va_arg(*args, long long int *) = value;
1307 *va_arg(*args, intmax_t *) = value;
1309 case SCAN_PTRDIFF_T:
1310 *va_arg(*args, ptrdiff_t *) = value;
1313 *va_arg(*args, size_t *) = value;
1320 skip_digits(const char *s)
1322 while (*s >= '0' && *s <= '9') {
1329 scan_float(const char *s, const struct scan_spec *spec, va_list *args)
1331 const char *start = s;
1337 s += *s == '+' || *s == '-';
1340 s = skip_digits(s + 1);
1342 if (*s == 'e' || *s == 'E') {
1344 s += *s == '+' || *s == '-';
1348 if (s - start > spec->width) {
1349 s = start + spec->width;
1352 copy = xmemdup0(start, s - start);
1353 value = strtold(copy, &tail);
1360 switch (spec->type) {
1364 *va_arg(*args, float *) = value;
1367 *va_arg(*args, double *) = value;
1370 *va_arg(*args, long double *) = value;
1376 case SCAN_PTRDIFF_T:
1384 scan_output_string(const struct scan_spec *spec,
1385 const char *s, size_t n,
1388 if (spec->type != SCAN_DISCARD) {
1389 char *out = va_arg(*args, char *);
1396 scan_string(const char *s, const struct scan_spec *spec, va_list *args)
1400 for (n = 0; n < spec->width; n++) {
1401 if (!s[n] || isspace((unsigned char) s[n])) {
1409 scan_output_string(spec, s, n, args);
1414 parse_scanset(const char *p_, unsigned long *set, bool *complemented)
1416 const uint8_t *p = (const uint8_t *) p_;
1418 *complemented = *p == '^';
1422 bitmap_set1(set, ']');
1426 while (*p && *p != ']') {
1427 if (p[1] == '-' && p[2] != ']' && p[2] > *p) {
1428 bitmap_set_multiple(set, *p, p[2] - *p + 1, true);
1431 bitmap_set1(set, *p++);
1437 return (const char *) p;
1441 scan_set(const char *s, const struct scan_spec *spec, const char **pp,
1444 unsigned long set[BITMAP_N_LONGS(UCHAR_MAX + 1)];
1448 /* Parse the scan set. */
1449 memset(set, 0, sizeof set);
1450 *pp = parse_scanset(*pp, set, &complemented);
1452 /* Parse the data. */
1455 && bitmap_is_set(set, (unsigned char) s[n]) == !complemented
1456 && n < spec->width) {
1462 scan_output_string(spec, s, n, args);
1467 scan_chars(const char *s, const struct scan_spec *spec, va_list *args)
1469 unsigned int n = spec->width == UINT_MAX ? 1 : spec->width;
1471 if (strlen(s) < n) {
1474 if (spec->type != SCAN_DISCARD) {
1475 memcpy(va_arg(*args, char *), s, n);
1480 /* This is an implementation of the standard sscanf() function, with the
1481 * following exceptions:
1483 * - It returns true if the entire format was successfully scanned and
1484 * converted, false if any conversion failed.
1486 * - The standard doesn't define sscanf() behavior when an out-of-range value
1487 * is scanned, e.g. if a "%"PRIi8 conversion scans "-1" or "0x1ff". Some
1488 * implementations consider this an error and stop scanning. This
1489 * implementation never considers an out-of-range value an error; instead,
1490 * it stores the least-significant bits of the converted value in the
1491 * destination, e.g. the value 255 for both examples earlier.
1493 * - Only single-byte characters are supported, that is, the 'l' modifier
1494 * on %s, %[, and %c is not supported. The GNU extension 'a' modifier is
1495 * also not supported.
1497 * - %p is not supported.
1500 ovs_scan(const char *s, const char *format, ...)
1502 const char *const start = s;
1507 va_start(args, format);
1509 while (*p != '\0') {
1510 struct scan_spec spec;
1511 unsigned char c = *p++;
1517 } else if (c != '%') {
1523 } else if (*p == '%') {
1531 /* Parse '*' flag. */
1532 discard = *p == '*';
1535 /* Parse field width. */
1537 while (*p >= '0' && *p <= '9') {
1538 spec.width = spec.width * 10 + (*p++ - '0');
1540 if (spec.width == 0) {
1541 spec.width = UINT_MAX;
1544 /* Parse type modifier. */
1548 spec.type = SCAN_CHAR;
1551 spec.type = SCAN_SHORT;
1557 spec.type = SCAN_INTMAX_T;
1563 spec.type = SCAN_LLONG;
1566 spec.type = SCAN_LONG;
1573 spec.type = SCAN_LLONG;
1578 spec.type = SCAN_PTRDIFF_T;
1583 spec.type = SCAN_SIZE_T;
1588 spec.type = SCAN_INT;
1593 spec.type = SCAN_DISCARD;
1597 if (c != 'c' && c != 'n' && c != '[') {
1602 s = scan_int(s, &spec, 10, &args);
1606 s = scan_int(s, &spec, 0, &args);
1610 s = scan_int(s, &spec, 8, &args);
1614 s = scan_int(s, &spec, 10, &args);
1619 s = scan_int(s, &spec, 16, &args);
1627 s = scan_float(s, &spec, &args);
1631 s = scan_string(s, &spec, &args);
1635 s = scan_set(s, &spec, &p, &args);
1639 s = scan_chars(s, &spec, &args);
1643 if (spec.type != SCAN_DISCARD) {
1644 *va_arg(args, int *) = s - start;
1662 /* Calls FormatMessage() with GetLastError() as an argument. Returns
1663 * pointer to a buffer that receives the null-terminated string that specifies
1664 * the formatted message and that has to be freed by the caller with
1667 ovs_lasterror_to_string(void)
1670 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
1671 | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), 0,
1672 (char *)&buffer, 0, NULL);