]>
git.proxmox.com Git - ovs.git/blob - lib/util.c
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_error_valist(err_no
, format
, args
);
208 /* Prints 'format' on stderr, formatting it like printf() does. If 'err_no' is
209 * nonzero, then it is formatted with ovs_retval_to_string() and appended to
210 * the message inside parentheses. Then, terminates with EXIT_FAILURE.
212 * 'format' should not end with a new-line, because this function will add one
215 ovs_fatal(int err_no
, const char *format
, ...)
219 va_start(args
, format
);
220 ovs_fatal_valist(err_no
, format
, args
);
223 /* Same as ovs_fatal() except that the arguments are supplied as a va_list. */
225 ovs_fatal_valist(int err_no
, const char *format
, va_list args
)
227 ovs_error_valist(err_no
, format
, args
);
231 /* Prints 'format' on stderr, formatting it like printf() does. If 'err_no' is
232 * nonzero, then it is formatted with ovs_retval_to_string() and appended to
233 * the message inside parentheses.
235 * 'format' should not end with a new-line, because this function will add one
238 ovs_error(int err_no
, const char *format
, ...)
242 va_start(args
, format
);
243 ovs_error_valist(err_no
, format
, args
);
247 /* Same as ovs_error() except that the arguments are supplied as a va_list. */
249 ovs_error_valist(int err_no
, const char *format
, va_list args
)
251 int save_errno
= errno
;
253 if (subprogram_name
[0]) {
254 fprintf(stderr
, "%s(%s): ", program_name
, subprogram_name
);
256 fprintf(stderr
, "%s: ", program_name
);
259 vfprintf(stderr
, format
, args
);
261 fprintf(stderr
, " (%s)", ovs_retval_to_string(err_no
));
268 /* Many OVS functions return an int which is one of:
271 * - EOF: end of file (not necessarily an error; depends on the function called)
273 * Returns the appropriate human-readable string. The caller must copy the
274 * string if it wants to hold onto it, as the storage may be overwritten on
275 * subsequent function calls.
278 ovs_retval_to_string(int retval
)
280 static char unknown
[48];
286 return strerror(retval
);
289 return "End of file";
291 snprintf(unknown
, sizeof unknown
, "***unknown return value: %d***", retval
);
295 /* Sets global "program_name" and "program_version" variables. Should
296 * be called at the beginning of main() with "argv[0]" as the argument
299 * 'version' should contain the version of the caller's program. If 'version'
300 * is the same as the VERSION #define, the caller is assumed to be part of Open
301 * vSwitch. Otherwise, it is assumed to be an external program linking against
302 * the Open vSwitch libraries.
304 * The 'date' and 'time' arguments should likely be called with
305 * "__DATE__" and "__TIME__" to use the time the binary was built.
306 * Alternatively, the "set_program_name" macro may be called to do this
310 set_program_name__(const char *argv0
, const char *version
, const char *date
,
313 const char *slash
= strrchr(argv0
, '/');
314 program_name
= slash
? slash
+ 1 : argv0
;
316 free(program_version
);
318 if (!strcmp(version
, VERSION
)) {
319 program_version
= xasprintf("%s (Open vSwitch) "VERSION
"\n"
321 program_name
, date
, time
);
323 program_version
= xasprintf("%s %s\n"
324 "Open vSwitch Library "VERSION
"\n"
326 program_name
, version
, date
, time
);
330 /* Returns a pointer to a string describing the program version. The
331 * caller must not modify or free the returned string.
334 get_program_version(void)
336 return program_version
;
339 /* Print the version information for the program. */
341 ovs_print_version(uint8_t min_ofp
, uint8_t max_ofp
)
343 printf("%s", program_version
);
344 if (min_ofp
|| max_ofp
) {
345 printf("OpenFlow versions %#x:%#x\n", min_ofp
, max_ofp
);
349 /* Writes the 'size' bytes in 'buf' to 'stream' as hex bytes arranged 16 per
350 * line. Numeric offsets are also included, starting at 'ofs' for the first
351 * byte in 'buf'. If 'ascii' is true then the corresponding ASCII characters
352 * are also rendered alongside. */
354 ovs_hex_dump(FILE *stream
, const void *buf_
, size_t size
,
355 uintptr_t ofs
, bool ascii
)
357 const uint8_t *buf
= buf_
;
358 const size_t per_line
= 16; /* Maximum bytes per line. */
362 size_t start
, end
, n
;
365 /* Number of bytes on this line. */
366 start
= ofs
% per_line
;
368 if (end
- start
> size
)
373 fprintf(stream
, "%08jx ", (uintmax_t) ROUND_DOWN(ofs
, per_line
));
374 for (i
= 0; i
< start
; i
++)
375 fprintf(stream
, " ");
377 fprintf(stream
, "%02hhx%c",
378 buf
[i
- start
], i
== per_line
/ 2 - 1? '-' : ' ');
381 for (; i
< per_line
; i
++)
382 fprintf(stream
, " ");
383 fprintf(stream
, "|");
384 for (i
= 0; i
< start
; i
++)
385 fprintf(stream
, " ");
386 for (; i
< end
; i
++) {
387 int c
= buf
[i
- start
];
388 putc(c
>= 32 && c
< 127 ? c
: '.', stream
);
390 for (; i
< per_line
; i
++)
391 fprintf(stream
, " ");
392 fprintf(stream
, "|");
394 fprintf(stream
, "\n");
403 str_to_int(const char *s
, int base
, int *i
)
406 bool ok
= str_to_llong(s
, base
, &ll
);
412 str_to_long(const char *s
, int base
, long *li
)
415 bool ok
= str_to_llong(s
, base
, &ll
);
421 str_to_llong(const char *s
, int base
, long long *x
)
423 int save_errno
= errno
;
426 *x
= strtoll(s
, &tail
, base
);
427 if (errno
== EINVAL
|| errno
== ERANGE
|| tail
== s
|| *tail
!= '\0') {
438 str_to_uint(const char *s
, int base
, unsigned int *u
)
440 return str_to_int(s
, base
, (int *) u
);
444 str_to_ulong(const char *s
, int base
, unsigned long *ul
)
446 return str_to_long(s
, base
, (long *) ul
);
450 str_to_ullong(const char *s
, int base
, unsigned long long *ull
)
452 return str_to_llong(s
, base
, (long long *) ull
);
455 /* Converts floating-point string 's' into a double. If successful, stores
456 * the double in '*d' and returns true; on failure, stores 0 in '*d' and
459 * Underflow (e.g. "1e-9999") is not considered an error, but overflow
460 * (e.g. "1e9999)" is. */
462 str_to_double(const char *s
, double *d
)
464 int save_errno
= errno
;
467 *d
= strtod(s
, &tail
);
468 if (errno
== EINVAL
|| (errno
== ERANGE
&& *d
!= 0)
469 || tail
== s
|| *tail
!= '\0') {
479 /* Returns the value of 'c' as a hexadecimal digit. */
484 case '0': case '1': case '2': case '3': case '4':
485 case '5': case '6': case '7': case '8': case '9':
511 /* Returns the integer value of the 'n' hexadecimal digits starting at 's', or
512 * UINT_MAX if one of those "digits" is not really a hex digit. If 'ok' is
513 * nonnull, '*ok' is set to true if the conversion succeeds or to false if a
514 * non-hex digit is detected. */
516 hexits_value(const char *s
, size_t n
, bool *ok
)
522 for (i
= 0; i
< n
; i
++) {
523 int hexit
= hexit_value(s
[i
]);
530 value
= (value
<< 4) + hexit
;
538 /* Returns the current working directory as a malloc()'d string, or a null
539 * pointer if the current working directory cannot be determined. */
546 /* Get maximum path length or at least a reasonable estimate. */
547 path_max
= pathconf(".", _PC_PATH_MAX
);
548 size
= (path_max
< 0 ? 1024
549 : path_max
> 10240 ? 10240
552 /* Get current working directory. */
554 char *buf
= xmalloc(size
);
555 if (getcwd(buf
, size
)) {
556 return xrealloc(buf
, strlen(buf
) + 1);
560 if (error
!= ERANGE
) {
561 VLOG_WARN("getcwd failed (%s)", strerror(error
));
570 all_slashes_name(const char *s
)
572 return xstrdup(s
[0] == '/' && s
[1] == '/' && s
[2] != '/' ? "//"
577 /* Returns the directory name portion of 'file_name' as a malloc()'d string,
578 * similar to the POSIX dirname() function but thread-safe. */
580 dir_name(const char *file_name
)
582 size_t len
= strlen(file_name
);
583 while (len
> 0 && file_name
[len
- 1] == '/') {
586 while (len
> 0 && file_name
[len
- 1] != '/') {
589 while (len
> 0 && file_name
[len
- 1] == '/') {
592 return len
? xmemdup0(file_name
, len
) : all_slashes_name(file_name
);
595 /* Returns the file name portion of 'file_name' as a malloc()'d string,
596 * similar to the POSIX basename() function but thread-safe. */
598 base_name(const char *file_name
)
602 end
= strlen(file_name
);
603 while (end
> 0 && file_name
[end
- 1] == '/') {
608 return all_slashes_name(file_name
);
612 while (start
> 0 && file_name
[start
- 1] != '/') {
616 return xmemdup0(file_name
+ start
, end
- start
);
619 /* If 'file_name' starts with '/', returns a copy of 'file_name'. Otherwise,
620 * returns an absolute path to 'file_name' considering it relative to 'dir',
621 * which itself must be absolute. 'dir' may be null or the empty string, in
622 * which case the current working directory is used.
624 * Returns a null pointer if 'dir' is null and getcwd() fails. */
626 abs_file_name(const char *dir
, const char *file_name
)
628 if (file_name
[0] == '/') {
629 return xstrdup(file_name
);
630 } else if (dir
&& dir
[0]) {
631 char *separator
= dir
[strlen(dir
) - 1] == '/' ? "" : "/";
632 return xasprintf("%s%s%s", dir
, separator
, file_name
);
634 char *cwd
= get_cwd();
636 char *abs_name
= xasprintf("%s/%s", cwd
, file_name
);
646 /* Pass a value to this function if it is marked with
647 * __attribute__((warn_unused_result)) and you genuinely want to ignore
648 * its return value. (Note that every scalar type can be implicitly
649 * converted to bool.) */
650 void ignore(bool x OVS_UNUSED
) { }
652 /* Returns an appropriate delimiter for inserting just before the 0-based item
653 * 'index' in a list that has 'total' items in it. */
655 english_list_delimiter(size_t index
, size_t total
)
657 return (index
== 0 ? ""
658 : index
< total
- 1 ? ", "
659 : total
> 2 ? ", and "
663 /* Given a 32 bit word 'n', calculates floor(log_2('n')). This is equivalent
664 * to finding the bit position of the most significant one bit in 'n'. It is
665 * an error to call this function with 'n' == 0. */
667 log_2_floor(uint32_t n
)
671 #if !defined(UINT_MAX) || !defined(UINT32_MAX)
672 #error "Someone screwed up the #includes."
673 #elif __GNUC__ >= 4 && UINT_MAX == UINT32_MAX
674 return 31 - __builtin_clz(n
);
679 #define BIN_SEARCH_STEP(BITS) \
680 if (n >= (1 << BITS)) { \
689 #undef BIN_SEARCH_STEP
695 /* Given a 32 bit word 'n', calculates ceil(log_2('n')). It is an error to
696 * call this function with 'n' == 0. */
698 log_2_ceil(uint32_t n
)
700 return log_2_floor(n
) + !IS_POW2(n
);
703 /* Returns the number of trailing 0-bits in 'n', or 32 if 'n' is 0. */
710 #if !defined(UINT_MAX) || !defined(UINT32_MAX)
711 #error "Someone screwed up the #includes."
712 #elif __GNUC__ >= 4 && UINT_MAX == UINT32_MAX
713 return __builtin_ctz(n
);
718 #define CTZ_STEP(X) \
736 /* Returns true if the 'n' bytes starting at 'p' are zeros. */
738 is_all_zeros(const uint8_t *p
, size_t n
)
742 for (i
= 0; i
< n
; i
++) {
750 /* Returns true if the 'n' bytes starting at 'p' are 0xff. */
752 is_all_ones(const uint8_t *p
, size_t n
)
756 for (i
= 0; i
< n
; i
++) {
764 /* Copies 'n_bits' bits starting from bit 'src_ofs' in 'src' to the 'n_bits'
765 * starting from bit 'dst_ofs' in 'dst'. 'src' is 'src_len' bytes long and
766 * 'dst' is 'dst_len' bytes long.
768 * If you consider all of 'src' to be a single unsigned integer in network byte
769 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
770 * with value 1 in src[src_len - 1], bit 1 is the bit with value 2, bit 2 is
771 * the bit with value 4, ..., bit 8 is the bit with value 1 in src[src_len -
772 * 2], and so on. Similarly for 'dst'.
774 * Required invariants:
775 * src_ofs + n_bits <= src_len * 8
776 * dst_ofs + n_bits <= dst_len * 8
777 * 'src' and 'dst' must not overlap.
780 bitwise_copy(const void *src_
, unsigned int src_len
, unsigned int src_ofs
,
781 void *dst_
, unsigned int dst_len
, unsigned int dst_ofs
,
784 const uint8_t *src
= src_
;
787 src
+= src_len
- (src_ofs
/ 8 + 1);
790 dst
+= dst_len
- (dst_ofs
/ 8 + 1);
793 if (src_ofs
== 0 && dst_ofs
== 0) {
794 unsigned int n_bytes
= n_bits
/ 8;
798 memcpy(dst
, src
, n_bytes
);
805 uint8_t mask
= (1 << n_bits
) - 1;
806 *dst
= (*dst
& ~mask
) | (*src
& mask
);
810 unsigned int max_copy
= 8 - MAX(src_ofs
, dst_ofs
);
811 unsigned int chunk
= MIN(n_bits
, max_copy
);
812 uint8_t mask
= ((1 << chunk
) - 1) << dst_ofs
;
815 *dst
|= ((*src
>> src_ofs
) << dst_ofs
) & mask
;
832 /* Zeros the 'n_bits' bits starting from bit 'dst_ofs' in 'dst'. 'dst' is
833 * 'dst_len' bytes long.
835 * If you consider all of 'dst' to be a single unsigned integer in network byte
836 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
837 * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
838 * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
841 * Required invariant:
842 * dst_ofs + n_bits <= dst_len * 8
845 bitwise_zero(void *dst_
, unsigned int dst_len
, unsigned dst_ofs
,
854 dst
+= dst_len
- (dst_ofs
/ 8 + 1);
858 unsigned int chunk
= MIN(n_bits
, 8 - dst_ofs
);
860 *dst
&= ~(((1 << chunk
) - 1) << dst_ofs
);
870 while (n_bits
>= 8) {
876 *dst
&= ~((1 << n_bits
) - 1);
880 /* Sets to 1 all of the 'n_bits' bits starting from bit 'dst_ofs' in 'dst'.
881 * 'dst' is 'dst_len' bytes long.
883 * If you consider all of 'dst' to be a single unsigned integer in network byte
884 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
885 * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
886 * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
889 * Required invariant:
890 * dst_ofs + n_bits <= dst_len * 8
893 bitwise_one(void *dst_
, unsigned int dst_len
, unsigned dst_ofs
,
902 dst
+= dst_len
- (dst_ofs
/ 8 + 1);
906 unsigned int chunk
= MIN(n_bits
, 8 - dst_ofs
);
908 *dst
|= ((1 << chunk
) - 1) << dst_ofs
;
918 while (n_bits
>= 8) {
924 *dst
|= (1 << n_bits
) - 1;
928 /* Scans the 'n_bits' bits starting from bit 'dst_ofs' in 'dst' for 1-bits.
929 * Returns false if any 1-bits are found, otherwise true. 'dst' is 'dst_len'
932 * If you consider all of 'dst' to be a single unsigned integer in network byte
933 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
934 * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
935 * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
938 * Required invariant:
939 * dst_ofs + n_bits <= dst_len * 8
942 bitwise_is_all_zeros(const void *p_
, unsigned int len
, unsigned int ofs
,
945 const uint8_t *p
= p_
;
951 p
+= len
- (ofs
/ 8 + 1);
955 unsigned int chunk
= MIN(n_bits
, 8 - ofs
);
957 if (*p
& (((1 << chunk
) - 1) << ofs
)) {
969 while (n_bits
>= 8) {
977 if (n_bits
&& *p
& ((1 << n_bits
) - 1)) {
984 /* Copies the 'n_bits' low-order bits of 'value' into the 'n_bits' bits
985 * starting at bit 'dst_ofs' in 'dst', which is 'dst_len' bytes long.
987 * If you consider all of 'dst' to be a single unsigned integer in network byte
988 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
989 * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
990 * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
993 * Required invariants:
994 * dst_ofs + n_bits <= dst_len * 8
998 bitwise_put(uint64_t value
,
999 void *dst
, unsigned int dst_len
, unsigned int dst_ofs
,
1000 unsigned int n_bits
)
1002 ovs_be64 n_value
= htonll(value
);
1003 bitwise_copy(&n_value
, sizeof n_value
, 0,
1004 dst
, dst_len
, dst_ofs
,
1008 /* Returns the value of the 'n_bits' bits starting at bit 'src_ofs' in 'src',
1009 * which is 'src_len' bytes long.
1011 * If you consider all of 'src' to be a single unsigned integer in network byte
1012 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1013 * with value 1 in src[src_len - 1], bit 1 is the bit with value 2, bit 2 is
1014 * the bit with value 4, ..., bit 8 is the bit with value 1 in src[src_len -
1017 * Required invariants:
1018 * src_ofs + n_bits <= src_len * 8
1022 bitwise_get(const void *src
, unsigned int src_len
,
1023 unsigned int src_ofs
, unsigned int n_bits
)
1025 ovs_be64 value
= htonll(0);
1027 bitwise_copy(src
, src_len
, src_ofs
,
1028 &value
, sizeof value
, 0,
1030 return ntohll(value
);