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 const char *program_name;
38 static char *program_version;
43 ovs_abort(0, "virtual memory exhausted");
47 xcalloc(size_t count, size_t size)
49 void *p = count && size ? calloc(count, size) : malloc(1);
50 COVERAGE_INC(util_xalloc);
60 return xcalloc(1, size);
66 void *p = malloc(size ? size : 1);
67 COVERAGE_INC(util_xalloc);
75 xrealloc(void *p, size_t size)
77 p = realloc(p, size ? size : 1);
78 COVERAGE_INC(util_xalloc);
86 xmemdup(const void *p_, size_t size)
88 void *p = xmalloc(size);
94 xmemdup0(const char *p_, size_t length)
96 char *p = xmalloc(length + 1);
97 memcpy(p, p_, length);
103 xstrdup(const char *s)
105 return xmemdup0(s, strlen(s));
109 xvasprintf(const char *format, va_list args)
115 va_copy(args2, args);
116 needed = vsnprintf(NULL, 0, format, args);
118 s = xmalloc(needed + 1);
120 vsnprintf(s, needed + 1, format, args2);
127 x2nrealloc(void *p, size_t *n, size_t s)
129 *n = *n == 0 ? 1 : 2 * *n;
130 return xrealloc(p, *n * s);
134 xasprintf(const char *format, ...)
139 va_start(args, format);
140 s = xvasprintf(format, args);
146 /* Similar to strlcpy() from OpenBSD, but it never reads more than 'size - 1'
147 * bytes from 'src' and doesn't return anything. */
149 ovs_strlcpy(char *dst, const char *src, size_t size)
152 size_t len = strnlen(src, size - 1);
153 memcpy(dst, src, len);
158 /* Copies 'src' to 'dst'. Reads no more than 'size - 1' bytes from 'src'.
159 * Always null-terminates 'dst' (if 'size' is nonzero), and writes a zero byte
160 * to every otherwise unused byte in 'dst'.
162 * Except for performance, the following call:
163 * ovs_strzcpy(dst, src, size);
164 * is equivalent to these two calls:
165 * memset(dst, '\0', size);
166 * ovs_strlcpy(dst, src, size);
168 * (Thus, ovs_strzcpy() is similar to strncpy() without some of the pitfalls.)
171 ovs_strzcpy(char *dst, const char *src, size_t size)
174 size_t len = strnlen(src, size - 1);
175 memcpy(dst, src, len);
176 memset(dst + len, '\0', size - len);
180 /* Prints 'format' on stderr, formatting it like printf() does. If 'err_no' is
181 * nonzero, then it is formatted with ovs_retval_to_string() and appended to
182 * the message inside parentheses. Then, terminates with abort().
184 * This function is preferred to ovs_fatal() in a situation where it would make
185 * sense for a monitoring process to restart the daemon.
187 * 'format' should not end with a new-line, because this function will add one
190 ovs_abort(int err_no, const char *format, ...)
194 va_start(args, format);
195 ovs_error_valist(err_no, format, args);
201 /* Prints 'format' on stderr, formatting it like printf() does. If 'err_no' is
202 * nonzero, then it is formatted with ovs_retval_to_string() and appended to
203 * the message inside parentheses. Then, terminates with EXIT_FAILURE.
205 * 'format' should not end with a new-line, because this function will add one
208 ovs_fatal(int err_no, const char *format, ...)
212 va_start(args, format);
213 ovs_fatal_valist(err_no, format, args);
216 /* Same as ovs_fatal() except that the arguments are supplied as a va_list. */
218 ovs_fatal_valist(int err_no, const char *format, va_list args)
220 ovs_error_valist(err_no, format, args);
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.
228 * 'format' should not end with a new-line, because this function will add one
231 ovs_error(int err_no, const char *format, ...)
235 va_start(args, format);
236 ovs_error_valist(err_no, format, args);
240 /* Same as ovs_error() except that the arguments are supplied as a va_list. */
242 ovs_error_valist(int err_no, const char *format, va_list args)
244 int save_errno = errno;
246 fprintf(stderr, "%s: ", program_name);
247 vfprintf(stderr, format, args);
249 fprintf(stderr, " (%s)", ovs_retval_to_string(err_no));
256 /* Many OVS functions return an int which is one of:
259 * - EOF: end of file (not necessarily an error; depends on the function called)
261 * Returns the appropriate human-readable string. The caller must copy the
262 * string if it wants to hold onto it, as the storage may be overwritten on
263 * subsequent function calls.
266 ovs_retval_to_string(int retval)
268 static char unknown[48];
274 return strerror(retval);
277 return "End of file";
279 snprintf(unknown, sizeof unknown, "***unknown return value: %d***", retval);
283 /* Sets global "program_name" and "program_version" variables. Should
284 * be called at the beginning of main() with "argv[0]" as the argument
287 * 'version' should contain the version of the caller's program. If 'version'
288 * is the same as the VERSION #define, the caller is assumed to be part of Open
289 * vSwitch. Otherwise, it is assumed to be an external program linking against
290 * the Open vSwitch libraries.
292 * The 'date' and 'time' arguments should likely be called with
293 * "__DATE__" and "__TIME__" to use the time the binary was built.
294 * Alternatively, the "set_program_name" macro may be called to do this
298 set_program_name__(const char *argv0, const char *version, const char *date,
301 const char *slash = strrchr(argv0, '/');
302 program_name = slash ? slash + 1 : argv0;
304 free(program_version);
306 if (!strcmp(version, VERSION)) {
307 program_version = xasprintf("%s (Open vSwitch) "VERSION"\n"
309 program_name, date, time);
311 program_version = xasprintf("%s %s\n"
312 "Open vSwitch Library "VERSION"\n"
314 program_name, version, date, time);
318 /* Returns a pointer to a string describing the program version. The
319 * caller must not modify or free the returned string.
322 get_program_version(void)
324 return program_version;
327 /* Print the version information for the program. */
329 ovs_print_version(uint8_t min_ofp, uint8_t max_ofp)
331 printf("%s", program_version);
332 if (min_ofp || max_ofp) {
333 printf("OpenFlow versions %#x:%#x\n", min_ofp, max_ofp);
337 /* Writes the 'size' bytes in 'buf' to 'stream' as hex bytes arranged 16 per
338 * line. Numeric offsets are also included, starting at 'ofs' for the first
339 * byte in 'buf'. If 'ascii' is true then the corresponding ASCII characters
340 * are also rendered alongside. */
342 ovs_hex_dump(FILE *stream, const void *buf_, size_t size,
343 uintptr_t ofs, bool ascii)
345 const uint8_t *buf = buf_;
346 const size_t per_line = 16; /* Maximum bytes per line. */
350 size_t start, end, n;
353 /* Number of bytes on this line. */
354 start = ofs % per_line;
356 if (end - start > size)
361 fprintf(stream, "%08jx ", (uintmax_t) ROUND_DOWN(ofs, per_line));
362 for (i = 0; i < start; i++)
363 fprintf(stream, " ");
365 fprintf(stream, "%02hhx%c",
366 buf[i - start], i == per_line / 2 - 1? '-' : ' ');
369 for (; i < per_line; i++)
370 fprintf(stream, " ");
371 fprintf(stream, "|");
372 for (i = 0; i < start; i++)
373 fprintf(stream, " ");
374 for (; i < end; i++) {
375 int c = buf[i - start];
376 putc(c >= 32 && c < 127 ? c : '.', stream);
378 for (; i < per_line; i++)
379 fprintf(stream, " ");
380 fprintf(stream, "|");
382 fprintf(stream, "\n");
391 str_to_int(const char *s, int base, int *i)
394 bool ok = str_to_llong(s, base, &ll);
400 str_to_long(const char *s, int base, long *li)
403 bool ok = str_to_llong(s, base, &ll);
409 str_to_llong(const char *s, int base, long long *x)
411 int save_errno = errno;
414 *x = strtoll(s, &tail, base);
415 if (errno == EINVAL || errno == ERANGE || tail == s || *tail != '\0') {
426 str_to_uint(const char *s, int base, unsigned int *u)
428 return str_to_int(s, base, (int *) u);
432 str_to_ulong(const char *s, int base, unsigned long *ul)
434 return str_to_long(s, base, (long *) ul);
438 str_to_ullong(const char *s, int base, unsigned long long *ull)
440 return str_to_llong(s, base, (long long *) ull);
443 /* Converts floating-point string 's' into a double. If successful, stores
444 * the double in '*d' and returns true; on failure, stores 0 in '*d' and
447 * Underflow (e.g. "1e-9999") is not considered an error, but overflow
448 * (e.g. "1e9999)" is. */
450 str_to_double(const char *s, double *d)
452 int save_errno = errno;
455 *d = strtod(s, &tail);
456 if (errno == EINVAL || (errno == ERANGE && *d != 0)
457 || tail == s || *tail != '\0') {
467 /* Returns the value of 'c' as a hexadecimal digit. */
472 case '0': case '1': case '2': case '3': case '4':
473 case '5': case '6': case '7': case '8': case '9':
499 /* Returns the integer value of the 'n' hexadecimal digits starting at 's', or
500 * UINT_MAX if one of those "digits" is not really a hex digit. If 'ok' is
501 * nonnull, '*ok' is set to true if the conversion succeeds or to false if a
502 * non-hex digit is detected. */
504 hexits_value(const char *s, size_t n, bool *ok)
510 for (i = 0; i < n; i++) {
511 int hexit = hexit_value(s[i]);
518 value = (value << 4) + hexit;
526 /* Returns the current working directory as a malloc()'d string, or a null
527 * pointer if the current working directory cannot be determined. */
534 /* Get maximum path length or at least a reasonable estimate. */
535 path_max = pathconf(".", _PC_PATH_MAX);
536 size = (path_max < 0 ? 1024
537 : path_max > 10240 ? 10240
540 /* Get current working directory. */
542 char *buf = xmalloc(size);
543 if (getcwd(buf, size)) {
544 return xrealloc(buf, strlen(buf) + 1);
548 if (error != ERANGE) {
549 VLOG_WARN("getcwd failed (%s)", strerror(error));
558 all_slashes_name(const char *s)
560 return xstrdup(s[0] == '/' && s[1] == '/' && s[2] != '/' ? "//"
565 /* Returns the directory name portion of 'file_name' as a malloc()'d string,
566 * similar to the POSIX dirname() function but thread-safe. */
568 dir_name(const char *file_name)
570 size_t len = strlen(file_name);
571 while (len > 0 && file_name[len - 1] == '/') {
574 while (len > 0 && file_name[len - 1] != '/') {
577 while (len > 0 && file_name[len - 1] == '/') {
580 return len ? xmemdup0(file_name, len) : all_slashes_name(file_name);
583 /* Returns the file name portion of 'file_name' as a malloc()'d string,
584 * similar to the POSIX basename() function but thread-safe. */
586 base_name(const char *file_name)
590 end = strlen(file_name);
591 while (end > 0 && file_name[end - 1] == '/') {
596 return all_slashes_name(file_name);
600 while (start > 0 && file_name[start - 1] != '/') {
604 return xmemdup0(file_name + start, end - start);
607 /* If 'file_name' starts with '/', returns a copy of 'file_name'. Otherwise,
608 * returns an absolute path to 'file_name' considering it relative to 'dir',
609 * which itself must be absolute. 'dir' may be null or the empty string, in
610 * which case the current working directory is used.
612 * Returns a null pointer if 'dir' is null and getcwd() fails. */
614 abs_file_name(const char *dir, const char *file_name)
616 if (file_name[0] == '/') {
617 return xstrdup(file_name);
618 } else if (dir && dir[0]) {
619 char *separator = dir[strlen(dir) - 1] == '/' ? "" : "/";
620 return xasprintf("%s%s%s", dir, separator, file_name);
622 char *cwd = get_cwd();
624 char *abs_name = xasprintf("%s/%s", cwd, file_name);
634 /* Pass a value to this function if it is marked with
635 * __attribute__((warn_unused_result)) and you genuinely want to ignore
636 * its return value. (Note that every scalar type can be implicitly
637 * converted to bool.) */
638 void ignore(bool x OVS_UNUSED) { }
640 /* Returns an appropriate delimiter for inserting just before the 0-based item
641 * 'index' in a list that has 'total' items in it. */
643 english_list_delimiter(size_t index, size_t total)
645 return (index == 0 ? ""
646 : index < total - 1 ? ", "
647 : total > 2 ? ", and "
651 /* Given a 32 bit word 'n', calculates floor(log_2('n')). This is equivalent
652 * to finding the bit position of the most significant one bit in 'n'. It is
653 * an error to call this function with 'n' == 0. */
655 log_2_floor(uint32_t n)
659 #if !defined(UINT_MAX) || !defined(UINT32_MAX)
660 #error "Someone screwed up the #includes."
661 #elif __GNUC__ >= 4 && UINT_MAX == UINT32_MAX
662 return 31 - __builtin_clz(n);
667 #define BIN_SEARCH_STEP(BITS) \
668 if (n >= (1 << BITS)) { \
677 #undef BIN_SEARCH_STEP
683 /* Given a 32 bit word 'n', calculates ceil(log_2('n')). It is an error to
684 * call this function with 'n' == 0. */
686 log_2_ceil(uint32_t n)
688 return log_2_floor(n) + !IS_POW2(n);
691 /* Returns the number of trailing 0-bits in 'n', or 32 if 'n' is 0. */
698 #if !defined(UINT_MAX) || !defined(UINT32_MAX)
699 #error "Someone screwed up the #includes."
700 #elif __GNUC__ >= 4 && UINT_MAX == UINT32_MAX
701 return __builtin_ctz(n);
706 #define CTZ_STEP(X) \
724 /* Returns true if the 'n' bytes starting at 'p' are zeros. */
726 is_all_zeros(const uint8_t *p, size_t n)
730 for (i = 0; i < n; i++) {
738 /* Returns true if the 'n' bytes starting at 'p' are 0xff. */
740 is_all_ones(const uint8_t *p, size_t n)
744 for (i = 0; i < n; i++) {
752 /* Copies 'n_bits' bits starting from bit 'src_ofs' in 'src' to the 'n_bits'
753 * starting from bit 'dst_ofs' in 'dst'. 'src' is 'src_len' bytes long and
754 * 'dst' is 'dst_len' bytes long.
756 * If you consider all of 'src' to be a single unsigned integer in network byte
757 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
758 * with value 1 in src[src_len - 1], bit 1 is the bit with value 2, bit 2 is
759 * the bit with value 4, ..., bit 8 is the bit with value 1 in src[src_len -
760 * 2], and so on. Similarly for 'dst'.
762 * Required invariants:
763 * src_ofs + n_bits <= src_len * 8
764 * dst_ofs + n_bits <= dst_len * 8
765 * 'src' and 'dst' must not overlap.
768 bitwise_copy(const void *src_, unsigned int src_len, unsigned int src_ofs,
769 void *dst_, unsigned int dst_len, unsigned int dst_ofs,
772 const uint8_t *src = src_;
775 src += src_len - (src_ofs / 8 + 1);
778 dst += dst_len - (dst_ofs / 8 + 1);
781 if (src_ofs == 0 && dst_ofs == 0) {
782 unsigned int n_bytes = n_bits / 8;
786 memcpy(dst, src, n_bytes);
793 uint8_t mask = (1 << n_bits) - 1;
794 *dst = (*dst & ~mask) | (*src & mask);
798 unsigned int max_copy = 8 - MAX(src_ofs, dst_ofs);
799 unsigned int chunk = MIN(n_bits, max_copy);
800 uint8_t mask = ((1 << chunk) - 1) << dst_ofs;
803 *dst |= ((*src >> src_ofs) << dst_ofs) & mask;
820 /* Zeros the 'n_bits' bits starting from bit 'dst_ofs' in 'dst'. 'dst' is
821 * 'dst_len' bytes long.
823 * If you consider all of 'dst' to be a single unsigned integer in network byte
824 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
825 * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
826 * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
829 * Required invariant:
830 * dst_ofs + n_bits <= dst_len * 8
833 bitwise_zero(void *dst_, unsigned int dst_len, unsigned dst_ofs,
842 dst += dst_len - (dst_ofs / 8 + 1);
846 unsigned int chunk = MIN(n_bits, 8 - dst_ofs);
848 *dst &= ~(((1 << chunk) - 1) << dst_ofs);
858 while (n_bits >= 8) {
864 *dst &= ~((1 << n_bits) - 1);
868 /* Sets to 1 all of the 'n_bits' bits starting from bit 'dst_ofs' in 'dst'.
869 * 'dst' is 'dst_len' bytes long.
871 * If you consider all of 'dst' to be a single unsigned integer in network byte
872 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
873 * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
874 * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
877 * Required invariant:
878 * dst_ofs + n_bits <= dst_len * 8
881 bitwise_one(void *dst_, unsigned int dst_len, unsigned dst_ofs,
890 dst += dst_len - (dst_ofs / 8 + 1);
894 unsigned int chunk = MIN(n_bits, 8 - dst_ofs);
896 *dst |= ((1 << chunk) - 1) << dst_ofs;
906 while (n_bits >= 8) {
912 *dst |= (1 << n_bits) - 1;
916 /* Scans the 'n_bits' bits starting from bit 'dst_ofs' in 'dst' for 1-bits.
917 * Returns false if any 1-bits are found, otherwise true. 'dst' is 'dst_len'
920 * If you consider all of 'dst' to be a single unsigned integer in network byte
921 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
922 * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
923 * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
926 * Required invariant:
927 * dst_ofs + n_bits <= dst_len * 8
930 bitwise_is_all_zeros(const void *p_, unsigned int len, unsigned int ofs,
933 const uint8_t *p = p_;
939 p += len - (ofs / 8 + 1);
943 unsigned int chunk = MIN(n_bits, 8 - ofs);
945 if (*p & (((1 << chunk) - 1) << ofs)) {
957 while (n_bits >= 8) {
965 if (n_bits && *p & ((1 << n_bits) - 1)) {
972 /* Copies the 'n_bits' low-order bits of 'value' into the 'n_bits' bits
973 * starting at bit 'dst_ofs' in 'dst', which is 'dst_len' bytes long.
975 * If you consider all of 'dst' to be a single unsigned integer in network byte
976 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
977 * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
978 * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
981 * Required invariants:
982 * dst_ofs + n_bits <= dst_len * 8
986 bitwise_put(uint64_t value,
987 void *dst, unsigned int dst_len, unsigned int dst_ofs,
990 ovs_be64 n_value = htonll(value);
991 bitwise_copy(&n_value, sizeof n_value, 0,
992 dst, dst_len, dst_ofs,
996 /* Returns the value of the 'n_bits' bits starting at bit 'src_ofs' in 'src',
997 * which is 'src_len' bytes long.
999 * If you consider all of 'src' to be a single unsigned integer in network byte
1000 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1001 * with value 1 in src[src_len - 1], bit 1 is the bit with value 2, bit 2 is
1002 * the bit with value 4, ..., bit 8 is the bit with value 1 in src[src_len -
1005 * Required invariants:
1006 * src_ofs + n_bits <= src_len * 8
1010 bitwise_get(const void *src, unsigned int src_len,
1011 unsigned int src_ofs, unsigned int n_bits)
1013 ovs_be64 value = htonll(0);
1015 bitwise_copy(src, src_len, src_ofs,
1016 &value, sizeof value, 0,
1018 return ntohll(value);