2 * Copyright (c) 2008, 2009, 2010, 2011, 2012 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.
28 #include "byte-order.h"
30 #include "openvswitch/types.h"
33 VLOG_DEFINE_THIS_MODULE(util);
35 COVERAGE_DEFINE(util_xalloc);
37 /* argv[0] without directory names. */
38 const char *program_name;
40 /* Ordinarily "" but set to "monitor" for a monitor process or "worker" for a
42 const char *subprogram_name = "";
44 /* --version option output. */
45 static char *program_version;
50 ovs_abort(0, "virtual memory exhausted");
54 xcalloc(size_t count, size_t size)
56 void *p = count && size ? calloc(count, size) : malloc(1);
57 COVERAGE_INC(util_xalloc);
67 return xcalloc(1, size);
73 void *p = malloc(size ? size : 1);
74 COVERAGE_INC(util_xalloc);
82 xrealloc(void *p, size_t size)
84 p = realloc(p, size ? size : 1);
85 COVERAGE_INC(util_xalloc);
93 xmemdup(const void *p_, size_t size)
95 void *p = xmalloc(size);
101 xmemdup0(const char *p_, size_t length)
103 char *p = xmalloc(length + 1);
104 memcpy(p, p_, length);
110 xstrdup(const char *s)
112 return xmemdup0(s, strlen(s));
116 xvasprintf(const char *format, va_list args)
122 va_copy(args2, args);
123 needed = vsnprintf(NULL, 0, format, args);
125 s = xmalloc(needed + 1);
127 vsnprintf(s, needed + 1, format, args2);
134 x2nrealloc(void *p, size_t *n, size_t s)
136 *n = *n == 0 ? 1 : 2 * *n;
137 return xrealloc(p, *n * s);
141 xasprintf(const char *format, ...)
146 va_start(args, format);
147 s = xvasprintf(format, args);
153 /* Similar to strlcpy() from OpenBSD, but it never reads more than 'size - 1'
154 * bytes from 'src' and doesn't return anything. */
156 ovs_strlcpy(char *dst, const char *src, size_t size)
159 size_t len = strnlen(src, size - 1);
160 memcpy(dst, src, len);
165 /* Copies 'src' to 'dst'. Reads no more than 'size - 1' bytes from 'src'.
166 * Always null-terminates 'dst' (if 'size' is nonzero), and writes a zero byte
167 * to every otherwise unused byte in 'dst'.
169 * Except for performance, the following call:
170 * ovs_strzcpy(dst, src, size);
171 * is equivalent to these two calls:
172 * memset(dst, '\0', size);
173 * ovs_strlcpy(dst, src, size);
175 * (Thus, ovs_strzcpy() is similar to strncpy() without some of the pitfalls.)
178 ovs_strzcpy(char *dst, const char *src, size_t size)
181 size_t len = strnlen(src, size - 1);
182 memcpy(dst, src, len);
183 memset(dst + len, '\0', size - len);
187 /* Prints 'format' on stderr, formatting it like printf() does. If 'err_no' is
188 * nonzero, then it is formatted with ovs_retval_to_string() and appended to
189 * the message inside parentheses. Then, terminates with abort().
191 * This function is preferred to ovs_fatal() in a situation where it would make
192 * sense for a monitoring process to restart the daemon.
194 * 'format' should not end with a new-line, because this function will add one
197 ovs_abort(int err_no, const char *format, ...)
201 va_start(args, format);
202 ovs_abort_valist(err_no, format, args);
205 /* Same as ovs_abort() except that the arguments are supplied as a va_list. */
207 ovs_abort_valist(int err_no, const char *format, va_list args)
209 ovs_error_valist(err_no, format, args);
213 /* Prints 'format' on stderr, formatting it like printf() does. If 'err_no' is
214 * nonzero, then it is formatted with ovs_retval_to_string() and appended to
215 * the message inside parentheses. Then, terminates with EXIT_FAILURE.
217 * 'format' should not end with a new-line, because this function will add one
220 ovs_fatal(int err_no, const char *format, ...)
224 va_start(args, format);
225 ovs_fatal_valist(err_no, format, args);
228 /* Same as ovs_fatal() except that the arguments are supplied as a va_list. */
230 ovs_fatal_valist(int err_no, const char *format, va_list args)
232 ovs_error_valist(err_no, format, args);
236 /* Prints 'format' on stderr, formatting it like printf() does. If 'err_no' is
237 * nonzero, then it is formatted with ovs_retval_to_string() and appended to
238 * the message inside parentheses.
240 * 'format' should not end with a new-line, because this function will add one
243 ovs_error(int err_no, const char *format, ...)
247 va_start(args, format);
248 ovs_error_valist(err_no, format, args);
252 /* Same as ovs_error() except that the arguments are supplied as a va_list. */
254 ovs_error_valist(int err_no, const char *format, va_list args)
256 int save_errno = errno;
258 if (subprogram_name[0]) {
259 fprintf(stderr, "%s(%s): ", program_name, subprogram_name);
261 fprintf(stderr, "%s: ", program_name);
264 vfprintf(stderr, format, args);
266 fprintf(stderr, " (%s)", ovs_retval_to_string(err_no));
273 /* Many OVS functions return an int which is one of:
276 * - EOF: end of file (not necessarily an error; depends on the function called)
278 * Returns the appropriate human-readable string. The caller must copy the
279 * string if it wants to hold onto it, as the storage may be overwritten on
280 * subsequent function calls.
283 ovs_retval_to_string(int retval)
285 static char unknown[48];
291 return strerror(retval);
294 return "End of file";
296 snprintf(unknown, sizeof unknown, "***unknown return value: %d***", retval);
300 /* Sets global "program_name" and "program_version" variables. Should
301 * be called at the beginning of main() with "argv[0]" as the argument
304 * 'version' should contain the version of the caller's program. If 'version'
305 * is the same as the VERSION #define, the caller is assumed to be part of Open
306 * vSwitch. Otherwise, it is assumed to be an external program linking against
307 * the Open vSwitch libraries.
309 * The 'date' and 'time' arguments should likely be called with
310 * "__DATE__" and "__TIME__" to use the time the binary was built.
311 * Alternatively, the "set_program_name" macro may be called to do this
315 set_program_name__(const char *argv0, const char *version, const char *date,
318 const char *slash = strrchr(argv0, '/');
319 program_name = slash ? slash + 1 : argv0;
321 free(program_version);
323 if (!strcmp(version, VERSION)) {
324 program_version = xasprintf("%s (Open vSwitch) "VERSION"\n"
326 program_name, date, time);
328 program_version = xasprintf("%s %s\n"
329 "Open vSwitch Library "VERSION"\n"
331 program_name, version, date, time);
335 /* Returns a pointer to a string describing the program version. The
336 * caller must not modify or free the returned string.
339 get_program_version(void)
341 return program_version;
344 /* Print the version information for the program. */
346 ovs_print_version(uint8_t min_ofp, uint8_t max_ofp)
348 printf("%s", program_version);
349 if (min_ofp || max_ofp) {
350 printf("OpenFlow versions %#x:%#x\n", min_ofp, max_ofp);
354 /* Writes the 'size' bytes in 'buf' to 'stream' as hex bytes arranged 16 per
355 * line. Numeric offsets are also included, starting at 'ofs' for the first
356 * byte in 'buf'. If 'ascii' is true then the corresponding ASCII characters
357 * are also rendered alongside. */
359 ovs_hex_dump(FILE *stream, const void *buf_, size_t size,
360 uintptr_t ofs, bool ascii)
362 const uint8_t *buf = buf_;
363 const size_t per_line = 16; /* Maximum bytes per line. */
367 size_t start, end, n;
370 /* Number of bytes on this line. */
371 start = ofs % per_line;
373 if (end - start > size)
378 fprintf(stream, "%08jx ", (uintmax_t) ROUND_DOWN(ofs, per_line));
379 for (i = 0; i < start; i++)
380 fprintf(stream, " ");
382 fprintf(stream, "%02hhx%c",
383 buf[i - start], i == per_line / 2 - 1? '-' : ' ');
386 for (; i < per_line; i++)
387 fprintf(stream, " ");
388 fprintf(stream, "|");
389 for (i = 0; i < start; i++)
390 fprintf(stream, " ");
391 for (; i < end; i++) {
392 int c = buf[i - start];
393 putc(c >= 32 && c < 127 ? c : '.', stream);
395 for (; i < per_line; i++)
396 fprintf(stream, " ");
397 fprintf(stream, "|");
399 fprintf(stream, "\n");
408 str_to_int(const char *s, int base, int *i)
411 bool ok = str_to_llong(s, base, &ll);
417 str_to_long(const char *s, int base, long *li)
420 bool ok = str_to_llong(s, base, &ll);
426 str_to_llong(const char *s, int base, long long *x)
428 int save_errno = errno;
431 *x = strtoll(s, &tail, base);
432 if (errno == EINVAL || errno == ERANGE || tail == s || *tail != '\0') {
443 str_to_uint(const char *s, int base, unsigned int *u)
445 return str_to_int(s, base, (int *) u);
449 str_to_ulong(const char *s, int base, unsigned long *ul)
451 return str_to_long(s, base, (long *) ul);
455 str_to_ullong(const char *s, int base, unsigned long long *ull)
457 return str_to_llong(s, base, (long long *) ull);
460 /* Converts floating-point string 's' into a double. If successful, stores
461 * the double in '*d' and returns true; on failure, stores 0 in '*d' and
464 * Underflow (e.g. "1e-9999") is not considered an error, but overflow
465 * (e.g. "1e9999)" is. */
467 str_to_double(const char *s, double *d)
469 int save_errno = errno;
472 *d = strtod(s, &tail);
473 if (errno == EINVAL || (errno == ERANGE && *d != 0)
474 || tail == s || *tail != '\0') {
484 /* Returns the value of 'c' as a hexadecimal digit. */
489 case '0': case '1': case '2': case '3': case '4':
490 case '5': case '6': case '7': case '8': case '9':
516 /* Returns the integer value of the 'n' hexadecimal digits starting at 's', or
517 * UINT_MAX if one of those "digits" is not really a hex digit. If 'ok' is
518 * nonnull, '*ok' is set to true if the conversion succeeds or to false if a
519 * non-hex digit is detected. */
521 hexits_value(const char *s, size_t n, bool *ok)
527 for (i = 0; i < n; i++) {
528 int hexit = hexit_value(s[i]);
535 value = (value << 4) + hexit;
543 /* Returns the current working directory as a malloc()'d string, or a null
544 * pointer if the current working directory cannot be determined. */
551 /* Get maximum path length or at least a reasonable estimate. */
552 path_max = pathconf(".", _PC_PATH_MAX);
553 size = (path_max < 0 ? 1024
554 : path_max > 10240 ? 10240
557 /* Get current working directory. */
559 char *buf = xmalloc(size);
560 if (getcwd(buf, size)) {
561 return xrealloc(buf, strlen(buf) + 1);
565 if (error != ERANGE) {
566 VLOG_WARN("getcwd failed (%s)", strerror(error));
575 all_slashes_name(const char *s)
577 return xstrdup(s[0] == '/' && s[1] == '/' && s[2] != '/' ? "//"
582 /* Returns the directory name portion of 'file_name' as a malloc()'d string,
583 * similar to the POSIX dirname() function but thread-safe. */
585 dir_name(const char *file_name)
587 size_t len = strlen(file_name);
588 while (len > 0 && file_name[len - 1] == '/') {
591 while (len > 0 && file_name[len - 1] != '/') {
594 while (len > 0 && file_name[len - 1] == '/') {
597 return len ? xmemdup0(file_name, len) : all_slashes_name(file_name);
600 /* Returns the file name portion of 'file_name' as a malloc()'d string,
601 * similar to the POSIX basename() function but thread-safe. */
603 base_name(const char *file_name)
607 end = strlen(file_name);
608 while (end > 0 && file_name[end - 1] == '/') {
613 return all_slashes_name(file_name);
617 while (start > 0 && file_name[start - 1] != '/') {
621 return xmemdup0(file_name + start, end - start);
624 /* If 'file_name' starts with '/', returns a copy of 'file_name'. Otherwise,
625 * returns an absolute path to 'file_name' considering it relative to 'dir',
626 * which itself must be absolute. 'dir' may be null or the empty string, in
627 * which case the current working directory is used.
629 * Returns a null pointer if 'dir' is null and getcwd() fails. */
631 abs_file_name(const char *dir, const char *file_name)
633 if (file_name[0] == '/') {
634 return xstrdup(file_name);
635 } else if (dir && dir[0]) {
636 char *separator = dir[strlen(dir) - 1] == '/' ? "" : "/";
637 return xasprintf("%s%s%s", dir, separator, file_name);
639 char *cwd = get_cwd();
641 char *abs_name = xasprintf("%s/%s", cwd, file_name);
651 /* Pass a value to this function if it is marked with
652 * __attribute__((warn_unused_result)) and you genuinely want to ignore
653 * its return value. (Note that every scalar type can be implicitly
654 * converted to bool.) */
655 void ignore(bool x OVS_UNUSED) { }
657 /* Returns an appropriate delimiter for inserting just before the 0-based item
658 * 'index' in a list that has 'total' items in it. */
660 english_list_delimiter(size_t index, size_t total)
662 return (index == 0 ? ""
663 : index < total - 1 ? ", "
664 : total > 2 ? ", and "
668 /* Given a 32 bit word 'n', calculates floor(log_2('n')). This is equivalent
669 * to finding the bit position of the most significant one bit in 'n'. It is
670 * an error to call this function with 'n' == 0. */
672 log_2_floor(uint32_t n)
676 #if !defined(UINT_MAX) || !defined(UINT32_MAX)
677 #error "Someone screwed up the #includes."
678 #elif __GNUC__ >= 4 && UINT_MAX == UINT32_MAX
679 return 31 - __builtin_clz(n);
684 #define BIN_SEARCH_STEP(BITS) \
685 if (n >= (1 << BITS)) { \
694 #undef BIN_SEARCH_STEP
700 /* Given a 32 bit word 'n', calculates ceil(log_2('n')). It is an error to
701 * call this function with 'n' == 0. */
703 log_2_ceil(uint32_t n)
705 return log_2_floor(n) + !IS_POW2(n);
708 /* Returns the number of trailing 0-bits in 'n', or 32 if 'n' is 0. */
715 #if !defined(UINT_MAX) || !defined(UINT32_MAX)
716 #error "Someone screwed up the #includes."
717 #elif __GNUC__ >= 4 && UINT_MAX == UINT32_MAX
718 return __builtin_ctz(n);
723 #define CTZ_STEP(X) \
741 /* Returns true if the 'n' bytes starting at 'p' are zeros. */
743 is_all_zeros(const uint8_t *p, size_t n)
747 for (i = 0; i < n; i++) {
755 /* Returns true if the 'n' bytes starting at 'p' are 0xff. */
757 is_all_ones(const uint8_t *p, size_t n)
761 for (i = 0; i < n; i++) {
769 /* Copies 'n_bits' bits starting from bit 'src_ofs' in 'src' to the 'n_bits'
770 * starting from bit 'dst_ofs' in 'dst'. 'src' is 'src_len' bytes long and
771 * 'dst' is 'dst_len' bytes long.
773 * If you consider all of 'src' to be a single unsigned integer in network byte
774 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
775 * with value 1 in src[src_len - 1], bit 1 is the bit with value 2, bit 2 is
776 * the bit with value 4, ..., bit 8 is the bit with value 1 in src[src_len -
777 * 2], and so on. Similarly for 'dst'.
779 * Required invariants:
780 * src_ofs + n_bits <= src_len * 8
781 * dst_ofs + n_bits <= dst_len * 8
782 * 'src' and 'dst' must not overlap.
785 bitwise_copy(const void *src_, unsigned int src_len, unsigned int src_ofs,
786 void *dst_, unsigned int dst_len, unsigned int dst_ofs,
789 const uint8_t *src = src_;
792 src += src_len - (src_ofs / 8 + 1);
795 dst += dst_len - (dst_ofs / 8 + 1);
798 if (src_ofs == 0 && dst_ofs == 0) {
799 unsigned int n_bytes = n_bits / 8;
803 memcpy(dst, src, n_bytes);
810 uint8_t mask = (1 << n_bits) - 1;
811 *dst = (*dst & ~mask) | (*src & mask);
815 unsigned int max_copy = 8 - MAX(src_ofs, dst_ofs);
816 unsigned int chunk = MIN(n_bits, max_copy);
817 uint8_t mask = ((1 << chunk) - 1) << dst_ofs;
820 *dst |= ((*src >> src_ofs) << dst_ofs) & mask;
837 /* Zeros the 'n_bits' bits starting from bit 'dst_ofs' in 'dst'. 'dst' is
838 * 'dst_len' bytes long.
840 * If you consider all of 'dst' to be a single unsigned integer in network byte
841 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
842 * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
843 * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
846 * Required invariant:
847 * dst_ofs + n_bits <= dst_len * 8
850 bitwise_zero(void *dst_, unsigned int dst_len, unsigned dst_ofs,
859 dst += dst_len - (dst_ofs / 8 + 1);
863 unsigned int chunk = MIN(n_bits, 8 - dst_ofs);
865 *dst &= ~(((1 << chunk) - 1) << dst_ofs);
875 while (n_bits >= 8) {
881 *dst &= ~((1 << n_bits) - 1);
885 /* Sets to 1 all of the 'n_bits' bits starting from bit 'dst_ofs' in 'dst'.
886 * 'dst' is 'dst_len' bytes long.
888 * If you consider all of 'dst' to be a single unsigned integer in network byte
889 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
890 * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
891 * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
894 * Required invariant:
895 * dst_ofs + n_bits <= dst_len * 8
898 bitwise_one(void *dst_, unsigned int dst_len, unsigned dst_ofs,
907 dst += dst_len - (dst_ofs / 8 + 1);
911 unsigned int chunk = MIN(n_bits, 8 - dst_ofs);
913 *dst |= ((1 << chunk) - 1) << dst_ofs;
923 while (n_bits >= 8) {
929 *dst |= (1 << n_bits) - 1;
933 /* Scans the 'n_bits' bits starting from bit 'dst_ofs' in 'dst' for 1-bits.
934 * Returns false if any 1-bits are found, otherwise true. 'dst' is 'dst_len'
937 * If you consider all of 'dst' to be a single unsigned integer in network byte
938 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
939 * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
940 * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
943 * Required invariant:
944 * dst_ofs + n_bits <= dst_len * 8
947 bitwise_is_all_zeros(const void *p_, unsigned int len, unsigned int ofs,
950 const uint8_t *p = p_;
956 p += len - (ofs / 8 + 1);
960 unsigned int chunk = MIN(n_bits, 8 - ofs);
962 if (*p & (((1 << chunk) - 1) << ofs)) {
974 while (n_bits >= 8) {
982 if (n_bits && *p & ((1 << n_bits) - 1)) {
989 /* Copies the 'n_bits' low-order bits of 'value' into the 'n_bits' bits
990 * starting at bit 'dst_ofs' in 'dst', which is 'dst_len' bytes long.
992 * If you consider all of 'dst' to be a single unsigned integer in network byte
993 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
994 * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
995 * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
998 * Required invariants:
999 * dst_ofs + n_bits <= dst_len * 8
1003 bitwise_put(uint64_t value,
1004 void *dst, unsigned int dst_len, unsigned int dst_ofs,
1005 unsigned int n_bits)
1007 ovs_be64 n_value = htonll(value);
1008 bitwise_copy(&n_value, sizeof n_value, 0,
1009 dst, dst_len, dst_ofs,
1013 /* Returns the value of the 'n_bits' bits starting at bit 'src_ofs' in 'src',
1014 * which is 'src_len' bytes long.
1016 * If you consider all of 'src' to be a single unsigned integer in network byte
1017 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1018 * with value 1 in src[src_len - 1], bit 1 is the bit with value 2, bit 2 is
1019 * the bit with value 4, ..., bit 8 is the bit with value 1 in src[src_len -
1022 * Required invariants:
1023 * src_ofs + n_bits <= src_len * 8
1027 bitwise_get(const void *src, unsigned int src_len,
1028 unsigned int src_ofs, unsigned int n_bits)
1030 ovs_be64 value = htonll(0);
1032 bitwise_copy(src, src_len, src_ofs,
1033 &value, sizeof value, 0,
1035 return ntohll(value);