2 * Copyright (c) 2008, 2009, 2010, 2011, 2012 Nicira Networks.
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 * The 'date' and 'time' arguments should likely be called with
288 * "__DATE__" and "__TIME__" to use the time the binary was built.
289 * Alternatively, the "set_program_name" macro may be called to do this
293 set_program_name__(const char *argv0, const char *date, const char *time)
295 const char *slash = strrchr(argv0, '/');
296 program_name = slash ? slash + 1 : argv0;
298 free(program_version);
299 program_version = xasprintf("%s (Open vSwitch) "VERSION BUILDNR"\n"
301 program_name, date, time);
304 /* Returns a pointer to a string describing the program version. The
305 * caller must not modify or free the returned string.
308 get_program_version(void)
310 return program_version;
313 /* Print the version information for the program. */
315 ovs_print_version(uint8_t min_ofp, uint8_t max_ofp)
317 printf("%s", program_version);
318 if (min_ofp || max_ofp) {
319 printf("OpenFlow versions %#x:%#x\n", min_ofp, max_ofp);
323 /* Writes the 'size' bytes in 'buf' to 'stream' as hex bytes arranged 16 per
324 * line. Numeric offsets are also included, starting at 'ofs' for the first
325 * byte in 'buf'. If 'ascii' is true then the corresponding ASCII characters
326 * are also rendered alongside. */
328 ovs_hex_dump(FILE *stream, const void *buf_, size_t size,
329 uintptr_t ofs, bool ascii)
331 const uint8_t *buf = buf_;
332 const size_t per_line = 16; /* Maximum bytes per line. */
336 size_t start, end, n;
339 /* Number of bytes on this line. */
340 start = ofs % per_line;
342 if (end - start > size)
347 fprintf(stream, "%08jx ", (uintmax_t) ROUND_DOWN(ofs, per_line));
348 for (i = 0; i < start; i++)
349 fprintf(stream, " ");
351 fprintf(stream, "%02hhx%c",
352 buf[i - start], i == per_line / 2 - 1? '-' : ' ');
355 for (; i < per_line; i++)
356 fprintf(stream, " ");
357 fprintf(stream, "|");
358 for (i = 0; i < start; i++)
359 fprintf(stream, " ");
360 for (; i < end; i++) {
361 int c = buf[i - start];
362 putc(c >= 32 && c < 127 ? c : '.', stream);
364 for (; i < per_line; i++)
365 fprintf(stream, " ");
366 fprintf(stream, "|");
368 fprintf(stream, "\n");
377 str_to_int(const char *s, int base, int *i)
380 bool ok = str_to_llong(s, base, &ll);
386 str_to_long(const char *s, int base, long *li)
389 bool ok = str_to_llong(s, base, &ll);
395 str_to_llong(const char *s, int base, long long *x)
397 int save_errno = errno;
400 *x = strtoll(s, &tail, base);
401 if (errno == EINVAL || errno == ERANGE || tail == s || *tail != '\0') {
412 str_to_uint(const char *s, int base, unsigned int *u)
414 return str_to_int(s, base, (int *) u);
418 str_to_ulong(const char *s, int base, unsigned long *ul)
420 return str_to_long(s, base, (long *) ul);
424 str_to_ullong(const char *s, int base, unsigned long long *ull)
426 return str_to_llong(s, base, (long long *) ull);
429 /* Converts floating-point string 's' into a double. If successful, stores
430 * the double in '*d' and returns true; on failure, stores 0 in '*d' and
433 * Underflow (e.g. "1e-9999") is not considered an error, but overflow
434 * (e.g. "1e9999)" is. */
436 str_to_double(const char *s, double *d)
438 int save_errno = errno;
441 *d = strtod(s, &tail);
442 if (errno == EINVAL || (errno == ERANGE && *d != 0)
443 || tail == s || *tail != '\0') {
453 /* Returns the value of 'c' as a hexadecimal digit. */
458 case '0': case '1': case '2': case '3': case '4':
459 case '5': case '6': case '7': case '8': case '9':
485 /* Returns the integer value of the 'n' hexadecimal digits starting at 's', or
486 * UINT_MAX if one of those "digits" is not really a hex digit. If 'ok' is
487 * nonnull, '*ok' is set to true if the conversion succeeds or to false if a
488 * non-hex digit is detected. */
490 hexits_value(const char *s, size_t n, bool *ok)
496 for (i = 0; i < n; i++) {
497 int hexit = hexit_value(s[i]);
504 value = (value << 4) + hexit;
512 /* Returns the current working directory as a malloc()'d string, or a null
513 * pointer if the current working directory cannot be determined. */
520 /* Get maximum path length or at least a reasonable estimate. */
521 path_max = pathconf(".", _PC_PATH_MAX);
522 size = (path_max < 0 ? 1024
523 : path_max > 10240 ? 10240
526 /* Get current working directory. */
528 char *buf = xmalloc(size);
529 if (getcwd(buf, size)) {
530 return xrealloc(buf, strlen(buf) + 1);
534 if (error != ERANGE) {
535 VLOG_WARN("getcwd failed (%s)", strerror(error));
544 all_slashes_name(const char *s)
546 return xstrdup(s[0] == '/' && s[1] == '/' && s[2] != '/' ? "//"
551 /* Returns the directory name portion of 'file_name' as a malloc()'d string,
552 * similar to the POSIX dirname() function but thread-safe. */
554 dir_name(const char *file_name)
556 size_t len = strlen(file_name);
557 while (len > 0 && file_name[len - 1] == '/') {
560 while (len > 0 && file_name[len - 1] != '/') {
563 while (len > 0 && file_name[len - 1] == '/') {
566 return len ? xmemdup0(file_name, len) : all_slashes_name(file_name);
569 /* Returns the file name portion of 'file_name' as a malloc()'d string,
570 * similar to the POSIX basename() function but thread-safe. */
572 base_name(const char *file_name)
576 end = strlen(file_name);
577 while (end > 0 && file_name[end - 1] == '/') {
582 return all_slashes_name(file_name);
586 while (start > 0 && file_name[start - 1] != '/') {
590 return xmemdup0(file_name + start, end - start);
593 /* If 'file_name' starts with '/', returns a copy of 'file_name'. Otherwise,
594 * returns an absolute path to 'file_name' considering it relative to 'dir',
595 * which itself must be absolute. 'dir' may be null or the empty string, in
596 * which case the current working directory is used.
598 * Returns a null pointer if 'dir' is null and getcwd() fails. */
600 abs_file_name(const char *dir, const char *file_name)
602 if (file_name[0] == '/') {
603 return xstrdup(file_name);
604 } else if (dir && dir[0]) {
605 char *separator = dir[strlen(dir) - 1] == '/' ? "" : "/";
606 return xasprintf("%s%s%s", dir, separator, file_name);
608 char *cwd = get_cwd();
610 char *abs_name = xasprintf("%s/%s", cwd, file_name);
620 /* Pass a value to this function if it is marked with
621 * __attribute__((warn_unused_result)) and you genuinely want to ignore
622 * its return value. (Note that every scalar type can be implicitly
623 * converted to bool.) */
624 void ignore(bool x OVS_UNUSED) { }
626 /* Returns an appropriate delimiter for inserting just before the 0-based item
627 * 'index' in a list that has 'total' items in it. */
629 english_list_delimiter(size_t index, size_t total)
631 return (index == 0 ? ""
632 : index < total - 1 ? ", "
633 : total > 2 ? ", and "
637 /* Given a 32 bit word 'n', calculates floor(log_2('n')). This is equivalent
638 * to finding the bit position of the most significant one bit in 'n'. It is
639 * an error to call this function with 'n' == 0. */
641 log_2_floor(uint32_t n)
645 #if !defined(UINT_MAX) || !defined(UINT32_MAX)
646 #error "Someone screwed up the #includes."
647 #elif __GNUC__ >= 4 && UINT_MAX == UINT32_MAX
648 return 31 - __builtin_clz(n);
653 #define BIN_SEARCH_STEP(BITS) \
654 if (n >= (1 << BITS)) { \
663 #undef BIN_SEARCH_STEP
669 /* Given a 32 bit word 'n', calculates ceil(log_2('n')). It is an error to
670 * call this function with 'n' == 0. */
672 log_2_ceil(uint32_t n)
674 return log_2_floor(n) + !IS_POW2(n);
677 /* Returns the number of trailing 0-bits in 'n', or 32 if 'n' is 0. */
684 #if !defined(UINT_MAX) || !defined(UINT32_MAX)
685 #error "Someone screwed up the #includes."
686 #elif __GNUC__ >= 4 && UINT_MAX == UINT32_MAX
687 return __builtin_ctz(n);
692 #define CTZ_STEP(X) \
710 /* Returns true if the 'n' bytes starting at 'p' are zeros. */
712 is_all_zeros(const uint8_t *p, size_t n)
716 for (i = 0; i < n; i++) {
724 /* Returns true if the 'n' bytes starting at 'p' are 0xff. */
726 is_all_ones(const uint8_t *p, size_t n)
730 for (i = 0; i < n; i++) {
738 /* Copies 'n_bits' bits starting from bit 'src_ofs' in 'src' to the 'n_bits'
739 * starting from bit 'dst_ofs' in 'dst'. 'src' is 'src_len' bytes long and
740 * 'dst' is 'dst_len' bytes long.
742 * If you consider all of 'src' to be a single unsigned integer in network byte
743 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
744 * with value 1 in src[src_len - 1], bit 1 is the bit with value 2, bit 2 is
745 * the bit with value 4, ..., bit 8 is the bit with value 1 in src[src_len -
746 * 2], and so on. Similarly for 'dst'.
748 * Required invariants:
749 * src_ofs + n_bits <= src_len * 8
750 * dst_ofs + n_bits <= dst_len * 8
751 * 'src' and 'dst' must not overlap.
754 bitwise_copy(const void *src_, unsigned int src_len, unsigned int src_ofs,
755 void *dst_, unsigned int dst_len, unsigned int dst_ofs,
758 const uint8_t *src = src_;
761 src += src_len - (src_ofs / 8 + 1);
764 dst += dst_len - (dst_ofs / 8 + 1);
767 if (src_ofs == 0 && dst_ofs == 0) {
768 unsigned int n_bytes = n_bits / 8;
772 memcpy(dst, src, n_bytes);
779 uint8_t mask = (1 << n_bits) - 1;
780 *dst = (*dst & ~mask) | (*src & mask);
784 unsigned int max_copy = 8 - MAX(src_ofs, dst_ofs);
785 unsigned int chunk = MIN(n_bits, max_copy);
786 uint8_t mask = ((1 << chunk) - 1) << dst_ofs;
789 *dst |= ((*src >> src_ofs) << dst_ofs) & mask;
806 /* Zeros the 'n_bits' bits starting from bit 'dst_ofs' in 'dst'. 'dst' is
807 * 'dst_len' bytes long.
809 * If you consider all of 'dst' to be a single unsigned integer in network byte
810 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
811 * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
812 * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
815 * Required invariant:
816 * dst_ofs + n_bits <= dst_len * 8
819 bitwise_zero(void *dst_, unsigned int dst_len, unsigned dst_ofs,
828 dst += dst_len - (dst_ofs / 8 + 1);
832 unsigned int chunk = MIN(n_bits, 8 - dst_ofs);
834 *dst &= ~(((1 << chunk) - 1) << dst_ofs);
844 while (n_bits >= 8) {
850 *dst &= ~((1 << n_bits) - 1);
854 /* Copies the 'n_bits' low-order bits of 'value' into the 'n_bits' bits
855 * starting at bit 'dst_ofs' in 'dst', which is 'dst_len' bytes long.
857 * If you consider all of 'dst' to be a single unsigned integer in network byte
858 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
859 * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
860 * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
863 * Required invariants:
864 * dst_ofs + n_bits <= dst_len * 8
868 bitwise_put(uint64_t value,
869 void *dst, unsigned int dst_len, unsigned int dst_ofs,
872 ovs_be64 n_value = htonll(value);
873 bitwise_copy(&n_value, sizeof n_value, 0,
874 dst, dst_len, dst_ofs,
878 /* Returns the value of the 'n_bits' bits starting at bit 'src_ofs' in 'src',
879 * which is 'src_len' bytes long.
881 * If you consider all of 'src' to be a single unsigned integer in network byte
882 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
883 * with value 1 in src[src_len - 1], bit 1 is the bit with value 2, bit 2 is
884 * the bit with value 4, ..., bit 8 is the bit with value 1 in src[src_len -
887 * Required invariants:
888 * src_ofs + n_bits <= src_len * 8
892 bitwise_get(const void *src, unsigned int src_len,
893 unsigned int src_ofs, unsigned int n_bits)
895 ovs_be64 value = htonll(0);
897 bitwise_copy(src, src_len, src_ofs,
898 &value, sizeof value, 0,
900 return ntohll(value);