2 * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016 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"
34 #include "ovs-thread.h"
35 #include "socket-util.h"
37 #include "openvswitch/vlog.h"
38 #ifdef HAVE_PTHREAD_SET_NAME_NP
39 #include <pthread_np.h>
45 VLOG_DEFINE_THIS_MODULE(util
);
49 #include <asm/param.h>
54 COVERAGE_DEFINE(util_xalloc
);
56 /* argv[0] without directory names. */
59 /* Name for the currently running thread or process, for log messages, process
60 * listings, and debuggers. */
61 DEFINE_PER_THREAD_MALLOCED_DATA(char *, subprogram_name
);
63 /* --version option output. */
64 static char *program_version
;
66 /* 'true' if mlockall() succeeded. */
67 static bool is_memory_locked
= false;
69 /* Buffer used by ovs_strerror() and ovs_format_message(). */
70 DEFINE_STATIC_PER_THREAD_DATA(struct { char s
[128]; },
74 static char *xreadlink(const char *filename
);
77 ovs_assert_failure(const char *where
, const char *function
,
78 const char *condition
)
80 /* Prevent an infinite loop (or stack overflow) in case VLOG_ABORT happens
81 * to trigger an assertion failure of its own. */
82 static int reentry
= 0;
86 VLOG_ABORT("%s: assertion %s failed in %s()",
87 where
, condition
, function
);
91 fprintf(stderr
, "%s: assertion %s failed in %s()",
92 where
, condition
, function
);
101 set_memory_locked(void)
103 is_memory_locked
= true;
109 return is_memory_locked
;
115 ovs_abort(0, "virtual memory exhausted");
119 xcalloc(size_t count
, size_t size
)
121 void *p
= count
&& size
? calloc(count
, size
) : malloc(1);
122 COVERAGE_INC(util_xalloc
);
132 return xcalloc(1, size
);
138 void *p
= malloc(size
? size
: 1);
139 COVERAGE_INC(util_xalloc
);
147 xrealloc(void *p
, size_t size
)
149 p
= realloc(p
, size
? size
: 1);
150 COVERAGE_INC(util_xalloc
);
158 xmemdup(const void *p_
, size_t size
)
160 void *p
= xmalloc(size
);
161 nullable_memcpy(p
, p_
, size
);
166 xmemdup0(const char *p_
, size_t length
)
168 char *p
= xmalloc(length
+ 1);
169 memcpy(p
, p_
, length
);
175 xstrdup(const char *s
)
177 return xmemdup0(s
, strlen(s
));
181 nullable_xstrdup(const char *s
)
183 return s
? xstrdup(s
) : NULL
;
187 nullable_string_is_equal(const char *a
, const char *b
)
189 return a
? b
&& !strcmp(a
, b
) : !b
;
193 xvasprintf(const char *format
, va_list args
)
199 va_copy(args2
, args
);
200 needed
= vsnprintf(NULL
, 0, format
, args
);
202 s
= xmalloc(needed
+ 1);
204 vsnprintf(s
, needed
+ 1, format
, args2
);
211 x2nrealloc(void *p
, size_t *n
, size_t s
)
213 *n
= *n
== 0 ? 1 : 2 * *n
;
214 return xrealloc(p
, *n
* s
);
217 /* Allocates and returns 'size' bytes of memory aligned to 'alignment' bytes.
218 * 'alignment' must be a power of two and a multiple of sizeof(void *).
220 * Use free_size_align() to free the returned memory block. */
222 xmalloc_size_align(size_t size
, size_t alignment
)
224 #ifdef HAVE_POSIX_MEMALIGN
228 COVERAGE_INC(util_xalloc
);
229 error
= posix_memalign(&p
, alignment
, size
? size
: 1);
235 /* Allocate room for:
237 * - Header padding: Up to alignment - 1 bytes, to allow the
238 * pointer 'q' to be aligned exactly sizeof(void *) bytes before the
239 * beginning of the alignment.
241 * - Pointer: A pointer to the start of the header padding, to allow us
242 * to free() the block later.
244 * - User data: 'size' bytes.
246 * - Trailer padding: Enough to bring the user data up to a alignment
249 * +---------------+---------+------------------------+---------+
250 * | header | pointer | user data | trailer |
251 * +---------------+---------+------------------------+---------+
260 if (!IS_POW2(alignment
) || (alignment
% sizeof(void *) != 0)) {
261 ovs_abort(0, "Invalid alignment");
264 p
= xmalloc((alignment
- 1)
266 + ROUND_UP(size
, alignment
));
268 runt
= PAD_SIZE((uintptr_t) p
, alignment
) < sizeof(void *);
269 /* When the padding size < sizeof(void*), we don't have enough room for
270 * pointer 'q'. As a reuslt, need to move 'r' to the next alignment.
271 * So ROUND_UP when xmalloc above, and ROUND_UP again when calculate 'r'
274 r
= (void *) ROUND_UP((uintptr_t) p
+ (runt
? alignment
: 0), alignment
);
283 free_size_align(void *p
)
285 #ifdef HAVE_POSIX_MEMALIGN
289 void **q
= (void **) p
- 1;
295 /* Allocates and returns 'size' bytes of memory aligned to a cache line and in
296 * dedicated cache lines. That is, the memory block returned will not share a
297 * cache line with other data, avoiding "false sharing".
299 * Use free_cacheline() to free the returned memory block. */
301 xmalloc_cacheline(size_t size
)
303 return xmalloc_size_align(size
, CACHE_LINE_SIZE
);
306 /* Like xmalloc_cacheline() but clears the allocated memory to all zero
309 xzalloc_cacheline(size_t size
)
311 void *p
= xmalloc_cacheline(size
);
316 /* Frees a memory block allocated with xmalloc_cacheline() or
317 * xzalloc_cacheline(). */
319 free_cacheline(void *p
)
325 xmalloc_pagealign(size_t size
)
327 return xmalloc_size_align(size
, get_page_size());
331 free_pagealign(void *p
)
337 xasprintf(const char *format
, ...)
342 va_start(args
, format
);
343 s
= xvasprintf(format
, args
);
349 /* Similar to strlcpy() from OpenBSD, but it never reads more than 'size - 1'
350 * bytes from 'src' and doesn't return anything. */
352 ovs_strlcpy(char *dst
, const char *src
, size_t size
)
355 size_t len
= strnlen(src
, size
- 1);
356 memcpy(dst
, src
, len
);
361 /* Copies 'src' to 'dst'. Reads no more than 'size - 1' bytes from 'src'.
362 * Always null-terminates 'dst' (if 'size' is nonzero), and writes a zero byte
363 * to every otherwise unused byte in 'dst'.
365 * Except for performance, the following call:
366 * ovs_strzcpy(dst, src, size);
367 * is equivalent to these two calls:
368 * memset(dst, '\0', size);
369 * ovs_strlcpy(dst, src, size);
371 * (Thus, ovs_strzcpy() is similar to strncpy() without some of the pitfalls.)
374 ovs_strzcpy(char *dst
, const char *src
, size_t size
)
377 size_t len
= strnlen(src
, size
- 1);
378 memcpy(dst
, src
, len
);
379 memset(dst
+ len
, '\0', size
- len
);
384 * Returns true if 'str' ends with given 'suffix'.
387 string_ends_with(const char *str
, const char *suffix
)
389 int str_len
= strlen(str
);
390 int suffix_len
= strlen(suffix
);
392 return (str_len
>= suffix_len
) &&
393 (0 == strcmp(str
+ (str_len
- suffix_len
), suffix
));
396 /* Prints 'format' on stderr, formatting it like printf() does. If 'err_no' is
397 * nonzero, then it is formatted with ovs_retval_to_string() and appended to
398 * the message inside parentheses. Then, terminates with abort().
400 * This function is preferred to ovs_fatal() in a situation where it would make
401 * sense for a monitoring process to restart the daemon.
403 * 'format' should not end with a new-line, because this function will add one
406 ovs_abort(int err_no
, const char *format
, ...)
410 va_start(args
, format
);
411 ovs_abort_valist(err_no
, format
, args
);
414 /* Same as ovs_abort() except that the arguments are supplied as a va_list. */
416 ovs_abort_valist(int err_no
, const char *format
, va_list args
)
418 ovs_error_valist(err_no
, format
, args
);
422 /* Prints 'format' on stderr, formatting it like printf() does. If 'err_no' is
423 * nonzero, then it is formatted with ovs_retval_to_string() and appended to
424 * the message inside parentheses. Then, terminates with EXIT_FAILURE.
426 * 'format' should not end with a new-line, because this function will add one
429 ovs_fatal(int err_no
, const char *format
, ...)
433 va_start(args
, format
);
434 ovs_fatal_valist(err_no
, format
, args
);
437 /* Same as ovs_fatal() except that the arguments are supplied as a va_list. */
439 ovs_fatal_valist(int err_no
, const char *format
, va_list args
)
441 ovs_error_valist(err_no
, format
, args
);
445 /* Prints 'format' on stderr, formatting it like printf() does. If 'err_no' is
446 * nonzero, then it is formatted with ovs_retval_to_string() and appended to
447 * the message inside parentheses.
449 * 'format' should not end with a new-line, because this function will add one
452 ovs_error(int err_no
, const char *format
, ...)
456 va_start(args
, format
);
457 ovs_error_valist(err_no
, format
, args
);
461 /* Same as ovs_error() except that the arguments are supplied as a va_list. */
463 ovs_error_valist(int err_no
, const char *format
, va_list args
)
465 const char *subprogram_name
= get_subprogram_name();
466 int save_errno
= errno
;
468 if (subprogram_name
[0]) {
469 fprintf(stderr
, "%s(%s): ", program_name
, subprogram_name
);
471 fprintf(stderr
, "%s: ", program_name
);
474 vfprintf(stderr
, format
, args
);
476 fprintf(stderr
, " (%s)", ovs_retval_to_string(err_no
));
483 /* Many OVS functions return an int which is one of:
486 * - EOF: end of file (not necessarily an error; depends on the function called)
488 * Returns the appropriate human-readable string. The caller must copy the
489 * string if it wants to hold onto it, as the storage may be overwritten on
490 * subsequent function calls.
493 ovs_retval_to_string(int retval
)
496 : retval
== EOF
? "End of file"
497 : ovs_strerror(retval
));
500 /* This function returns the string describing the error number in 'error'
501 * for POSIX platforms. For Windows, this function can be used for C library
502 * calls. For socket calls that are also used in Windows, use sock_strerror()
503 * instead. For WINAPI calls, look at ovs_lasterror_to_string(). */
505 ovs_strerror(int error
)
507 enum { BUFSIZE
= sizeof strerror_buffer_get()->s
};
514 * strerror(0) varies among platforms:
520 * We want to provide a consistent result here because
521 * our testsuite has test cases which strictly matches
522 * log messages containing this string.
528 buffer
= strerror_buffer_get()->s
;
530 #if STRERROR_R_CHAR_P
531 /* GNU style strerror_r() might return an immutable static string, or it
532 * might write and return 'buffer', but in either case we can pass the
533 * returned string directly to the caller. */
534 s
= strerror_r(error
, buffer
, BUFSIZE
);
535 #else /* strerror_r() returns an int. */
537 if (strerror_r(error
, buffer
, BUFSIZE
)) {
538 /* strerror_r() is only allowed to fail on ERANGE (because the buffer
539 * is too short). We don't check the actual failure reason because
540 * POSIX requires strerror_r() to return the error but old glibc
541 * (before 2.13) returns -1 and sets errno. */
542 snprintf(buffer
, BUFSIZE
, "Unknown error %d", error
);
551 /* Sets global "program_name" and "program_version" variables. Should
552 * be called at the beginning of main() with "argv[0]" as the argument
555 * 'version' should contain the version of the caller's program. If 'version'
556 * is the same as the VERSION #define, the caller is assumed to be part of Open
557 * vSwitch. Otherwise, it is assumed to be an external program linking against
558 * the Open vSwitch libraries.
562 ovs_set_program_name(const char *argv0
, const char *version
)
566 size_t max_len
= strlen(argv0
) + 1;
568 SetErrorMode(GetErrorMode() | SEM_NOGPFAULTERRORBOX
);
570 /* This function is deprecated from 1900 (Visual Studio 2015) */
571 _set_output_format(_TWO_DIGIT_EXPONENT
);
574 basename
= xmalloc(max_len
);
575 _splitpath_s(argv0
, NULL
, 0, NULL
, 0, basename
, max_len
, NULL
, 0);
577 const char *slash
= strrchr(argv0
, '/');
578 basename
= xstrdup(slash
? slash
+ 1 : argv0
);
581 assert_single_threaded();
583 /* Remove libtool prefix, if it is there */
584 if (strncmp(basename
, "lt-", 3) == 0) {
585 char *tmp_name
= basename
;
586 basename
= xstrdup(basename
+ 3);
589 program_name
= basename
;
591 free(program_version
);
592 if (!strcmp(version
, VERSION
)) {
593 program_version
= xasprintf("%s (Open vSwitch) "VERSION
"\n",
596 program_version
= xasprintf("%s %s\n"
597 "Open vSwitch Library "VERSION
"\n",
598 program_name
, version
);
602 /* Returns the name of the currently running thread or process. */
604 get_subprogram_name(void)
606 const char *name
= subprogram_name_get();
607 return name
? name
: "";
610 /* Sets 'subprogram_name' as the name of the currently running thread or
611 * process. (This appears in log messages and may also be visible in system
612 * process listings and debuggers.) */
614 set_subprogram_name(const char *subprogram_name
)
616 char *pname
= xstrdup(subprogram_name
? subprogram_name
: program_name
);
617 free(subprogram_name_set(pname
));
619 #if HAVE_GLIBC_PTHREAD_SETNAME_NP
620 pthread_setname_np(pthread_self(), pname
);
621 #elif HAVE_NETBSD_PTHREAD_SETNAME_NP
622 pthread_setname_np(pthread_self(), "%s", pname
);
623 #elif HAVE_PTHREAD_SET_NAME_NP
624 pthread_set_name_np(pthread_self(), pname
);
631 static unsigned int cached
;
635 long int value
= sysconf(_SC_PAGESIZE
);
639 GetSystemInfo(&sysinfo
);
640 value
= sysinfo
.dwPageSize
;
650 /* Returns the time at which the system booted, as the number of milliseconds
651 * since the epoch, or 0 if the time of boot cannot be determined. */
655 static long long int cache_expiration
= LLONG_MIN
;
656 static long long int boot_time
;
660 if (time_msec() >= cache_expiration
) {
661 static const char stat_file
[] = "/proc/stat";
665 cache_expiration
= time_msec() + 5 * 1000;
667 stream
= fopen(stat_file
, "r");
669 VLOG_ERR_ONCE("%s: open failed (%s)",
670 stat_file
, ovs_strerror(errno
));
674 while (fgets(line
, sizeof line
, stream
)) {
676 if (ovs_scan(line
, "btime %lld", &btime
)) {
677 boot_time
= btime
* 1000;
681 VLOG_ERR_ONCE("%s: btime not found", stat_file
);
688 /* This is a wrapper for setting timeout in control utils.
689 * The value of OVS_CTL_TIMEOUT environment variable will be used by
690 * default if 'secs' is not specified. */
692 ctl_timeout_setup(unsigned int secs
)
695 char *env
= getenv("OVS_CTL_TIMEOUT");
698 str_to_uint(env
, 10, &secs
);
706 /* Returns a pointer to a string describing the program version. The
707 * caller must not modify or free the returned string.
710 ovs_get_program_version(void)
712 return program_version
;
715 /* Returns a pointer to a string describing the program name. The
716 * caller must not modify or free the returned string.
719 ovs_get_program_name(void)
724 /* Print the version information for the program. */
726 ovs_print_version(uint8_t min_ofp
, uint8_t max_ofp
)
728 printf("%s", program_version
);
729 if (min_ofp
|| max_ofp
) {
730 printf("OpenFlow versions %#x:%#x\n", min_ofp
, max_ofp
);
734 /* Writes the 'size' bytes in 'buf' to 'stream' as hex bytes arranged 16 per
735 * line. Numeric offsets are also included, starting at 'ofs' for the first
736 * byte in 'buf'. If 'ascii' is true then the corresponding ASCII characters
737 * are also rendered alongside. */
739 ovs_hex_dump(FILE *stream
, const void *buf_
, size_t size
,
740 uintptr_t ofs
, bool ascii
)
742 const uint8_t *buf
= buf_
;
743 const size_t per_line
= 16; /* Maximum bytes per line. */
748 /* Number of bytes on this line. */
749 size_t start
= ofs
% per_line
;
750 size_t end
= per_line
;
751 if (end
- start
> size
) {
754 size_t n
= end
- start
;
757 fprintf(stream
, "%08"PRIxMAX
" ",
758 (uintmax_t) ROUND_DOWN(ofs
, per_line
));
759 for (i
= 0; i
< start
; i
++) {
760 fprintf(stream
, " ");
762 for (; i
< end
; i
++) {
763 fprintf(stream
, "%c%02x",
764 i
== per_line
/ 2 ? '-' : ' ', buf
[i
- start
]);
767 fprintf(stream
, " ");
768 for (; i
< per_line
; i
++) {
769 fprintf(stream
, " ");
771 fprintf(stream
, "|");
772 for (i
= 0; i
< start
; i
++) {
773 fprintf(stream
, " ");
775 for (; i
< end
; i
++) {
776 int c
= buf
[i
- start
];
777 putc(c
>= 32 && c
< 127 ? c
: '.', stream
);
779 for (; i
< per_line
; i
++) {
780 fprintf(stream
, " ");
782 fprintf(stream
, "|");
784 fprintf(stream
, "\n");
793 str_to_int(const char *s
, int base
, int *i
)
796 bool ok
= str_to_llong(s
, base
, &ll
);
798 if (!ok
|| ll
< INT_MIN
|| ll
> INT_MAX
) {
807 str_to_long(const char *s
, int base
, long *li
)
810 bool ok
= str_to_llong(s
, base
, &ll
);
812 if (!ok
|| ll
< LONG_MIN
|| ll
> LONG_MAX
) {
821 str_to_llong(const char *s
, int base
, long long *x
)
824 bool ok
= str_to_llong_with_tail(s
, &tail
, base
, x
);
833 str_to_llong_with_tail(const char *s
, char **tail
, int base
, long long *x
)
835 int save_errno
= errno
;
837 *x
= strtoll(s
, tail
, base
);
838 if (errno
== EINVAL
|| errno
== ERANGE
|| *tail
== s
) {
849 str_to_uint(const char *s
, int base
, unsigned int *u
)
852 bool ok
= str_to_llong(s
, base
, &ll
);
853 if (!ok
|| ll
< 0 || ll
> UINT_MAX
) {
863 str_to_ullong(const char *s
, int base
, unsigned long long *x
)
865 int save_errno
= errno
;
869 *x
= strtoull(s
, &tail
, base
);
870 if (errno
== EINVAL
|| errno
== ERANGE
|| tail
== s
|| *tail
!= '\0') {
881 str_to_llong_range(const char *s
, int base
, long long *begin
,
885 if (str_to_llong_with_tail(s
, &tail
, base
, begin
)
887 && str_to_llong(tail
+ 1, base
, end
)) {
895 /* Converts floating-point string 's' into a double. If successful, stores
896 * the double in '*d' and returns true; on failure, stores 0 in '*d' and
899 * Underflow (e.g. "1e-9999") is not considered an error, but overflow
900 * (e.g. "1e9999)" is. */
902 str_to_double(const char *s
, double *d
)
904 int save_errno
= errno
;
907 *d
= strtod(s
, &tail
);
908 if (errno
== EINVAL
|| (errno
== ERANGE
&& *d
!= 0)
909 || tail
== s
|| *tail
!= '\0') {
919 /* Returns the value of 'c' as a hexadecimal digit. */
921 hexit_value(unsigned char c
)
923 static const signed char tbl
[UCHAR_MAX
+ 1] = {
925 ( x >= '0' && x <= '9' ? x - '0' \
926 : x >= 'a' && x <= 'f' ? x - 'a' + 0xa \
927 : x >= 'A' && x <= 'F' ? x - 'A' + 0xa \
929 #define TBL0(x) TBL(x), TBL((x) + 1), TBL((x) + 2), TBL((x) + 3)
930 #define TBL1(x) TBL0(x), TBL0((x) + 4), TBL0((x) + 8), TBL0((x) + 12)
931 #define TBL2(x) TBL1(x), TBL1((x) + 16), TBL1((x) + 32), TBL1((x) + 48)
932 TBL2(0), TBL2(64), TBL2(128), TBL2(192)
938 /* Returns the integer value of the 'n' hexadecimal digits starting at 's', or
939 * UINTMAX_MAX if one of those "digits" is not really a hex digit. Sets '*ok'
940 * to true if the conversion succeeds or to false if a non-hex digit is
943 hexits_value(const char *s
, size_t n
, bool *ok
)
949 for (i
= 0; i
< n
; i
++) {
950 int hexit
= hexit_value(s
[i
]);
955 value
= (value
<< 4) + hexit
;
961 /* Parses the string in 's' as an integer in either hex or decimal format and
962 * puts the result right justified in the array 'valuep' that is 'field_width'
963 * big. If the string is in hex format, the value may be arbitrarily large;
964 * integers are limited to 64-bit values. (The rationale is that decimal is
965 * likely to represent a number and 64 bits is a reasonable maximum whereas
966 * hex could either be a number or a byte string.)
968 * On return 'tail' points to the first character in the string that was
969 * not parsed as part of the value. ERANGE is returned if the value is too
970 * large to fit in the given field. */
972 parse_int_string(const char *s
, uint8_t *valuep
, int field_width
, char **tail
)
974 unsigned long long int integer
;
977 if (!strncmp(s
, "0x", 2) || !strncmp(s
, "0X", 2)) {
984 hexit_str
= xmalloc(field_width
* 2);
990 s
+= strspn(s
, " \t\r\n");
991 hexit
= hexits_value(s
, 1, &ok
);
993 *tail
= CONST_CAST(char *, s
);
997 if (hexit
!= 0 || len
) {
998 if (DIV_ROUND_UP(len
+ 1, 2) > field_width
) {
1003 hexit_str
[len
] = hexit
;
1009 val_idx
= field_width
;
1010 for (i
= len
- 1; i
>= 0; i
-= 2) {
1012 valuep
[val_idx
] = hexit_str
[i
];
1014 valuep
[val_idx
] += hexit_str
[i
- 1] << 4;
1018 memset(valuep
, 0, val_idx
);
1026 integer
= strtoull(s
, tail
, 0);
1027 if (errno
|| s
== *tail
) {
1028 return errno
? errno
: EINVAL
;
1031 for (i
= field_width
- 1; i
>= 0; i
--) {
1032 valuep
[i
] = integer
;
1042 /* Returns the current working directory as a malloc()'d string, or a null
1043 * pointer if the current working directory cannot be determined. */
1050 /* Get maximum path length or at least a reasonable estimate. */
1052 path_max
= pathconf(".", _PC_PATH_MAX
);
1054 path_max
= MAX_PATH
;
1056 size
= (path_max
< 0 ? 1024
1057 : path_max
> 10240 ? 10240
1060 /* Get current working directory. */
1062 char *buf
= xmalloc(size
);
1063 if (getcwd(buf
, size
)) {
1064 return xrealloc(buf
, strlen(buf
) + 1);
1068 if (error
!= ERANGE
) {
1069 VLOG_WARN("getcwd failed (%s)", ovs_strerror(error
));
1078 all_slashes_name(const char *s
)
1080 return xstrdup(s
[0] == '/' && s
[1] == '/' && s
[2] != '/' ? "//"
1086 /* Returns the directory name portion of 'file_name' as a malloc()'d string,
1087 * similar to the POSIX dirname() function but thread-safe. */
1089 dir_name(const char *file_name
)
1091 size_t len
= strlen(file_name
);
1092 while (len
> 0 && file_name
[len
- 1] == '/') {
1095 while (len
> 0 && file_name
[len
- 1] != '/') {
1098 while (len
> 0 && file_name
[len
- 1] == '/') {
1101 return len
? xmemdup0(file_name
, len
) : all_slashes_name(file_name
);
1104 /* Returns the file name portion of 'file_name' as a malloc()'d string,
1105 * similar to the POSIX basename() function but thread-safe. */
1107 base_name(const char *file_name
)
1111 end
= strlen(file_name
);
1112 while (end
> 0 && file_name
[end
- 1] == '/') {
1117 return all_slashes_name(file_name
);
1121 while (start
> 0 && file_name
[start
- 1] != '/') {
1125 return xmemdup0(file_name
+ start
, end
- start
);
1130 is_file_name_absolute(const char *fn
)
1133 /* Use platform specific API */
1134 return !PathIsRelative(fn
);
1136 /* An absolute path begins with /. */
1137 return fn
[0] == '/';
1141 /* If 'file_name' is absolute, returns a copy of 'file_name'. Otherwise,
1142 * returns an absolute path to 'file_name' considering it relative to 'dir',
1143 * which itself must be absolute. 'dir' may be null or the empty string, in
1144 * which case the current working directory is used.
1146 * Returns a null pointer if 'dir' is null and getcwd() fails. */
1148 abs_file_name(const char *dir
, const char *file_name
)
1150 /* If it's already absolute, return a copy. */
1151 if (is_file_name_absolute(file_name
)) {
1152 return xstrdup(file_name
);
1155 /* If a base dir was supplied, use it. We assume, without checking, that
1156 * the base dir is absolute.*/
1157 if (dir
&& dir
[0]) {
1158 char *separator
= dir
[strlen(dir
) - 1] == '/' ? "" : "/";
1159 return xasprintf("%s%s%s", dir
, separator
, file_name
);
1163 /* It's a little complicated to make an absolute path on Windows because a
1164 * relative path might still specify a drive letter. The OS has a function
1165 * to do the job for us, so use it. */
1166 char abs_path
[MAX_PATH
];
1167 DWORD n
= GetFullPathName(file_name
, sizeof abs_path
, abs_path
, NULL
);
1168 return n
> 0 && n
<= sizeof abs_path
? xmemdup0(abs_path
, n
) : NULL
;
1170 /* Outside Windows, do the job ourselves. */
1171 char *cwd
= get_cwd();
1175 char *abs_name
= xasprintf("%s/%s", cwd
, file_name
);
1181 /* Like readlink(), but returns the link name as a null-terminated string in
1182 * allocated memory that the caller must eventually free (with free()).
1183 * Returns NULL on error, in which case errno is set appropriately. */
1185 xreadlink(const char *filename
)
1193 for (size
= 64; ; size
*= 2) {
1194 char *buf
= xmalloc(size
);
1195 ssize_t retval
= readlink(filename
, buf
, size
);
1198 if (retval
>= 0 && retval
< size
) {
1212 /* Returns a version of 'filename' with symlinks in the final component
1213 * dereferenced. This differs from realpath() in that:
1215 * - 'filename' need not exist.
1217 * - If 'filename' does exist as a symlink, its referent need not exist.
1219 * - Only symlinks in the final component of 'filename' are dereferenced.
1221 * For Windows platform, this function returns a string that has the same
1222 * value as the passed string.
1224 * The caller must eventually free the returned string (with free()). */
1226 follow_symlinks(const char *filename
)
1233 fn
= xstrdup(filename
);
1234 for (i
= 0; i
< 10; i
++) {
1238 if (lstat(fn
, &s
) != 0 || !S_ISLNK(s
.st_mode
)) {
1242 linkname
= xreadlink(fn
);
1244 VLOG_WARN("%s: readlink failed (%s)",
1245 filename
, ovs_strerror(errno
));
1249 if (linkname
[0] == '/') {
1250 /* Target of symlink is absolute so use it raw. */
1253 /* Target of symlink is relative so add to 'fn''s directory. */
1254 char *dir
= dir_name(fn
);
1256 if (!strcmp(dir
, ".")) {
1259 char *separator
= dir
[strlen(dir
) - 1] == '/' ? "" : "/";
1260 next_fn
= xasprintf("%s%s%s", dir
, separator
, linkname
);
1271 VLOG_WARN("%s: too many levels of symlinks", filename
);
1274 return xstrdup(filename
);
1277 /* Pass a value to this function if it is marked with
1278 * __attribute__((warn_unused_result)) and you genuinely want to ignore
1279 * its return value. (Note that every scalar type can be implicitly
1280 * converted to bool.) */
1281 void ignore(bool x OVS_UNUSED
) { }
1283 /* Returns an appropriate delimiter for inserting just before the 0-based item
1284 * 'index' in a list that has 'total' items in it. */
1286 english_list_delimiter(size_t index
, size_t total
)
1288 return (index
== 0 ? ""
1289 : index
< total
- 1 ? ", "
1290 : total
> 2 ? ", and "
1294 /* Returns the number of trailing 0-bits in 'n'. Undefined if 'n' == 0. */
1295 #if __GNUC__ >= 4 || _MSC_VER
1296 /* Defined inline in util.h. */
1298 /* Returns the number of trailing 0-bits in 'n'. Undefined if 'n' == 0. */
1305 #define CTZ_STEP(X) \
1322 /* Returns the number of leading 0-bits in 'n'. Undefined if 'n' == 0. */
1324 raw_clz64(uint64_t n
)
1329 #define CLZ_STEP(X) \
1347 #if NEED_COUNT_1BITS_8
1349 ((((X) & (1 << 0)) != 0) + \
1350 (((X) & (1 << 1)) != 0) + \
1351 (((X) & (1 << 2)) != 0) + \
1352 (((X) & (1 << 3)) != 0) + \
1353 (((X) & (1 << 4)) != 0) + \
1354 (((X) & (1 << 5)) != 0) + \
1355 (((X) & (1 << 6)) != 0) + \
1356 (((X) & (1 << 7)) != 0))
1357 #define INIT2(X) INIT1(X), INIT1((X) + 1)
1358 #define INIT4(X) INIT2(X), INIT2((X) + 2)
1359 #define INIT8(X) INIT4(X), INIT4((X) + 4)
1360 #define INIT16(X) INIT8(X), INIT8((X) + 8)
1361 #define INIT32(X) INIT16(X), INIT16((X) + 16)
1362 #define INIT64(X) INIT32(X), INIT32((X) + 32)
1364 const uint8_t count_1bits_8
[256] = {
1365 INIT64(0), INIT64(64), INIT64(128), INIT64(192)
1369 /* Returns true if the 'n' bytes starting at 'p' are 'byte'. */
1371 is_all_byte(const void *p_
, size_t n
, uint8_t byte
)
1373 const uint8_t *p
= p_
;
1376 for (i
= 0; i
< n
; i
++) {
1384 /* Returns true if the 'n' bytes starting at 'p' are zeros. */
1386 is_all_zeros(const void *p
, size_t n
)
1388 return is_all_byte(p
, n
, 0);
1391 /* Returns true if the 'n' bytes starting at 'p' are 0xff. */
1393 is_all_ones(const void *p
, size_t n
)
1395 return is_all_byte(p
, n
, 0xff);
1398 /* *dst |= *src for 'n' bytes. */
1400 or_bytes(void *dst_
, const void *src_
, size_t n
)
1402 const uint8_t *src
= src_
;
1403 uint8_t *dst
= dst_
;
1406 for (i
= 0; i
< n
; i
++) {
1411 /* Copies 'n_bits' bits starting from bit 'src_ofs' in 'src' to the 'n_bits'
1412 * starting from bit 'dst_ofs' in 'dst'. 'src' is 'src_len' bytes long and
1413 * 'dst' is 'dst_len' bytes long.
1415 * If you consider all of 'src' to be a single unsigned integer in network byte
1416 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1417 * with value 1 in src[src_len - 1], bit 1 is the bit with value 2, bit 2 is
1418 * the bit with value 4, ..., bit 8 is the bit with value 1 in src[src_len -
1419 * 2], and so on. Similarly for 'dst'.
1421 * Required invariants:
1422 * src_ofs + n_bits <= src_len * 8
1423 * dst_ofs + n_bits <= dst_len * 8
1424 * 'src' and 'dst' must not overlap.
1427 bitwise_copy(const void *src_
, unsigned int src_len
, unsigned int src_ofs
,
1428 void *dst_
, unsigned int dst_len
, unsigned int dst_ofs
,
1429 unsigned int n_bits
)
1431 const uint8_t *src
= src_
;
1432 uint8_t *dst
= dst_
;
1434 src
+= src_len
- (src_ofs
/ 8 + 1);
1437 dst
+= dst_len
- (dst_ofs
/ 8 + 1);
1440 if (src_ofs
== 0 && dst_ofs
== 0) {
1441 unsigned int n_bytes
= n_bits
/ 8;
1445 memcpy(dst
, src
, n_bytes
);
1452 uint8_t mask
= (1 << n_bits
) - 1;
1453 *dst
= (*dst
& ~mask
) | (*src
& mask
);
1456 while (n_bits
> 0) {
1457 unsigned int max_copy
= 8 - MAX(src_ofs
, dst_ofs
);
1458 unsigned int chunk
= MIN(n_bits
, max_copy
);
1459 uint8_t mask
= ((1 << chunk
) - 1) << dst_ofs
;
1462 *dst
|= ((*src
>> src_ofs
) << dst_ofs
) & mask
;
1479 /* Zeros the 'n_bits' bits starting from bit 'dst_ofs' in 'dst'. 'dst' is
1480 * 'dst_len' bytes long.
1482 * If you consider all of 'dst' to be a single unsigned integer in network byte
1483 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1484 * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
1485 * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
1488 * Required invariant:
1489 * dst_ofs + n_bits <= dst_len * 8
1492 bitwise_zero(void *dst_
, unsigned int dst_len
, unsigned dst_ofs
,
1493 unsigned int n_bits
)
1495 uint8_t *dst
= dst_
;
1501 dst
+= dst_len
- (dst_ofs
/ 8 + 1);
1505 unsigned int chunk
= MIN(n_bits
, 8 - dst_ofs
);
1507 *dst
&= ~(((1 << chunk
) - 1) << dst_ofs
);
1517 while (n_bits
>= 8) {
1523 *dst
&= ~((1 << n_bits
) - 1);
1527 /* Sets to 1 all of the 'n_bits' bits starting from bit 'dst_ofs' in 'dst'.
1528 * 'dst' is 'dst_len' bytes long.
1530 * If you consider all of 'dst' to be a single unsigned integer in network byte
1531 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1532 * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
1533 * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
1536 * Required invariant:
1537 * dst_ofs + n_bits <= dst_len * 8
1540 bitwise_one(void *dst_
, unsigned int dst_len
, unsigned dst_ofs
,
1541 unsigned int n_bits
)
1543 uint8_t *dst
= dst_
;
1549 dst
+= dst_len
- (dst_ofs
/ 8 + 1);
1553 unsigned int chunk
= MIN(n_bits
, 8 - dst_ofs
);
1555 *dst
|= ((1 << chunk
) - 1) << dst_ofs
;
1565 while (n_bits
>= 8) {
1571 *dst
|= (1 << n_bits
) - 1;
1575 /* Scans the 'n_bits' bits starting from bit 'dst_ofs' in 'dst' for 1-bits.
1576 * Returns false if any 1-bits are found, otherwise true. 'dst' is 'dst_len'
1579 * If you consider all of 'dst' to be a single unsigned integer in network byte
1580 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1581 * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
1582 * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
1585 * Required invariant:
1586 * dst_ofs + n_bits <= dst_len * 8
1589 bitwise_is_all_zeros(const void *p_
, unsigned int len
, unsigned int ofs
,
1590 unsigned int n_bits
)
1592 const uint8_t *p
= p_
;
1598 p
+= len
- (ofs
/ 8 + 1);
1602 unsigned int chunk
= MIN(n_bits
, 8 - ofs
);
1604 if (*p
& (((1 << chunk
) - 1) << ofs
)) {
1616 while (n_bits
>= 8) {
1624 if (n_bits
&& *p
& ((1 << n_bits
) - 1)) {
1631 /* Scans the bits in 'p' that have bit offsets 'start' (inclusive) through
1632 * 'end' (exclusive) for the first bit with value 'target'. If one is found,
1633 * returns its offset, otherwise 'end'. 'p' is 'len' bytes long.
1635 * If you consider all of 'p' to be a single unsigned integer in network byte
1636 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1637 * with value 1 in p[len - 1], bit 1 is the bit with value 2, bit 2 is the bit
1638 * with value 4, ..., bit 8 is the bit with value 1 in p[len - 2], and so on.
1640 * Required invariant:
1644 bitwise_scan(const void *p
, unsigned int len
, bool target
, unsigned int start
,
1649 for (ofs
= start
; ofs
< end
; ofs
++) {
1650 if (bitwise_get_bit(p
, len
, ofs
) == target
) {
1657 /* Scans the bits in 'p' that have bit offsets 'start' (inclusive) through
1658 * 'end' (exclusive) for the first bit with value 'target', in reverse order.
1659 * If one is found, returns its offset, otherwise 'end'. 'p' is 'len' bytes
1662 * If you consider all of 'p' to be a single unsigned integer in network byte
1663 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1664 * with value 1 in p[len - 1], bit 1 is the bit with value 2, bit 2 is the bit
1665 * with value 4, ..., bit 8 is the bit with value 1 in p[len - 2], and so on.
1667 * To scan an entire bit array in reverse order, specify start == len * 8 - 1
1668 * and end == -1, in which case the return value is nonnegative if successful
1669 * and -1 if no 'target' match is found.
1671 * Required invariant:
1675 bitwise_rscan(const void *p
, unsigned int len
, bool target
, int start
, int end
)
1677 const uint8_t *s
= p
;
1678 int start_byte
= len
- (start
/ 8 + 1);
1679 int end_byte
= len
- (end
/ 8 + 1);
1684 /* Find the target in the start_byte from starting offset */
1685 ofs_byte
= start_byte
;
1686 the_byte
= s
[ofs_byte
];
1687 for (ofs
= start
% 8; ofs
>= 0; ofs
--) {
1688 if (((the_byte
& (1u << ofs
)) != 0) == target
) {
1693 /* Target not found in start byte, continue searching byte by byte */
1694 for (ofs_byte
= start_byte
+ 1; ofs_byte
<= end_byte
; ofs_byte
++) {
1695 if ((target
&& s
[ofs_byte
])
1696 || (!target
&& (s
[ofs_byte
] != 0xff))) {
1700 if (ofs_byte
> end_byte
) {
1703 the_byte
= s
[ofs_byte
];
1704 /* Target is in the_byte, find it bit by bit */
1705 for (ofs
= 7; ofs
>= 0; ofs
--) {
1706 if (((the_byte
& (1u << ofs
)) != 0) == target
) {
1711 int ret
= (len
- ofs_byte
) * 8 - (8 - ofs
);
1718 /* Copies the 'n_bits' low-order bits of 'value' into the 'n_bits' bits
1719 * starting at bit 'dst_ofs' in 'dst', which is 'dst_len' bytes long.
1721 * If you consider all of 'dst' to be a single unsigned integer in network byte
1722 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1723 * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
1724 * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
1727 * Required invariants:
1728 * dst_ofs + n_bits <= dst_len * 8
1732 bitwise_put(uint64_t value
,
1733 void *dst
, unsigned int dst_len
, unsigned int dst_ofs
,
1734 unsigned int n_bits
)
1736 ovs_be64 n_value
= htonll(value
);
1737 bitwise_copy(&n_value
, sizeof n_value
, 0,
1738 dst
, dst_len
, dst_ofs
,
1742 /* Returns the value of the 'n_bits' bits starting at bit 'src_ofs' in 'src',
1743 * which is 'src_len' bytes long.
1745 * If you consider all of 'src' to be a single unsigned integer in network byte
1746 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1747 * with value 1 in src[src_len - 1], bit 1 is the bit with value 2, bit 2 is
1748 * the bit with value 4, ..., bit 8 is the bit with value 1 in src[src_len -
1751 * Required invariants:
1752 * src_ofs + n_bits <= src_len * 8
1756 bitwise_get(const void *src
, unsigned int src_len
,
1757 unsigned int src_ofs
, unsigned int n_bits
)
1759 ovs_be64 value
= htonll(0);
1761 bitwise_copy(src
, src_len
, src_ofs
,
1762 &value
, sizeof value
, 0,
1764 return ntohll(value
);
1767 /* Returns the value of the bit with offset 'ofs' in 'src', which is 'len'
1770 * If you consider all of 'src' to be a single unsigned integer in network byte
1771 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1772 * with value 1 in src[len - 1], bit 1 is the bit with value 2, bit 2 is the
1773 * bit with value 4, ..., bit 8 is the bit with value 1 in src[len - 2], and so
1776 * Required invariants:
1780 bitwise_get_bit(const void *src_
, unsigned int len
, unsigned int ofs
)
1782 const uint8_t *src
= src_
;
1784 return (src
[len
- (ofs
/ 8 + 1)] & (1u << (ofs
% 8))) != 0;
1787 /* Sets the bit with offset 'ofs' in 'dst', which is 'len' bytes long, to 0.
1789 * If you consider all of 'dst' to be a single unsigned integer in network byte
1790 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1791 * with value 1 in dst[len - 1], bit 1 is the bit with value 2, bit 2 is the
1792 * bit with value 4, ..., bit 8 is the bit with value 1 in dst[len - 2], and so
1795 * Required invariants:
1799 bitwise_put0(void *dst_
, unsigned int len
, unsigned int ofs
)
1801 uint8_t *dst
= dst_
;
1803 dst
[len
- (ofs
/ 8 + 1)] &= ~(1u << (ofs
% 8));
1806 /* Sets the bit with offset 'ofs' in 'dst', which is 'len' bytes long, to 1.
1808 * If you consider all of 'dst' to be a single unsigned integer in network byte
1809 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1810 * with value 1 in dst[len - 1], bit 1 is the bit with value 2, bit 2 is the
1811 * bit with value 4, ..., bit 8 is the bit with value 1 in dst[len - 2], and so
1814 * Required invariants:
1818 bitwise_put1(void *dst_
, unsigned int len
, unsigned int ofs
)
1820 uint8_t *dst
= dst_
;
1822 dst
[len
- (ofs
/ 8 + 1)] |= 1u << (ofs
% 8);
1825 /* Sets the bit with offset 'ofs' in 'dst', which is 'len' bytes long, to 'b'.
1827 * If you consider all of 'dst' to be a single unsigned integer in network byte
1828 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1829 * with value 1 in dst[len - 1], bit 1 is the bit with value 2, bit 2 is the
1830 * bit with value 4, ..., bit 8 is the bit with value 1 in dst[len - 2], and so
1833 * Required invariants:
1837 bitwise_put_bit(void *dst
, unsigned int len
, unsigned int ofs
, bool b
)
1840 bitwise_put1(dst
, len
, ofs
);
1842 bitwise_put0(dst
, len
, ofs
);
1846 /* Flips the bit with offset 'ofs' in 'dst', which is 'len' bytes long.
1848 * If you consider all of 'dst' to be a single unsigned integer in network byte
1849 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1850 * with value 1 in dst[len - 1], bit 1 is the bit with value 2, bit 2 is the
1851 * bit with value 4, ..., bit 8 is the bit with value 1 in dst[len - 2], and so
1854 * Required invariants:
1858 bitwise_toggle_bit(void *dst_
, unsigned int len
, unsigned int ofs
)
1860 uint8_t *dst
= dst_
;
1862 dst
[len
- (ofs
/ 8 + 1)] ^= 1u << (ofs
% 8);
1883 skip_spaces(const char *s
)
1885 while (isspace((unsigned char) *s
)) {
1892 scan_int(const char *s
, const struct scan_spec
*spec
, int base
, va_list *args
)
1894 const char *start
= s
;
1899 negative
= *s
== '-';
1900 s
+= *s
== '-' || *s
== '+';
1902 if ((!base
|| base
== 16) && *s
== '0' && (s
[1] == 'x' || s
[1] == 'X')) {
1906 base
= *s
== '0' ? 8 : 10;
1909 if (s
- start
>= spec
->width
) {
1915 while (s
- start
< spec
->width
) {
1916 int digit
= hexit_value(*s
);
1918 if (digit
< 0 || digit
>= base
) {
1921 value
= value
* base
+ digit
;
1933 switch (spec
->type
) {
1937 *va_arg(*args
, char *) = value
;
1940 *va_arg(*args
, short int *) = value
;
1943 *va_arg(*args
, int *) = value
;
1946 *va_arg(*args
, long int *) = value
;
1949 *va_arg(*args
, long long int *) = value
;
1952 *va_arg(*args
, intmax_t *) = value
;
1954 case SCAN_PTRDIFF_T
:
1955 *va_arg(*args
, ptrdiff_t *) = value
;
1958 *va_arg(*args
, size_t *) = value
;
1965 skip_digits(const char *s
)
1967 while (*s
>= '0' && *s
<= '9') {
1974 scan_float(const char *s
, const struct scan_spec
*spec
, va_list *args
)
1976 const char *start
= s
;
1982 s
+= *s
== '+' || *s
== '-';
1985 s
= skip_digits(s
+ 1);
1987 if (*s
== 'e' || *s
== 'E') {
1989 s
+= *s
== '+' || *s
== '-';
1993 if (s
- start
> spec
->width
) {
1994 s
= start
+ spec
->width
;
1997 copy
= xmemdup0(start
, s
- start
);
1998 value
= strtold(copy
, &tail
);
2005 switch (spec
->type
) {
2009 *va_arg(*args
, float *) = value
;
2012 *va_arg(*args
, double *) = value
;
2015 *va_arg(*args
, long double *) = value
;
2021 case SCAN_PTRDIFF_T
:
2029 scan_output_string(const struct scan_spec
*spec
,
2030 const char *s
, size_t n
,
2033 if (spec
->type
!= SCAN_DISCARD
) {
2034 char *out
= va_arg(*args
, char *);
2041 scan_string(const char *s
, const struct scan_spec
*spec
, va_list *args
)
2045 for (n
= 0; n
< spec
->width
; n
++) {
2046 if (!s
[n
] || isspace((unsigned char) s
[n
])) {
2054 scan_output_string(spec
, s
, n
, args
);
2059 parse_scanset(const char *p_
, unsigned long *set
, bool *complemented
)
2061 const uint8_t *p
= (const uint8_t *) p_
;
2063 *complemented
= *p
== '^';
2067 bitmap_set1(set
, ']');
2071 while (*p
&& *p
!= ']') {
2072 if (p
[1] == '-' && p
[2] != ']' && p
[2] > *p
) {
2073 bitmap_set_multiple(set
, *p
, p
[2] - *p
+ 1, true);
2076 bitmap_set1(set
, *p
++);
2082 return (const char *) p
;
2086 scan_set(const char *s
, const struct scan_spec
*spec
, const char **pp
,
2089 unsigned long set
[BITMAP_N_LONGS(UCHAR_MAX
+ 1)];
2093 /* Parse the scan set. */
2094 memset(set
, 0, sizeof set
);
2095 *pp
= parse_scanset(*pp
, set
, &complemented
);
2097 /* Parse the data. */
2100 && bitmap_is_set(set
, (unsigned char) s
[n
]) == !complemented
2101 && n
< spec
->width
) {
2107 scan_output_string(spec
, s
, n
, args
);
2112 scan_chars(const char *s
, const struct scan_spec
*spec
, va_list *args
)
2114 unsigned int n
= spec
->width
== UINT_MAX
? 1 : spec
->width
;
2116 if (strlen(s
) < n
) {
2119 if (spec
->type
!= SCAN_DISCARD
) {
2120 memcpy(va_arg(*args
, char *), s
, n
);
2126 ovs_scan__(const char *s
, int *n
, const char *format
, va_list *args
)
2128 const char *const start
= s
;
2133 while (*p
!= '\0') {
2134 struct scan_spec spec
;
2135 unsigned char c
= *p
++;
2141 } else if (c
!= '%') {
2147 } else if (*p
== '%') {
2155 /* Parse '*' flag. */
2156 discard
= *p
== '*';
2159 /* Parse field width. */
2161 while (*p
>= '0' && *p
<= '9') {
2162 spec
.width
= spec
.width
* 10 + (*p
++ - '0');
2164 if (spec
.width
== 0) {
2165 spec
.width
= UINT_MAX
;
2168 /* Parse type modifier. */
2172 spec
.type
= SCAN_CHAR
;
2175 spec
.type
= SCAN_SHORT
;
2181 spec
.type
= SCAN_INTMAX_T
;
2187 spec
.type
= SCAN_LLONG
;
2190 spec
.type
= SCAN_LONG
;
2197 spec
.type
= SCAN_LLONG
;
2202 spec
.type
= SCAN_PTRDIFF_T
;
2207 spec
.type
= SCAN_SIZE_T
;
2212 spec
.type
= SCAN_INT
;
2217 spec
.type
= SCAN_DISCARD
;
2221 if (c
!= 'c' && c
!= 'n' && c
!= '[') {
2226 s
= scan_int(s
, &spec
, 10, args
);
2230 s
= scan_int(s
, &spec
, 0, args
);
2234 s
= scan_int(s
, &spec
, 8, args
);
2238 s
= scan_int(s
, &spec
, 10, args
);
2243 s
= scan_int(s
, &spec
, 16, args
);
2251 s
= scan_float(s
, &spec
, args
);
2255 s
= scan_string(s
, &spec
, args
);
2259 s
= scan_set(s
, &spec
, &p
, args
);
2263 s
= scan_chars(s
, &spec
, args
);
2267 if (spec
.type
!= SCAN_DISCARD
) {
2268 *va_arg(*args
, int *) = s
- start
;
2286 /* This is an implementation of the standard sscanf() function, with the
2287 * following exceptions:
2289 * - It returns true if the entire format was successfully scanned and
2290 * converted, false if any conversion failed.
2292 * - The standard doesn't define sscanf() behavior when an out-of-range value
2293 * is scanned, e.g. if a "%"PRIi8 conversion scans "-1" or "0x1ff". Some
2294 * implementations consider this an error and stop scanning. This
2295 * implementation never considers an out-of-range value an error; instead,
2296 * it stores the least-significant bits of the converted value in the
2297 * destination, e.g. the value 255 for both examples earlier.
2299 * - Only single-byte characters are supported, that is, the 'l' modifier
2300 * on %s, %[, and %c is not supported. The GNU extension 'a' modifier is
2301 * also not supported.
2303 * - %p is not supported.
2306 ovs_scan(const char *s
, const char *format
, ...)
2311 va_start(args
, format
);
2312 res
= ovs_scan__(s
, NULL
, format
, &args
);
2318 * This function is similar to ovs_scan(), with an extra parameter `n` added to
2319 * return the number of scanned characters.
2322 ovs_scan_len(const char *s
, int *n
, const char *format
, ...)
2328 va_start(args
, format
);
2329 success
= ovs_scan__(s
+ *n
, &n1
, format
, &args
);
2338 xsleep(unsigned int seconds
)
2340 ovsrcu_quiesce_start();
2342 Sleep(seconds
* 1000);
2346 ovsrcu_quiesce_end();
2349 /* High resolution sleep. */
2351 xnanosleep(uint64_t nanoseconds
)
2353 ovsrcu_quiesce_start();
2356 struct timespec ts_sleep
;
2357 nsec_to_timespec(nanoseconds
, &ts_sleep
);
2361 retval
= nanosleep(&ts_sleep
, NULL
);
2362 error
= retval
< 0 ? errno
: 0;
2363 } while (error
== EINTR
);
2365 HANDLE timer
= CreateWaitableTimer(NULL
, FALSE
, NULL
);
2367 LARGE_INTEGER duetime
;
2368 duetime
.QuadPart
= -nanoseconds
;
2369 if (SetWaitableTimer(timer
, &duetime
, 0, NULL
, NULL
, FALSE
)) {
2370 WaitForSingleObject(timer
, INFINITE
);
2372 VLOG_ERR_ONCE("SetWaitableTimer Failed (%s)",
2373 ovs_lasterror_to_string());
2377 VLOG_ERR_ONCE("CreateWaitableTimer Failed (%s)",
2378 ovs_lasterror_to_string());
2381 ovsrcu_quiesce_end();
2384 /* Determine whether standard output is a tty or not. This is useful to decide
2385 * whether to use color output or not when --color option for utilities is set
2389 is_stdout_a_tty(void)
2391 char const *t
= getenv("TERM");
2392 return (isatty(STDOUT_FILENO
) && t
&& strcmp(t
, "dumb") != 0);
2398 ovs_format_message(int error
)
2400 enum { BUFSIZE
= sizeof strerror_buffer_get()->s
};
2401 char *buffer
= strerror_buffer_get()->s
;
2404 /* See ovs_strerror */
2408 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM
| FORMAT_MESSAGE_IGNORE_INSERTS
,
2409 NULL
, error
, 0, buffer
, BUFSIZE
, NULL
);
2413 /* Returns a null-terminated string that explains the last error.
2414 * Use this function to get the error string for WINAPI calls. */
2416 ovs_lasterror_to_string(void)
2418 return ovs_format_message(GetLastError());
2422 ftruncate(int fd
, off_t length
)
2426 error
= _chsize_s(fd
, length
);
2433 OVS_CONSTRUCTOR(winsock_start
) {
2437 error
= WSAStartup(MAKEWORD(2, 2), &wsaData
);
2439 VLOG_FATAL("WSAStartup failed: %s", sock_strerror(sock_errno()));