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 /* Buffer used by ovs_strerror() and ovs_format_message(). */
67 DEFINE_STATIC_PER_THREAD_DATA(struct { char s
[128]; },
71 static char *xreadlink(const char *filename
);
74 ovs_assert_failure(const char *where
, const char *function
,
75 const char *condition
)
77 /* Prevent an infinite loop (or stack overflow) in case VLOG_ABORT happens
78 * to trigger an assertion failure of its own. */
79 static int reentry
= 0;
83 VLOG_ABORT("%s: assertion %s failed in %s()",
84 where
, condition
, function
);
88 fprintf(stderr
, "%s: assertion %s failed in %s()",
89 where
, condition
, function
);
100 ovs_abort(0, "virtual memory exhausted");
104 xcalloc(size_t count
, size_t size
)
106 void *p
= count
&& size
? calloc(count
, size
) : malloc(1);
107 COVERAGE_INC(util_xalloc
);
117 return xcalloc(1, size
);
123 void *p
= malloc(size
? size
: 1);
124 COVERAGE_INC(util_xalloc
);
132 xrealloc(void *p
, size_t size
)
134 p
= realloc(p
, size
? size
: 1);
135 COVERAGE_INC(util_xalloc
);
143 xmemdup(const void *p_
, size_t size
)
145 void *p
= xmalloc(size
);
146 nullable_memcpy(p
, p_
, size
);
151 xmemdup0(const char *p_
, size_t length
)
153 char *p
= xmalloc(length
+ 1);
154 memcpy(p
, p_
, length
);
160 xstrdup(const char *s
)
162 return xmemdup0(s
, strlen(s
));
166 nullable_xstrdup(const char *s
)
168 return s
? xstrdup(s
) : NULL
;
172 nullable_string_is_equal(const char *a
, const char *b
)
174 return a
? b
&& !strcmp(a
, b
) : !b
;
178 xvasprintf(const char *format
, va_list args
)
184 va_copy(args2
, args
);
185 needed
= vsnprintf(NULL
, 0, format
, args
);
187 s
= xmalloc(needed
+ 1);
189 vsnprintf(s
, needed
+ 1, format
, args2
);
196 x2nrealloc(void *p
, size_t *n
, size_t s
)
198 *n
= *n
== 0 ? 1 : 2 * *n
;
199 return xrealloc(p
, *n
* s
);
202 /* Allocates and returns 'size' bytes of memory aligned to a cache line and in
203 * dedicated cache lines. That is, the memory block returned will not share a
204 * cache line with other data, avoiding "false sharing".
206 * Use free_cacheline() to free the returned memory block. */
208 xmalloc_cacheline(size_t size
)
210 #ifdef HAVE_POSIX_MEMALIGN
214 COVERAGE_INC(util_xalloc
);
215 error
= posix_memalign(&p
, CACHE_LINE_SIZE
, size
? size
: 1);
221 /* Allocate room for:
223 * - Header padding: Up to CACHE_LINE_SIZE - 1 bytes, to allow the
224 * pointer to be aligned exactly sizeof(void *) bytes before the
225 * beginning of a cache line.
227 * - Pointer: A pointer to the start of the header padding, to allow us
228 * to free() the block later.
230 * - User data: 'size' bytes.
232 * - Trailer padding: Enough to bring the user data up to a cache line
235 * +---------------+---------+------------------------+---------+
236 * | header | pointer | user data | trailer |
237 * +---------------+---------+------------------------+---------+
243 void *p
= xmalloc((CACHE_LINE_SIZE
- 1)
245 + ROUND_UP(size
, CACHE_LINE_SIZE
));
246 bool runt
= PAD_SIZE((uintptr_t) p
, CACHE_LINE_SIZE
) < sizeof(void *);
247 void *r
= (void *) ROUND_UP((uintptr_t) p
+ (runt
? CACHE_LINE_SIZE
: 0),
249 void **q
= (void **) r
- 1;
255 /* Like xmalloc_cacheline() but clears the allocated memory to all zero
258 xzalloc_cacheline(size_t size
)
260 void *p
= xmalloc_cacheline(size
);
265 /* Frees a memory block allocated with xmalloc_cacheline() or
266 * xzalloc_cacheline(). */
268 free_cacheline(void *p
)
270 #ifdef HAVE_POSIX_MEMALIGN
274 void **q
= (void **) p
- 1;
281 xasprintf(const char *format
, ...)
286 va_start(args
, format
);
287 s
= xvasprintf(format
, args
);
293 /* Similar to strlcpy() from OpenBSD, but it never reads more than 'size - 1'
294 * bytes from 'src' and doesn't return anything. */
296 ovs_strlcpy(char *dst
, const char *src
, size_t size
)
299 size_t len
= strnlen(src
, size
- 1);
300 memcpy(dst
, src
, len
);
305 /* Copies 'src' to 'dst'. Reads no more than 'size - 1' bytes from 'src'.
306 * Always null-terminates 'dst' (if 'size' is nonzero), and writes a zero byte
307 * to every otherwise unused byte in 'dst'.
309 * Except for performance, the following call:
310 * ovs_strzcpy(dst, src, size);
311 * is equivalent to these two calls:
312 * memset(dst, '\0', size);
313 * ovs_strlcpy(dst, src, size);
315 * (Thus, ovs_strzcpy() is similar to strncpy() without some of the pitfalls.)
318 ovs_strzcpy(char *dst
, const char *src
, size_t size
)
321 size_t len
= strnlen(src
, size
- 1);
322 memcpy(dst
, src
, len
);
323 memset(dst
+ len
, '\0', size
- len
);
328 * Returns true if 'str' ends with given 'suffix'.
331 string_ends_with(const char *str
, const char *suffix
)
333 int str_len
= strlen(str
);
334 int suffix_len
= strlen(suffix
);
336 return (str_len
>= suffix_len
) &&
337 (0 == strcmp(str
+ (str_len
- suffix_len
), suffix
));
340 /* Prints 'format' on stderr, formatting it like printf() does. If 'err_no' is
341 * nonzero, then it is formatted with ovs_retval_to_string() and appended to
342 * the message inside parentheses. Then, terminates with abort().
344 * This function is preferred to ovs_fatal() in a situation where it would make
345 * sense for a monitoring process to restart the daemon.
347 * 'format' should not end with a new-line, because this function will add one
350 ovs_abort(int err_no
, const char *format
, ...)
354 va_start(args
, format
);
355 ovs_abort_valist(err_no
, format
, args
);
358 /* Same as ovs_abort() except that the arguments are supplied as a va_list. */
360 ovs_abort_valist(int err_no
, const char *format
, va_list args
)
362 ovs_error_valist(err_no
, format
, args
);
366 /* Prints 'format' on stderr, formatting it like printf() does. If 'err_no' is
367 * nonzero, then it is formatted with ovs_retval_to_string() and appended to
368 * the message inside parentheses. Then, terminates with EXIT_FAILURE.
370 * 'format' should not end with a new-line, because this function will add one
373 ovs_fatal(int err_no
, const char *format
, ...)
377 va_start(args
, format
);
378 ovs_fatal_valist(err_no
, format
, args
);
381 /* Same as ovs_fatal() except that the arguments are supplied as a va_list. */
383 ovs_fatal_valist(int err_no
, const char *format
, va_list args
)
385 ovs_error_valist(err_no
, format
, args
);
389 /* Prints 'format' on stderr, formatting it like printf() does. If 'err_no' is
390 * nonzero, then it is formatted with ovs_retval_to_string() and appended to
391 * the message inside parentheses.
393 * 'format' should not end with a new-line, because this function will add one
396 ovs_error(int err_no
, const char *format
, ...)
400 va_start(args
, format
);
401 ovs_error_valist(err_no
, format
, args
);
405 /* Same as ovs_error() except that the arguments are supplied as a va_list. */
407 ovs_error_valist(int err_no
, const char *format
, va_list args
)
409 const char *subprogram_name
= get_subprogram_name();
410 int save_errno
= errno
;
412 if (subprogram_name
[0]) {
413 fprintf(stderr
, "%s(%s): ", program_name
, subprogram_name
);
415 fprintf(stderr
, "%s: ", program_name
);
418 vfprintf(stderr
, format
, args
);
420 fprintf(stderr
, " (%s)", ovs_retval_to_string(err_no
));
427 /* Many OVS functions return an int which is one of:
430 * - EOF: end of file (not necessarily an error; depends on the function called)
432 * Returns the appropriate human-readable string. The caller must copy the
433 * string if it wants to hold onto it, as the storage may be overwritten on
434 * subsequent function calls.
437 ovs_retval_to_string(int retval
)
440 : retval
== EOF
? "End of file"
441 : ovs_strerror(retval
));
444 /* This function returns the string describing the error number in 'error'
445 * for POSIX platforms. For Windows, this function can be used for C library
446 * calls. For socket calls that are also used in Windows, use sock_strerror()
447 * instead. For WINAPI calls, look at ovs_lasterror_to_string(). */
449 ovs_strerror(int error
)
451 enum { BUFSIZE
= sizeof strerror_buffer_get()->s
};
458 * strerror(0) varies among platforms:
464 * We want to provide a consistent result here because
465 * our testsuite has test cases which strictly matches
466 * log messages containing this string.
472 buffer
= strerror_buffer_get()->s
;
474 #if STRERROR_R_CHAR_P
475 /* GNU style strerror_r() might return an immutable static string, or it
476 * might write and return 'buffer', but in either case we can pass the
477 * returned string directly to the caller. */
478 s
= strerror_r(error
, buffer
, BUFSIZE
);
479 #else /* strerror_r() returns an int. */
481 if (strerror_r(error
, buffer
, BUFSIZE
)) {
482 /* strerror_r() is only allowed to fail on ERANGE (because the buffer
483 * is too short). We don't check the actual failure reason because
484 * POSIX requires strerror_r() to return the error but old glibc
485 * (before 2.13) returns -1 and sets errno. */
486 snprintf(buffer
, BUFSIZE
, "Unknown error %d", error
);
495 /* Sets global "program_name" and "program_version" variables. Should
496 * be called at the beginning of main() with "argv[0]" as the argument
499 * 'version' should contain the version of the caller's program. If 'version'
500 * is the same as the VERSION #define, the caller is assumed to be part of Open
501 * vSwitch. Otherwise, it is assumed to be an external program linking against
502 * the Open vSwitch libraries.
506 ovs_set_program_name(const char *argv0
, const char *version
)
510 size_t max_len
= strlen(argv0
) + 1;
512 SetErrorMode(GetErrorMode() | SEM_NOGPFAULTERRORBOX
);
514 /* This function is deprecated from 1900 (Visual Studio 2015) */
515 _set_output_format(_TWO_DIGIT_EXPONENT
);
518 basename
= xmalloc(max_len
);
519 _splitpath_s(argv0
, NULL
, 0, NULL
, 0, basename
, max_len
, NULL
, 0);
521 const char *slash
= strrchr(argv0
, '/');
522 basename
= xstrdup(slash
? slash
+ 1 : argv0
);
525 assert_single_threaded();
527 /* Remove libtool prefix, if it is there */
528 if (strncmp(basename
, "lt-", 3) == 0) {
529 char *tmp_name
= basename
;
530 basename
= xstrdup(basename
+ 3);
533 program_name
= basename
;
535 free(program_version
);
536 if (!strcmp(version
, VERSION
)) {
537 program_version
= xasprintf("%s (Open vSwitch) "VERSION
"\n",
540 program_version
= xasprintf("%s %s\n"
541 "Open vSwitch Library "VERSION
"\n",
542 program_name
, version
);
546 /* Returns the name of the currently running thread or process. */
548 get_subprogram_name(void)
550 const char *name
= subprogram_name_get();
551 return name
? name
: "";
554 /* Sets 'subprogram_name' as the name of the currently running thread or
555 * process. (This appears in log messages and may also be visible in system
556 * process listings and debuggers.) */
558 set_subprogram_name(const char *subprogram_name
)
560 char *pname
= xstrdup(subprogram_name
? subprogram_name
: program_name
);
561 free(subprogram_name_set(pname
));
563 #if HAVE_GLIBC_PTHREAD_SETNAME_NP
564 pthread_setname_np(pthread_self(), pname
);
565 #elif HAVE_NETBSD_PTHREAD_SETNAME_NP
566 pthread_setname_np(pthread_self(), "%s", pname
);
567 #elif HAVE_PTHREAD_SET_NAME_NP
568 pthread_set_name_np(pthread_self(), pname
);
575 static unsigned int cached
;
579 long int value
= sysconf(_SC_PAGESIZE
);
583 GetSystemInfo(&sysinfo
);
584 value
= sysinfo
.dwPageSize
;
594 /* Returns the time at which the system booted, as the number of milliseconds
595 * since the epoch, or 0 if the time of boot cannot be determined. */
599 static long long int cache_expiration
= LLONG_MIN
;
600 static long long int boot_time
;
604 if (time_msec() >= cache_expiration
) {
605 static const char stat_file
[] = "/proc/stat";
609 cache_expiration
= time_msec() + 5 * 1000;
611 stream
= fopen(stat_file
, "r");
613 VLOG_ERR_ONCE("%s: open failed (%s)",
614 stat_file
, ovs_strerror(errno
));
618 while (fgets(line
, sizeof line
, stream
)) {
620 if (ovs_scan(line
, "btime %lld", &btime
)) {
621 boot_time
= btime
* 1000;
625 VLOG_ERR_ONCE("%s: btime not found", stat_file
);
632 /* This is a wrapper for setting timeout in control utils.
633 * The value of OVS_CTL_TIMEOUT environment variable will be used by
634 * default if 'secs' is not specified. */
636 ctl_timeout_setup(unsigned int secs
)
639 char *env
= getenv("OVS_CTL_TIMEOUT");
642 str_to_uint(env
, 10, &secs
);
650 /* Returns a pointer to a string describing the program version. The
651 * caller must not modify or free the returned string.
654 ovs_get_program_version(void)
656 return program_version
;
659 /* Returns a pointer to a string describing the program name. The
660 * caller must not modify or free the returned string.
663 ovs_get_program_name(void)
668 /* Print the version information for the program. */
670 ovs_print_version(uint8_t min_ofp
, uint8_t max_ofp
)
672 printf("%s", program_version
);
673 if (min_ofp
|| max_ofp
) {
674 printf("OpenFlow versions %#x:%#x\n", min_ofp
, max_ofp
);
678 /* Writes the 'size' bytes in 'buf' to 'stream' as hex bytes arranged 16 per
679 * line. Numeric offsets are also included, starting at 'ofs' for the first
680 * byte in 'buf'. If 'ascii' is true then the corresponding ASCII characters
681 * are also rendered alongside. */
683 ovs_hex_dump(FILE *stream
, const void *buf_
, size_t size
,
684 uintptr_t ofs
, bool ascii
)
686 const uint8_t *buf
= buf_
;
687 const size_t per_line
= 16; /* Maximum bytes per line. */
692 /* Number of bytes on this line. */
693 size_t start
= ofs
% per_line
;
694 size_t end
= per_line
;
695 if (end
- start
> size
) {
698 size_t n
= end
- start
;
701 fprintf(stream
, "%08"PRIxMAX
" ",
702 (uintmax_t) ROUND_DOWN(ofs
, per_line
));
703 for (i
= 0; i
< start
; i
++) {
704 fprintf(stream
, " ");
706 for (; i
< end
; i
++) {
707 fprintf(stream
, "%c%02x",
708 i
== per_line
/ 2 ? '-' : ' ', buf
[i
- start
]);
711 fprintf(stream
, " ");
712 for (; i
< per_line
; i
++) {
713 fprintf(stream
, " ");
715 fprintf(stream
, "|");
716 for (i
= 0; i
< start
; i
++) {
717 fprintf(stream
, " ");
719 for (; i
< end
; i
++) {
720 int c
= buf
[i
- start
];
721 putc(c
>= 32 && c
< 127 ? c
: '.', stream
);
723 for (; i
< per_line
; i
++) {
724 fprintf(stream
, " ");
726 fprintf(stream
, "|");
728 fprintf(stream
, "\n");
737 str_to_int(const char *s
, int base
, int *i
)
740 bool ok
= str_to_llong(s
, base
, &ll
);
742 if (!ok
|| ll
< INT_MIN
|| ll
> INT_MAX
) {
751 str_to_long(const char *s
, int base
, long *li
)
754 bool ok
= str_to_llong(s
, base
, &ll
);
756 if (!ok
|| ll
< LONG_MIN
|| ll
> LONG_MAX
) {
765 str_to_llong(const char *s
, int base
, long long *x
)
768 bool ok
= str_to_llong_with_tail(s
, &tail
, base
, x
);
777 str_to_llong_with_tail(const char *s
, char **tail
, int base
, long long *x
)
779 int save_errno
= errno
;
781 *x
= strtoll(s
, tail
, base
);
782 if (errno
== EINVAL
|| errno
== ERANGE
|| *tail
== s
) {
793 str_to_uint(const char *s
, int base
, unsigned int *u
)
796 bool ok
= str_to_llong(s
, base
, &ll
);
797 if (!ok
|| ll
< 0 || ll
> UINT_MAX
) {
807 str_to_ullong(const char *s
, int base
, unsigned long long *x
)
809 int save_errno
= errno
;
813 *x
= strtoull(s
, &tail
, base
);
814 if (errno
== EINVAL
|| errno
== ERANGE
|| tail
== s
|| *tail
!= '\0') {
825 str_to_llong_range(const char *s
, int base
, long long *begin
,
829 if (str_to_llong_with_tail(s
, &tail
, base
, begin
)
831 && str_to_llong(tail
+ 1, base
, end
)) {
839 /* Converts floating-point string 's' into a double. If successful, stores
840 * the double in '*d' and returns true; on failure, stores 0 in '*d' and
843 * Underflow (e.g. "1e-9999") is not considered an error, but overflow
844 * (e.g. "1e9999)" is. */
846 str_to_double(const char *s
, double *d
)
848 int save_errno
= errno
;
851 *d
= strtod(s
, &tail
);
852 if (errno
== EINVAL
|| (errno
== ERANGE
&& *d
!= 0)
853 || tail
== s
|| *tail
!= '\0') {
863 /* Returns the value of 'c' as a hexadecimal digit. */
865 hexit_value(unsigned char c
)
867 static const signed char tbl
[UCHAR_MAX
+ 1] = {
869 ( x >= '0' && x <= '9' ? x - '0' \
870 : x >= 'a' && x <= 'f' ? x - 'a' + 0xa \
871 : x >= 'A' && x <= 'F' ? x - 'A' + 0xa \
873 #define TBL0(x) TBL(x), TBL((x) + 1), TBL((x) + 2), TBL((x) + 3)
874 #define TBL1(x) TBL0(x), TBL0((x) + 4), TBL0((x) + 8), TBL0((x) + 12)
875 #define TBL2(x) TBL1(x), TBL1((x) + 16), TBL1((x) + 32), TBL1((x) + 48)
876 TBL2(0), TBL2(64), TBL2(128), TBL2(192)
882 /* Returns the integer value of the 'n' hexadecimal digits starting at 's', or
883 * UINTMAX_MAX if one of those "digits" is not really a hex digit. Sets '*ok'
884 * to true if the conversion succeeds or to false if a non-hex digit is
887 hexits_value(const char *s
, size_t n
, bool *ok
)
893 for (i
= 0; i
< n
; i
++) {
894 int hexit
= hexit_value(s
[i
]);
899 value
= (value
<< 4) + hexit
;
905 /* Parses the string in 's' as an integer in either hex or decimal format and
906 * puts the result right justified in the array 'valuep' that is 'field_width'
907 * big. If the string is in hex format, the value may be arbitrarily large;
908 * integers are limited to 64-bit values. (The rationale is that decimal is
909 * likely to represent a number and 64 bits is a reasonable maximum whereas
910 * hex could either be a number or a byte string.)
912 * On return 'tail' points to the first character in the string that was
913 * not parsed as part of the value. ERANGE is returned if the value is too
914 * large to fit in the given field. */
916 parse_int_string(const char *s
, uint8_t *valuep
, int field_width
, char **tail
)
918 unsigned long long int integer
;
921 if (!strncmp(s
, "0x", 2) || !strncmp(s
, "0X", 2)) {
928 hexit_str
= xmalloc(field_width
* 2);
934 s
+= strspn(s
, " \t\r\n");
935 hexit
= hexits_value(s
, 1, &ok
);
937 *tail
= CONST_CAST(char *, s
);
941 if (hexit
!= 0 || len
) {
942 if (DIV_ROUND_UP(len
+ 1, 2) > field_width
) {
947 hexit_str
[len
] = hexit
;
953 val_idx
= field_width
;
954 for (i
= len
- 1; i
>= 0; i
-= 2) {
956 valuep
[val_idx
] = hexit_str
[i
];
958 valuep
[val_idx
] += hexit_str
[i
- 1] << 4;
962 memset(valuep
, 0, val_idx
);
970 integer
= strtoull(s
, tail
, 0);
971 if (errno
|| s
== *tail
) {
972 return errno
? errno
: EINVAL
;
975 for (i
= field_width
- 1; i
>= 0; i
--) {
986 /* Returns the current working directory as a malloc()'d string, or a null
987 * pointer if the current working directory cannot be determined. */
994 /* Get maximum path length or at least a reasonable estimate. */
996 path_max
= pathconf(".", _PC_PATH_MAX
);
1000 size
= (path_max
< 0 ? 1024
1001 : path_max
> 10240 ? 10240
1004 /* Get current working directory. */
1006 char *buf
= xmalloc(size
);
1007 if (getcwd(buf
, size
)) {
1008 return xrealloc(buf
, strlen(buf
) + 1);
1012 if (error
!= ERANGE
) {
1013 VLOG_WARN("getcwd failed (%s)", ovs_strerror(error
));
1022 all_slashes_name(const char *s
)
1024 return xstrdup(s
[0] == '/' && s
[1] == '/' && s
[2] != '/' ? "//"
1030 /* Returns the directory name portion of 'file_name' as a malloc()'d string,
1031 * similar to the POSIX dirname() function but thread-safe. */
1033 dir_name(const char *file_name
)
1035 size_t len
= strlen(file_name
);
1036 while (len
> 0 && file_name
[len
- 1] == '/') {
1039 while (len
> 0 && file_name
[len
- 1] != '/') {
1042 while (len
> 0 && file_name
[len
- 1] == '/') {
1045 return len
? xmemdup0(file_name
, len
) : all_slashes_name(file_name
);
1048 /* Returns the file name portion of 'file_name' as a malloc()'d string,
1049 * similar to the POSIX basename() function but thread-safe. */
1051 base_name(const char *file_name
)
1055 end
= strlen(file_name
);
1056 while (end
> 0 && file_name
[end
- 1] == '/') {
1061 return all_slashes_name(file_name
);
1065 while (start
> 0 && file_name
[start
- 1] != '/') {
1069 return xmemdup0(file_name
+ start
, end
- start
);
1074 is_file_name_absolute(const char *fn
)
1077 /* Use platform specific API */
1078 return !PathIsRelative(fn
);
1080 /* An absolute path begins with /. */
1081 return fn
[0] == '/';
1085 /* If 'file_name' is absolute, returns a copy of 'file_name'. Otherwise,
1086 * returns an absolute path to 'file_name' considering it relative to 'dir',
1087 * which itself must be absolute. 'dir' may be null or the empty string, in
1088 * which case the current working directory is used.
1090 * Returns a null pointer if 'dir' is null and getcwd() fails. */
1092 abs_file_name(const char *dir
, const char *file_name
)
1094 /* If it's already absolute, return a copy. */
1095 if (is_file_name_absolute(file_name
)) {
1096 return xstrdup(file_name
);
1099 /* If a base dir was supplied, use it. We assume, without checking, that
1100 * the base dir is absolute.*/
1101 if (dir
&& dir
[0]) {
1102 char *separator
= dir
[strlen(dir
) - 1] == '/' ? "" : "/";
1103 return xasprintf("%s%s%s", dir
, separator
, file_name
);
1107 /* It's a little complicated to make an absolute path on Windows because a
1108 * relative path might still specify a drive letter. The OS has a function
1109 * to do the job for us, so use it. */
1110 char abs_path
[MAX_PATH
];
1111 DWORD n
= GetFullPathName(file_name
, sizeof abs_path
, abs_path
, NULL
);
1112 return n
> 0 && n
<= sizeof abs_path
? xmemdup0(abs_path
, n
) : NULL
;
1114 /* Outside Windows, do the job ourselves. */
1115 char *cwd
= get_cwd();
1119 char *abs_name
= xasprintf("%s/%s", cwd
, file_name
);
1125 /* Like readlink(), but returns the link name as a null-terminated string in
1126 * allocated memory that the caller must eventually free (with free()).
1127 * Returns NULL on error, in which case errno is set appropriately. */
1129 xreadlink(const char *filename
)
1137 for (size
= 64; ; size
*= 2) {
1138 char *buf
= xmalloc(size
);
1139 ssize_t retval
= readlink(filename
, buf
, size
);
1142 if (retval
>= 0 && retval
< size
) {
1156 /* Returns a version of 'filename' with symlinks in the final component
1157 * dereferenced. This differs from realpath() in that:
1159 * - 'filename' need not exist.
1161 * - If 'filename' does exist as a symlink, its referent need not exist.
1163 * - Only symlinks in the final component of 'filename' are dereferenced.
1165 * For Windows platform, this function returns a string that has the same
1166 * value as the passed string.
1168 * The caller must eventually free the returned string (with free()). */
1170 follow_symlinks(const char *filename
)
1177 fn
= xstrdup(filename
);
1178 for (i
= 0; i
< 10; i
++) {
1182 if (lstat(fn
, &s
) != 0 || !S_ISLNK(s
.st_mode
)) {
1186 linkname
= xreadlink(fn
);
1188 VLOG_WARN("%s: readlink failed (%s)",
1189 filename
, ovs_strerror(errno
));
1193 if (linkname
[0] == '/') {
1194 /* Target of symlink is absolute so use it raw. */
1197 /* Target of symlink is relative so add to 'fn''s directory. */
1198 char *dir
= dir_name(fn
);
1200 if (!strcmp(dir
, ".")) {
1203 char *separator
= dir
[strlen(dir
) - 1] == '/' ? "" : "/";
1204 next_fn
= xasprintf("%s%s%s", dir
, separator
, linkname
);
1215 VLOG_WARN("%s: too many levels of symlinks", filename
);
1218 return xstrdup(filename
);
1221 /* Pass a value to this function if it is marked with
1222 * __attribute__((warn_unused_result)) and you genuinely want to ignore
1223 * its return value. (Note that every scalar type can be implicitly
1224 * converted to bool.) */
1225 void ignore(bool x OVS_UNUSED
) { }
1227 /* Returns an appropriate delimiter for inserting just before the 0-based item
1228 * 'index' in a list that has 'total' items in it. */
1230 english_list_delimiter(size_t index
, size_t total
)
1232 return (index
== 0 ? ""
1233 : index
< total
- 1 ? ", "
1234 : total
> 2 ? ", and "
1238 /* Returns the number of trailing 0-bits in 'n'. Undefined if 'n' == 0. */
1239 #if __GNUC__ >= 4 || _MSC_VER
1240 /* Defined inline in util.h. */
1242 /* Returns the number of trailing 0-bits in 'n'. Undefined if 'n' == 0. */
1249 #define CTZ_STEP(X) \
1266 /* Returns the number of leading 0-bits in 'n'. Undefined if 'n' == 0. */
1268 raw_clz64(uint64_t n
)
1273 #define CLZ_STEP(X) \
1291 #if NEED_COUNT_1BITS_8
1293 ((((X) & (1 << 0)) != 0) + \
1294 (((X) & (1 << 1)) != 0) + \
1295 (((X) & (1 << 2)) != 0) + \
1296 (((X) & (1 << 3)) != 0) + \
1297 (((X) & (1 << 4)) != 0) + \
1298 (((X) & (1 << 5)) != 0) + \
1299 (((X) & (1 << 6)) != 0) + \
1300 (((X) & (1 << 7)) != 0))
1301 #define INIT2(X) INIT1(X), INIT1((X) + 1)
1302 #define INIT4(X) INIT2(X), INIT2((X) + 2)
1303 #define INIT8(X) INIT4(X), INIT4((X) + 4)
1304 #define INIT16(X) INIT8(X), INIT8((X) + 8)
1305 #define INIT32(X) INIT16(X), INIT16((X) + 16)
1306 #define INIT64(X) INIT32(X), INIT32((X) + 32)
1308 const uint8_t count_1bits_8
[256] = {
1309 INIT64(0), INIT64(64), INIT64(128), INIT64(192)
1313 /* Returns true if the 'n' bytes starting at 'p' are 'byte'. */
1315 is_all_byte(const void *p_
, size_t n
, uint8_t byte
)
1317 const uint8_t *p
= p_
;
1320 for (i
= 0; i
< n
; i
++) {
1328 /* Returns true if the 'n' bytes starting at 'p' are zeros. */
1330 is_all_zeros(const void *p
, size_t n
)
1332 return is_all_byte(p
, n
, 0);
1335 /* Returns true if the 'n' bytes starting at 'p' are 0xff. */
1337 is_all_ones(const void *p
, size_t n
)
1339 return is_all_byte(p
, n
, 0xff);
1342 /* Copies 'n_bits' bits starting from bit 'src_ofs' in 'src' to the 'n_bits'
1343 * starting from bit 'dst_ofs' in 'dst'. 'src' is 'src_len' bytes long and
1344 * 'dst' is 'dst_len' bytes long.
1346 * If you consider all of 'src' to be a single unsigned integer in network byte
1347 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1348 * with value 1 in src[src_len - 1], bit 1 is the bit with value 2, bit 2 is
1349 * the bit with value 4, ..., bit 8 is the bit with value 1 in src[src_len -
1350 * 2], and so on. Similarly for 'dst'.
1352 * Required invariants:
1353 * src_ofs + n_bits <= src_len * 8
1354 * dst_ofs + n_bits <= dst_len * 8
1355 * 'src' and 'dst' must not overlap.
1358 bitwise_copy(const void *src_
, unsigned int src_len
, unsigned int src_ofs
,
1359 void *dst_
, unsigned int dst_len
, unsigned int dst_ofs
,
1360 unsigned int n_bits
)
1362 const uint8_t *src
= src_
;
1363 uint8_t *dst
= dst_
;
1365 src
+= src_len
- (src_ofs
/ 8 + 1);
1368 dst
+= dst_len
- (dst_ofs
/ 8 + 1);
1371 if (src_ofs
== 0 && dst_ofs
== 0) {
1372 unsigned int n_bytes
= n_bits
/ 8;
1376 memcpy(dst
, src
, n_bytes
);
1383 uint8_t mask
= (1 << n_bits
) - 1;
1384 *dst
= (*dst
& ~mask
) | (*src
& mask
);
1387 while (n_bits
> 0) {
1388 unsigned int max_copy
= 8 - MAX(src_ofs
, dst_ofs
);
1389 unsigned int chunk
= MIN(n_bits
, max_copy
);
1390 uint8_t mask
= ((1 << chunk
) - 1) << dst_ofs
;
1393 *dst
|= ((*src
>> src_ofs
) << dst_ofs
) & mask
;
1410 /* Zeros the 'n_bits' bits starting from bit 'dst_ofs' in 'dst'. 'dst' is
1411 * 'dst_len' bytes long.
1413 * If you consider all of 'dst' to be a single unsigned integer in network byte
1414 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1415 * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
1416 * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
1419 * Required invariant:
1420 * dst_ofs + n_bits <= dst_len * 8
1423 bitwise_zero(void *dst_
, unsigned int dst_len
, unsigned dst_ofs
,
1424 unsigned int n_bits
)
1426 uint8_t *dst
= dst_
;
1432 dst
+= dst_len
- (dst_ofs
/ 8 + 1);
1436 unsigned int chunk
= MIN(n_bits
, 8 - dst_ofs
);
1438 *dst
&= ~(((1 << chunk
) - 1) << dst_ofs
);
1448 while (n_bits
>= 8) {
1454 *dst
&= ~((1 << n_bits
) - 1);
1458 /* Sets to 1 all of the 'n_bits' bits starting from bit 'dst_ofs' in 'dst'.
1459 * 'dst' is 'dst_len' bytes long.
1461 * If you consider all of 'dst' to be a single unsigned integer in network byte
1462 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1463 * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
1464 * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
1467 * Required invariant:
1468 * dst_ofs + n_bits <= dst_len * 8
1471 bitwise_one(void *dst_
, unsigned int dst_len
, unsigned dst_ofs
,
1472 unsigned int n_bits
)
1474 uint8_t *dst
= dst_
;
1480 dst
+= dst_len
- (dst_ofs
/ 8 + 1);
1484 unsigned int chunk
= MIN(n_bits
, 8 - dst_ofs
);
1486 *dst
|= ((1 << chunk
) - 1) << dst_ofs
;
1496 while (n_bits
>= 8) {
1502 *dst
|= (1 << n_bits
) - 1;
1506 /* Scans the 'n_bits' bits starting from bit 'dst_ofs' in 'dst' for 1-bits.
1507 * Returns false if any 1-bits are found, otherwise true. 'dst' is 'dst_len'
1510 * If you consider all of 'dst' to be a single unsigned integer in network byte
1511 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1512 * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
1513 * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
1516 * Required invariant:
1517 * dst_ofs + n_bits <= dst_len * 8
1520 bitwise_is_all_zeros(const void *p_
, unsigned int len
, unsigned int ofs
,
1521 unsigned int n_bits
)
1523 const uint8_t *p
= p_
;
1529 p
+= len
- (ofs
/ 8 + 1);
1533 unsigned int chunk
= MIN(n_bits
, 8 - ofs
);
1535 if (*p
& (((1 << chunk
) - 1) << ofs
)) {
1547 while (n_bits
>= 8) {
1555 if (n_bits
&& *p
& ((1 << n_bits
) - 1)) {
1562 /* Scans the bits in 'p' that have bit offsets 'start' (inclusive) through
1563 * 'end' (exclusive) for the first bit with value 'target'. If one is found,
1564 * returns its offset, otherwise 'end'. 'p' is 'len' bytes long.
1566 * If you consider all of 'p' to be a single unsigned integer in network byte
1567 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1568 * with value 1 in p[len - 1], bit 1 is the bit with value 2, bit 2 is the bit
1569 * with value 4, ..., bit 8 is the bit with value 1 in p[len - 2], and so on.
1571 * Required invariant:
1575 bitwise_scan(const void *p
, unsigned int len
, bool target
, unsigned int start
,
1580 for (ofs
= start
; ofs
< end
; ofs
++) {
1581 if (bitwise_get_bit(p
, len
, ofs
) == target
) {
1588 /* Scans the bits in 'p' that have bit offsets 'start' (inclusive) through
1589 * 'end' (exclusive) for the first bit with value 'target', in reverse order.
1590 * If one is found, returns its offset, otherwise 'end'. 'p' is 'len' bytes
1593 * If you consider all of 'p' to be a single unsigned integer in network byte
1594 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1595 * with value 1 in p[len - 1], bit 1 is the bit with value 2, bit 2 is the bit
1596 * with value 4, ..., bit 8 is the bit with value 1 in p[len - 2], and so on.
1598 * To scan an entire bit array in reverse order, specify start == len * 8 - 1
1599 * and end == -1, in which case the return value is nonnegative if successful
1600 * and -1 if no 'target' match is found.
1602 * Required invariant:
1606 bitwise_rscan(const void *p
, unsigned int len
, bool target
, int start
, int end
)
1608 const uint8_t *s
= p
;
1609 int start_byte
= len
- (start
/ 8 + 1);
1610 int end_byte
= len
- (end
/ 8 + 1);
1615 /* Find the target in the start_byte from starting offset */
1616 ofs_byte
= start_byte
;
1617 the_byte
= s
[ofs_byte
];
1618 for (ofs
= start
% 8; ofs
>= 0; ofs
--) {
1619 if (((the_byte
& (1u << ofs
)) != 0) == target
) {
1624 /* Target not found in start byte, continue searching byte by byte */
1625 for (ofs_byte
= start_byte
+ 1; ofs_byte
<= end_byte
; ofs_byte
++) {
1626 if ((target
&& s
[ofs_byte
])
1627 || (!target
&& (s
[ofs_byte
] != 0xff))) {
1631 if (ofs_byte
> end_byte
) {
1634 the_byte
= s
[ofs_byte
];
1635 /* Target is in the_byte, find it bit by bit */
1636 for (ofs
= 7; ofs
>= 0; ofs
--) {
1637 if (((the_byte
& (1u << ofs
)) != 0) == target
) {
1642 int ret
= (len
- ofs_byte
) * 8 - (8 - ofs
);
1649 /* Copies the 'n_bits' low-order bits of 'value' into the 'n_bits' bits
1650 * starting at bit 'dst_ofs' in 'dst', which is 'dst_len' bytes long.
1652 * If you consider all of 'dst' to be a single unsigned integer in network byte
1653 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1654 * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
1655 * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
1658 * Required invariants:
1659 * dst_ofs + n_bits <= dst_len * 8
1663 bitwise_put(uint64_t value
,
1664 void *dst
, unsigned int dst_len
, unsigned int dst_ofs
,
1665 unsigned int n_bits
)
1667 ovs_be64 n_value
= htonll(value
);
1668 bitwise_copy(&n_value
, sizeof n_value
, 0,
1669 dst
, dst_len
, dst_ofs
,
1673 /* Returns the value of the 'n_bits' bits starting at bit 'src_ofs' in 'src',
1674 * which is 'src_len' bytes long.
1676 * If you consider all of 'src' to be a single unsigned integer in network byte
1677 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1678 * with value 1 in src[src_len - 1], bit 1 is the bit with value 2, bit 2 is
1679 * the bit with value 4, ..., bit 8 is the bit with value 1 in src[src_len -
1682 * Required invariants:
1683 * src_ofs + n_bits <= src_len * 8
1687 bitwise_get(const void *src
, unsigned int src_len
,
1688 unsigned int src_ofs
, unsigned int n_bits
)
1690 ovs_be64 value
= htonll(0);
1692 bitwise_copy(src
, src_len
, src_ofs
,
1693 &value
, sizeof value
, 0,
1695 return ntohll(value
);
1698 /* Returns the value of the bit with offset 'ofs' in 'src', which is 'len'
1701 * If you consider all of 'src' to be a single unsigned integer in network byte
1702 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1703 * with value 1 in src[len - 1], bit 1 is the bit with value 2, bit 2 is the
1704 * bit with value 4, ..., bit 8 is the bit with value 1 in src[len - 2], and so
1707 * Required invariants:
1711 bitwise_get_bit(const void *src_
, unsigned int len
, unsigned int ofs
)
1713 const uint8_t *src
= src_
;
1715 return (src
[len
- (ofs
/ 8 + 1)] & (1u << (ofs
% 8))) != 0;
1718 /* Sets the bit with offset 'ofs' in 'dst', which is 'len' bytes long, to 0.
1720 * If you consider all of 'dst' to be a single unsigned integer in network byte
1721 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1722 * with value 1 in dst[len - 1], bit 1 is the bit with value 2, bit 2 is the
1723 * bit with value 4, ..., bit 8 is the bit with value 1 in dst[len - 2], and so
1726 * Required invariants:
1730 bitwise_put0(void *dst_
, unsigned int len
, unsigned int ofs
)
1732 uint8_t *dst
= dst_
;
1734 dst
[len
- (ofs
/ 8 + 1)] &= ~(1u << (ofs
% 8));
1737 /* Sets the bit with offset 'ofs' in 'dst', which is 'len' bytes long, to 1.
1739 * If you consider all of 'dst' to be a single unsigned integer in network byte
1740 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1741 * with value 1 in dst[len - 1], bit 1 is the bit with value 2, bit 2 is the
1742 * bit with value 4, ..., bit 8 is the bit with value 1 in dst[len - 2], and so
1745 * Required invariants:
1749 bitwise_put1(void *dst_
, unsigned int len
, unsigned int ofs
)
1751 uint8_t *dst
= dst_
;
1753 dst
[len
- (ofs
/ 8 + 1)] |= 1u << (ofs
% 8);
1756 /* Sets the bit with offset 'ofs' in 'dst', which is 'len' bytes long, to 'b'.
1758 * If you consider all of 'dst' to be a single unsigned integer in network byte
1759 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1760 * with value 1 in dst[len - 1], bit 1 is the bit with value 2, bit 2 is the
1761 * bit with value 4, ..., bit 8 is the bit with value 1 in dst[len - 2], and so
1764 * Required invariants:
1768 bitwise_put_bit(void *dst
, unsigned int len
, unsigned int ofs
, bool b
)
1771 bitwise_put1(dst
, len
, ofs
);
1773 bitwise_put0(dst
, len
, ofs
);
1777 /* Flips the bit with offset 'ofs' in 'dst', which is 'len' bytes long.
1779 * If you consider all of 'dst' to be a single unsigned integer in network byte
1780 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1781 * with value 1 in dst[len - 1], bit 1 is the bit with value 2, bit 2 is the
1782 * bit with value 4, ..., bit 8 is the bit with value 1 in dst[len - 2], and so
1785 * Required invariants:
1789 bitwise_toggle_bit(void *dst_
, unsigned int len
, unsigned int ofs
)
1791 uint8_t *dst
= dst_
;
1793 dst
[len
- (ofs
/ 8 + 1)] ^= 1u << (ofs
% 8);
1814 skip_spaces(const char *s
)
1816 while (isspace((unsigned char) *s
)) {
1823 scan_int(const char *s
, const struct scan_spec
*spec
, int base
, va_list *args
)
1825 const char *start
= s
;
1830 negative
= *s
== '-';
1831 s
+= *s
== '-' || *s
== '+';
1833 if ((!base
|| base
== 16) && *s
== '0' && (s
[1] == 'x' || s
[1] == 'X')) {
1837 base
= *s
== '0' ? 8 : 10;
1840 if (s
- start
>= spec
->width
) {
1846 while (s
- start
< spec
->width
) {
1847 int digit
= hexit_value(*s
);
1849 if (digit
< 0 || digit
>= base
) {
1852 value
= value
* base
+ digit
;
1864 switch (spec
->type
) {
1868 *va_arg(*args
, char *) = value
;
1871 *va_arg(*args
, short int *) = value
;
1874 *va_arg(*args
, int *) = value
;
1877 *va_arg(*args
, long int *) = value
;
1880 *va_arg(*args
, long long int *) = value
;
1883 *va_arg(*args
, intmax_t *) = value
;
1885 case SCAN_PTRDIFF_T
:
1886 *va_arg(*args
, ptrdiff_t *) = value
;
1889 *va_arg(*args
, size_t *) = value
;
1896 skip_digits(const char *s
)
1898 while (*s
>= '0' && *s
<= '9') {
1905 scan_float(const char *s
, const struct scan_spec
*spec
, va_list *args
)
1907 const char *start
= s
;
1913 s
+= *s
== '+' || *s
== '-';
1916 s
= skip_digits(s
+ 1);
1918 if (*s
== 'e' || *s
== 'E') {
1920 s
+= *s
== '+' || *s
== '-';
1924 if (s
- start
> spec
->width
) {
1925 s
= start
+ spec
->width
;
1928 copy
= xmemdup0(start
, s
- start
);
1929 value
= strtold(copy
, &tail
);
1936 switch (spec
->type
) {
1940 *va_arg(*args
, float *) = value
;
1943 *va_arg(*args
, double *) = value
;
1946 *va_arg(*args
, long double *) = value
;
1952 case SCAN_PTRDIFF_T
:
1960 scan_output_string(const struct scan_spec
*spec
,
1961 const char *s
, size_t n
,
1964 if (spec
->type
!= SCAN_DISCARD
) {
1965 char *out
= va_arg(*args
, char *);
1972 scan_string(const char *s
, const struct scan_spec
*spec
, va_list *args
)
1976 for (n
= 0; n
< spec
->width
; n
++) {
1977 if (!s
[n
] || isspace((unsigned char) s
[n
])) {
1985 scan_output_string(spec
, s
, n
, args
);
1990 parse_scanset(const char *p_
, unsigned long *set
, bool *complemented
)
1992 const uint8_t *p
= (const uint8_t *) p_
;
1994 *complemented
= *p
== '^';
1998 bitmap_set1(set
, ']');
2002 while (*p
&& *p
!= ']') {
2003 if (p
[1] == '-' && p
[2] != ']' && p
[2] > *p
) {
2004 bitmap_set_multiple(set
, *p
, p
[2] - *p
+ 1, true);
2007 bitmap_set1(set
, *p
++);
2013 return (const char *) p
;
2017 scan_set(const char *s
, const struct scan_spec
*spec
, const char **pp
,
2020 unsigned long set
[BITMAP_N_LONGS(UCHAR_MAX
+ 1)];
2024 /* Parse the scan set. */
2025 memset(set
, 0, sizeof set
);
2026 *pp
= parse_scanset(*pp
, set
, &complemented
);
2028 /* Parse the data. */
2031 && bitmap_is_set(set
, (unsigned char) s
[n
]) == !complemented
2032 && n
< spec
->width
) {
2038 scan_output_string(spec
, s
, n
, args
);
2043 scan_chars(const char *s
, const struct scan_spec
*spec
, va_list *args
)
2045 unsigned int n
= spec
->width
== UINT_MAX
? 1 : spec
->width
;
2047 if (strlen(s
) < n
) {
2050 if (spec
->type
!= SCAN_DISCARD
) {
2051 memcpy(va_arg(*args
, char *), s
, n
);
2057 ovs_scan__(const char *s
, int *n
, const char *format
, va_list *args
)
2059 const char *const start
= s
;
2064 while (*p
!= '\0') {
2065 struct scan_spec spec
;
2066 unsigned char c
= *p
++;
2072 } else if (c
!= '%') {
2078 } else if (*p
== '%') {
2086 /* Parse '*' flag. */
2087 discard
= *p
== '*';
2090 /* Parse field width. */
2092 while (*p
>= '0' && *p
<= '9') {
2093 spec
.width
= spec
.width
* 10 + (*p
++ - '0');
2095 if (spec
.width
== 0) {
2096 spec
.width
= UINT_MAX
;
2099 /* Parse type modifier. */
2103 spec
.type
= SCAN_CHAR
;
2106 spec
.type
= SCAN_SHORT
;
2112 spec
.type
= SCAN_INTMAX_T
;
2118 spec
.type
= SCAN_LLONG
;
2121 spec
.type
= SCAN_LONG
;
2128 spec
.type
= SCAN_LLONG
;
2133 spec
.type
= SCAN_PTRDIFF_T
;
2138 spec
.type
= SCAN_SIZE_T
;
2143 spec
.type
= SCAN_INT
;
2148 spec
.type
= SCAN_DISCARD
;
2152 if (c
!= 'c' && c
!= 'n' && c
!= '[') {
2157 s
= scan_int(s
, &spec
, 10, args
);
2161 s
= scan_int(s
, &spec
, 0, args
);
2165 s
= scan_int(s
, &spec
, 8, args
);
2169 s
= scan_int(s
, &spec
, 10, args
);
2174 s
= scan_int(s
, &spec
, 16, args
);
2182 s
= scan_float(s
, &spec
, args
);
2186 s
= scan_string(s
, &spec
, args
);
2190 s
= scan_set(s
, &spec
, &p
, args
);
2194 s
= scan_chars(s
, &spec
, args
);
2198 if (spec
.type
!= SCAN_DISCARD
) {
2199 *va_arg(*args
, int *) = s
- start
;
2217 /* This is an implementation of the standard sscanf() function, with the
2218 * following exceptions:
2220 * - It returns true if the entire format was successfully scanned and
2221 * converted, false if any conversion failed.
2223 * - The standard doesn't define sscanf() behavior when an out-of-range value
2224 * is scanned, e.g. if a "%"PRIi8 conversion scans "-1" or "0x1ff". Some
2225 * implementations consider this an error and stop scanning. This
2226 * implementation never considers an out-of-range value an error; instead,
2227 * it stores the least-significant bits of the converted value in the
2228 * destination, e.g. the value 255 for both examples earlier.
2230 * - Only single-byte characters are supported, that is, the 'l' modifier
2231 * on %s, %[, and %c is not supported. The GNU extension 'a' modifier is
2232 * also not supported.
2234 * - %p is not supported.
2237 ovs_scan(const char *s
, const char *format
, ...)
2242 va_start(args
, format
);
2243 res
= ovs_scan__(s
, NULL
, format
, &args
);
2249 * This function is similar to ovs_scan(), with an extra parameter `n` added to
2250 * return the number of scanned characters.
2253 ovs_scan_len(const char *s
, int *n
, const char *format
, ...)
2259 va_start(args
, format
);
2260 success
= ovs_scan__(s
+ *n
, &n1
, format
, &args
);
2269 xsleep(unsigned int seconds
)
2271 ovsrcu_quiesce_start();
2273 Sleep(seconds
* 1000);
2277 ovsrcu_quiesce_end();
2280 /* High resolution sleep. */
2282 xnanosleep(uint64_t nanoseconds
)
2284 ovsrcu_quiesce_start();
2287 struct timespec ts_sleep
;
2288 nsec_to_timespec(nanoseconds
, &ts_sleep
);
2292 retval
= nanosleep(&ts_sleep
, NULL
);
2293 error
= retval
< 0 ? errno
: 0;
2294 } while (error
== EINTR
);
2296 HANDLE timer
= CreateWaitableTimer(NULL
, FALSE
, NULL
);
2298 LARGE_INTEGER duetime
;
2299 duetime
.QuadPart
= -nanoseconds
;
2300 if (SetWaitableTimer(timer
, &duetime
, 0, NULL
, NULL
, FALSE
)) {
2301 WaitForSingleObject(timer
, INFINITE
);
2303 VLOG_ERR_ONCE("SetWaitableTimer Failed (%s)",
2304 ovs_lasterror_to_string());
2308 VLOG_ERR_ONCE("CreateWaitableTimer Failed (%s)",
2309 ovs_lasterror_to_string());
2312 ovsrcu_quiesce_end();
2315 /* Determine whether standard output is a tty or not. This is useful to decide
2316 * whether to use color output or not when --color option for utilities is set
2320 is_stdout_a_tty(void)
2322 char const *t
= getenv("TERM");
2323 return (isatty(STDOUT_FILENO
) && t
&& strcmp(t
, "dumb") != 0);
2329 ovs_format_message(int error
)
2331 enum { BUFSIZE
= sizeof strerror_buffer_get()->s
};
2332 char *buffer
= strerror_buffer_get()->s
;
2335 /* See ovs_strerror */
2339 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM
| FORMAT_MESSAGE_IGNORE_INSERTS
,
2340 NULL
, error
, 0, buffer
, BUFSIZE
, NULL
);
2344 /* Returns a null-terminated string that explains the last error.
2345 * Use this function to get the error string for WINAPI calls. */
2347 ovs_lasterror_to_string(void)
2349 return ovs_format_message(GetLastError());
2353 ftruncate(int fd
, off_t length
)
2357 error
= _chsize_s(fd
, length
);
2364 OVS_CONSTRUCTOR(winsock_start
) {
2368 error
= WSAStartup(MAKEWORD(2, 2), &wsaData
);
2370 VLOG_FATAL("WSAStartup failed: %s", sock_strerror(sock_errno()));