]> git.proxmox.com Git - mirror_ovs.git/blob - lib/util.c
netdev-offload-tc: Use single 'once' variable for probing tc features
[mirror_ovs.git] / lib / util.c
1 /*
2 * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016 Nicira, Inc.
3 *
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:
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
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.
15 */
16
17 #include <config.h>
18 #include "util.h"
19 #include <ctype.h>
20 #include <errno.h>
21 #include <limits.h>
22 #include <pthread.h>
23 #include <stdarg.h>
24 #include <stdint.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <sys/stat.h>
29 #include <unistd.h>
30 #include "bitmap.h"
31 #include "byte-order.h"
32 #include "coverage.h"
33 #include "ovs-rcu.h"
34 #include "ovs-thread.h"
35 #include "socket-util.h"
36 #include "timeval.h"
37 #include "openvswitch/vlog.h"
38 #ifdef HAVE_PTHREAD_SET_NAME_NP
39 #include <pthread_np.h>
40 #endif
41 #ifdef _WIN32
42 #include <shlwapi.h>
43 #endif
44
45 VLOG_DEFINE_THIS_MODULE(util);
46
47 #ifdef __linux__
48 #define LINUX 1
49 #include <asm/param.h>
50 #else
51 #define LINUX 0
52 #endif
53
54 COVERAGE_DEFINE(util_xalloc);
55
56 /* argv[0] without directory names. */
57 char *program_name;
58
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);
62
63 /* --version option output. */
64 static char *program_version;
65
66 /* 'true' if mlockall() succeeded. */
67 static bool is_memory_locked = false;
68
69 /* Buffer used by ovs_strerror() and ovs_format_message(). */
70 DEFINE_STATIC_PER_THREAD_DATA(struct { char s[128]; },
71 strerror_buffer,
72 { "" });
73
74 static char *xreadlink(const char *filename);
75
76 void
77 ovs_assert_failure(const char *where, const char *function,
78 const char *condition)
79 {
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;
83
84 switch (reentry++) {
85 case 0:
86 VLOG_ABORT("%s: assertion %s failed in %s()",
87 where, condition, function);
88 OVS_NOT_REACHED();
89
90 case 1:
91 fprintf(stderr, "%s: assertion %s failed in %s()",
92 where, condition, function);
93 abort();
94
95 default:
96 abort();
97 }
98 }
99
100 void
101 set_memory_locked(void)
102 {
103 is_memory_locked = true;
104 }
105
106 bool
107 memory_locked(void)
108 {
109 return is_memory_locked;
110 }
111
112 void
113 out_of_memory(void)
114 {
115 ovs_abort(0, "virtual memory exhausted");
116 }
117
118 void *
119 xcalloc(size_t count, size_t size)
120 {
121 void *p = count && size ? calloc(count, size) : malloc(1);
122 COVERAGE_INC(util_xalloc);
123 if (p == NULL) {
124 out_of_memory();
125 }
126 return p;
127 }
128
129 void *
130 xzalloc(size_t size)
131 {
132 return xcalloc(1, size);
133 }
134
135 void *
136 xmalloc(size_t size)
137 {
138 void *p = malloc(size ? size : 1);
139 COVERAGE_INC(util_xalloc);
140 if (p == NULL) {
141 out_of_memory();
142 }
143 return p;
144 }
145
146 void *
147 xrealloc(void *p, size_t size)
148 {
149 p = realloc(p, size ? size : 1);
150 COVERAGE_INC(util_xalloc);
151 if (p == NULL) {
152 out_of_memory();
153 }
154 return p;
155 }
156
157 void *
158 xmemdup(const void *p_, size_t size)
159 {
160 void *p = xmalloc(size);
161 nullable_memcpy(p, p_, size);
162 return p;
163 }
164
165 char *
166 xmemdup0(const char *p_, size_t length)
167 {
168 char *p = xmalloc(length + 1);
169 memcpy(p, p_, length);
170 p[length] = '\0';
171 return p;
172 }
173
174 char *
175 xstrdup(const char *s)
176 {
177 return xmemdup0(s, strlen(s));
178 }
179
180 char * MALLOC_LIKE
181 nullable_xstrdup(const char *s)
182 {
183 return s ? xstrdup(s) : NULL;
184 }
185
186 bool
187 nullable_string_is_equal(const char *a, const char *b)
188 {
189 return a ? b && !strcmp(a, b) : !b;
190 }
191
192 char *
193 xvasprintf(const char *format, va_list args)
194 {
195 va_list args2;
196 size_t needed;
197 char *s;
198
199 va_copy(args2, args);
200 needed = vsnprintf(NULL, 0, format, args);
201
202 s = xmalloc(needed + 1);
203
204 vsnprintf(s, needed + 1, format, args2);
205 va_end(args2);
206
207 return s;
208 }
209
210 void *
211 x2nrealloc(void *p, size_t *n, size_t s)
212 {
213 *n = *n == 0 ? 1 : 2 * *n;
214 return xrealloc(p, *n * s);
215 }
216
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 *).
219 *
220 * Use free_size_align() to free the returned memory block. */
221 void *
222 xmalloc_size_align(size_t size, size_t alignment)
223 {
224 #ifdef HAVE_POSIX_MEMALIGN
225 void *p;
226 int error;
227
228 COVERAGE_INC(util_xalloc);
229 error = posix_memalign(&p, alignment, size ? size : 1);
230 if (error != 0) {
231 out_of_memory();
232 }
233 return p;
234 #else
235 /* Allocate room for:
236 *
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.
240 *
241 * - Pointer: A pointer to the start of the header padding, to allow us
242 * to free() the block later.
243 *
244 * - User data: 'size' bytes.
245 *
246 * - Trailer padding: Enough to bring the user data up to a alignment
247 * multiple.
248 *
249 * +---------------+---------+------------------------+---------+
250 * | header | pointer | user data | trailer |
251 * +---------------+---------+------------------------+---------+
252 * ^ ^ ^
253 * | | |
254 * p q r
255 *
256 */
257 void *p, *r, **q;
258 bool runt;
259
260 if (!IS_POW2(alignment) || (alignment % sizeof(void *) != 0)) {
261 ovs_abort(0, "Invalid alignment");
262 }
263
264 p = xmalloc((alignment - 1)
265 + sizeof(void *)
266 + ROUND_UP(size, alignment));
267
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'
272 * below.
273 */
274 r = (void *) ROUND_UP((uintptr_t) p + (runt ? alignment : 0), alignment);
275 q = (void **) r - 1;
276 *q = p;
277
278 return r;
279 #endif
280 }
281
282 void
283 free_size_align(void *p)
284 {
285 #ifdef HAVE_POSIX_MEMALIGN
286 free(p);
287 #else
288 if (p) {
289 void **q = (void **) p - 1;
290 free(*q);
291 }
292 #endif
293 }
294
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".
298 *
299 * Use free_cacheline() to free the returned memory block. */
300 void *
301 xmalloc_cacheline(size_t size)
302 {
303 return xmalloc_size_align(size, CACHE_LINE_SIZE);
304 }
305
306 /* Like xmalloc_cacheline() but clears the allocated memory to all zero
307 * bytes. */
308 void *
309 xzalloc_cacheline(size_t size)
310 {
311 void *p = xmalloc_cacheline(size);
312 memset(p, 0, size);
313 return p;
314 }
315
316 /* Frees a memory block allocated with xmalloc_cacheline() or
317 * xzalloc_cacheline(). */
318 void
319 free_cacheline(void *p)
320 {
321 free_size_align(p);
322 }
323
324 void *
325 xmalloc_pagealign(size_t size)
326 {
327 return xmalloc_size_align(size, get_page_size());
328 }
329
330 void
331 free_pagealign(void *p)
332 {
333 free_size_align(p);
334 }
335
336 char *
337 xasprintf(const char *format, ...)
338 {
339 va_list args;
340 char *s;
341
342 va_start(args, format);
343 s = xvasprintf(format, args);
344 va_end(args);
345
346 return s;
347 }
348
349 /* Similar to strlcpy() from OpenBSD, but it never reads more than 'size - 1'
350 * bytes from 'src' and doesn't return anything. */
351 void
352 ovs_strlcpy(char *dst, const char *src, size_t size)
353 {
354 if (size > 0) {
355 size_t len = strnlen(src, size - 1);
356 memcpy(dst, src, len);
357 dst[len] = '\0';
358 }
359 }
360
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'.
364 *
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);
370 *
371 * (Thus, ovs_strzcpy() is similar to strncpy() without some of the pitfalls.)
372 */
373 void
374 ovs_strzcpy(char *dst, const char *src, size_t size)
375 {
376 if (size > 0) {
377 size_t len = strnlen(src, size - 1);
378 memcpy(dst, src, len);
379 memset(dst + len, '\0', size - len);
380 }
381 }
382
383 /*
384 * Returns true if 'str' ends with given 'suffix'.
385 */
386 int
387 string_ends_with(const char *str, const char *suffix)
388 {
389 int str_len = strlen(str);
390 int suffix_len = strlen(suffix);
391
392 return (str_len >= suffix_len) &&
393 (0 == strcmp(str + (str_len - suffix_len), suffix));
394 }
395
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().
399 *
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.
402 *
403 * 'format' should not end with a new-line, because this function will add one
404 * itself. */
405 void
406 ovs_abort(int err_no, const char *format, ...)
407 {
408 va_list args;
409
410 va_start(args, format);
411 ovs_abort_valist(err_no, format, args);
412 }
413
414 /* Same as ovs_abort() except that the arguments are supplied as a va_list. */
415 void
416 ovs_abort_valist(int err_no, const char *format, va_list args)
417 {
418 ovs_error_valist(err_no, format, args);
419 abort();
420 }
421
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.
425 *
426 * 'format' should not end with a new-line, because this function will add one
427 * itself. */
428 void
429 ovs_fatal(int err_no, const char *format, ...)
430 {
431 va_list args;
432
433 va_start(args, format);
434 ovs_fatal_valist(err_no, format, args);
435 }
436
437 /* Same as ovs_fatal() except that the arguments are supplied as a va_list. */
438 void
439 ovs_fatal_valist(int err_no, const char *format, va_list args)
440 {
441 ovs_error_valist(err_no, format, args);
442 exit(EXIT_FAILURE);
443 }
444
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.
448 *
449 * 'format' should not end with a new-line, because this function will add one
450 * itself. */
451 void
452 ovs_error(int err_no, const char *format, ...)
453 {
454 va_list args;
455
456 va_start(args, format);
457 ovs_error_valist(err_no, format, args);
458 va_end(args);
459 }
460
461 /* Same as ovs_error() except that the arguments are supplied as a va_list. */
462 void
463 ovs_error_valist(int err_no, const char *format, va_list args)
464 {
465 const char *subprogram_name = get_subprogram_name();
466 int save_errno = errno;
467
468 if (subprogram_name[0]) {
469 fprintf(stderr, "%s(%s): ", program_name, subprogram_name);
470 } else {
471 fprintf(stderr, "%s: ", program_name);
472 }
473
474 vfprintf(stderr, format, args);
475 if (err_no != 0) {
476 fprintf(stderr, " (%s)", ovs_retval_to_string(err_no));
477 }
478 putc('\n', stderr);
479
480 errno = save_errno;
481 }
482
483 /* Many OVS functions return an int which is one of:
484 * - 0: no error yet
485 * - >0: errno value
486 * - EOF: end of file (not necessarily an error; depends on the function called)
487 *
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.
491 */
492 const char *
493 ovs_retval_to_string(int retval)
494 {
495 return (!retval ? ""
496 : retval == EOF ? "End of file"
497 : ovs_strerror(retval));
498 }
499
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(). */
504 const char *
505 ovs_strerror(int error)
506 {
507 enum { BUFSIZE = sizeof strerror_buffer_get()->s };
508 int save_errno;
509 char *buffer;
510 char *s;
511
512 if (error == 0) {
513 /*
514 * strerror(0) varies among platforms:
515 *
516 * Success
517 * No error
518 * Undefined error: 0
519 *
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.
523 */
524 return "Success";
525 }
526
527 save_errno = errno;
528 buffer = strerror_buffer_get()->s;
529
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. */
536 s = buffer;
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);
543 }
544 #endif
545
546 errno = save_errno;
547
548 return s;
549 }
550
551 /* Sets global "program_name" and "program_version" variables. Should
552 * be called at the beginning of main() with "argv[0]" as the argument
553 * to 'argv0'.
554 *
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.
559 *
560 */
561 void
562 ovs_set_program_name(const char *argv0, const char *version)
563 {
564 char *basename;
565 #ifdef _WIN32
566 size_t max_len = strlen(argv0) + 1;
567
568 SetErrorMode(GetErrorMode() | SEM_NOGPFAULTERRORBOX);
569 #if _MSC_VER < 1900
570 /* This function is deprecated from 1900 (Visual Studio 2015) */
571 _set_output_format(_TWO_DIGIT_EXPONENT);
572 #endif
573
574 basename = xmalloc(max_len);
575 _splitpath_s(argv0, NULL, 0, NULL, 0, basename, max_len, NULL, 0);
576 #else
577 const char *slash = strrchr(argv0, '/');
578 basename = xstrdup(slash ? slash + 1 : argv0);
579 #endif
580
581 assert_single_threaded();
582 free(program_name);
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);
587 free(tmp_name);
588 }
589 program_name = basename;
590
591 free(program_version);
592 if (!strcmp(version, VERSION)) {
593 program_version = xasprintf("%s (Open vSwitch) "VERSION"\n",
594 program_name);
595 } else {
596 program_version = xasprintf("%s %s\n"
597 "Open vSwitch Library "VERSION"\n",
598 program_name, version);
599 }
600 }
601
602 /* Returns the name of the currently running thread or process. */
603 const char *
604 get_subprogram_name(void)
605 {
606 const char *name = subprogram_name_get();
607 return name ? name : "";
608 }
609
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.) */
613 void
614 set_subprogram_name(const char *subprogram_name)
615 {
616 char *pname = xstrdup(subprogram_name ? subprogram_name : program_name);
617 free(subprogram_name_set(pname));
618
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);
625 #endif
626 }
627
628 unsigned int
629 get_page_size(void)
630 {
631 static unsigned int cached;
632
633 if (!cached) {
634 #ifndef _WIN32
635 long int value = sysconf(_SC_PAGESIZE);
636 #else
637 long int value;
638 SYSTEM_INFO sysinfo;
639 GetSystemInfo(&sysinfo);
640 value = sysinfo.dwPageSize;
641 #endif
642 if (value >= 0) {
643 cached = value;
644 }
645 }
646
647 return cached;
648 }
649
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. */
652 long long int
653 get_boot_time(void)
654 {
655 static long long int cache_expiration = LLONG_MIN;
656 static long long int boot_time;
657
658 ovs_assert(LINUX);
659
660 if (time_msec() >= cache_expiration) {
661 static const char stat_file[] = "/proc/stat";
662 char line[128];
663 FILE *stream;
664
665 cache_expiration = time_msec() + 5 * 1000;
666
667 stream = fopen(stat_file, "r");
668 if (!stream) {
669 VLOG_ERR_ONCE("%s: open failed (%s)",
670 stat_file, ovs_strerror(errno));
671 return boot_time;
672 }
673
674 while (fgets(line, sizeof line, stream)) {
675 long long int btime;
676 if (ovs_scan(line, "btime %lld", &btime)) {
677 boot_time = btime * 1000;
678 goto done;
679 }
680 }
681 VLOG_ERR_ONCE("%s: btime not found", stat_file);
682 done:
683 fclose(stream);
684 }
685 return boot_time;
686 }
687
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. */
691 void
692 ctl_timeout_setup(unsigned int secs)
693 {
694 if (!secs) {
695 char *env = getenv("OVS_CTL_TIMEOUT");
696
697 if (env && env[0]) {
698 str_to_uint(env, 10, &secs);
699 }
700 }
701 if (secs) {
702 time_alarm(secs);
703 }
704 }
705
706 /* Returns a pointer to a string describing the program version. The
707 * caller must not modify or free the returned string.
708 */
709 const char *
710 ovs_get_program_version(void)
711 {
712 return program_version;
713 }
714
715 /* Returns a pointer to a string describing the program name. The
716 * caller must not modify or free the returned string.
717 */
718 const char *
719 ovs_get_program_name(void)
720 {
721 return program_name;
722 }
723
724 /* Print the version information for the program. */
725 void
726 ovs_print_version(uint8_t min_ofp, uint8_t max_ofp)
727 {
728 printf("%s", program_version);
729 if (min_ofp || max_ofp) {
730 printf("OpenFlow versions %#x:%#x\n", min_ofp, max_ofp);
731 }
732 }
733
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. */
738 void
739 ovs_hex_dump(FILE *stream, const void *buf_, size_t size,
740 uintptr_t ofs, bool ascii)
741 {
742 const uint8_t *buf = buf_;
743 const size_t per_line = 16; /* Maximum bytes per line. */
744
745 while (size > 0) {
746 size_t i;
747
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) {
752 end = start + size;
753 }
754 size_t n = end - start;
755
756 /* Print line. */
757 fprintf(stream, "%08"PRIxMAX" ",
758 (uintmax_t) ROUND_DOWN(ofs, per_line));
759 for (i = 0; i < start; i++) {
760 fprintf(stream, " ");
761 }
762 for (; i < end; i++) {
763 fprintf(stream, "%c%02x",
764 i == per_line / 2 ? '-' : ' ', buf[i - start]);
765 }
766 if (ascii) {
767 fprintf(stream, " ");
768 for (; i < per_line; i++) {
769 fprintf(stream, " ");
770 }
771 fprintf(stream, "|");
772 for (i = 0; i < start; i++) {
773 fprintf(stream, " ");
774 }
775 for (; i < end; i++) {
776 int c = buf[i - start];
777 putc(c >= 32 && c < 127 ? c : '.', stream);
778 }
779 for (; i < per_line; i++) {
780 fprintf(stream, " ");
781 }
782 fprintf(stream, "|");
783 }
784 fprintf(stream, "\n");
785
786 ofs += n;
787 buf += n;
788 size -= n;
789 }
790 }
791
792 bool
793 str_to_int(const char *s, int base, int *i)
794 {
795 long long ll;
796 bool ok = str_to_llong(s, base, &ll);
797
798 if (!ok || ll < INT_MIN || ll > INT_MAX) {
799 *i = 0;
800 return false;
801 }
802 *i = ll;
803 return true;
804 }
805
806 bool
807 str_to_long(const char *s, int base, long *li)
808 {
809 long long ll;
810 bool ok = str_to_llong(s, base, &ll);
811
812 if (!ok || ll < LONG_MIN || ll > LONG_MAX) {
813 *li = 0;
814 return false;
815 }
816 *li = ll;
817 return true;
818 }
819
820 bool
821 str_to_llong(const char *s, int base, long long *x)
822 {
823 char *tail;
824 bool ok = str_to_llong_with_tail(s, &tail, base, x);
825 if (*tail != '\0') {
826 *x = 0;
827 return false;
828 }
829 return ok;
830 }
831
832 bool
833 str_to_llong_with_tail(const char *s, char **tail, int base, long long *x)
834 {
835 int save_errno = errno;
836 errno = 0;
837 *x = strtoll(s, tail, base);
838 if (errno == EINVAL || errno == ERANGE || *tail == s) {
839 errno = save_errno;
840 *x = 0;
841 return false;
842 } else {
843 errno = save_errno;
844 return true;
845 }
846 }
847
848 bool
849 str_to_uint(const char *s, int base, unsigned int *u)
850 {
851 long long ll;
852 bool ok = str_to_llong(s, base, &ll);
853 if (!ok || ll < 0 || ll > UINT_MAX) {
854 *u = 0;
855 return false;
856 } else {
857 *u = ll;
858 return true;
859 }
860 }
861
862 bool
863 str_to_ullong(const char *s, int base, unsigned long long *x)
864 {
865 int save_errno = errno;
866 char *tail;
867
868 errno = 0;
869 *x = strtoull(s, &tail, base);
870 if (errno == EINVAL || errno == ERANGE || tail == s || *tail != '\0') {
871 errno = save_errno;
872 *x = 0;
873 return false;
874 } else {
875 errno = save_errno;
876 return true;
877 }
878 }
879
880 bool
881 str_to_llong_range(const char *s, int base, long long *begin,
882 long long *end)
883 {
884 char *tail;
885 if (str_to_llong_with_tail(s, &tail, base, begin)
886 && *tail == '-'
887 && str_to_llong(tail + 1, base, end)) {
888 return true;
889 }
890 *begin = 0;
891 *end = 0;
892 return false;
893 }
894
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
897 * returns false.
898 *
899 * Underflow (e.g. "1e-9999") is not considered an error, but overflow
900 * (e.g. "1e9999)" is. */
901 bool
902 str_to_double(const char *s, double *d)
903 {
904 int save_errno = errno;
905 char *tail;
906 errno = 0;
907 *d = strtod(s, &tail);
908 if (errno == EINVAL || (errno == ERANGE && *d != 0)
909 || tail == s || *tail != '\0') {
910 errno = save_errno;
911 *d = 0;
912 return false;
913 } else {
914 errno = save_errno;
915 return true;
916 }
917 }
918
919 /* Returns the value of 'c' as a hexadecimal digit. */
920 int
921 hexit_value(unsigned char c)
922 {
923 static const signed char tbl[UCHAR_MAX + 1] = {
924 #define TBL(x) \
925 ( x >= '0' && x <= '9' ? x - '0' \
926 : x >= 'a' && x <= 'f' ? x - 'a' + 0xa \
927 : x >= 'A' && x <= 'F' ? x - 'A' + 0xa \
928 : -1)
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)
933 };
934
935 return tbl[c];
936 }
937
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
941 * detected. */
942 uintmax_t
943 hexits_value(const char *s, size_t n, bool *ok)
944 {
945 uintmax_t value;
946 size_t i;
947
948 value = 0;
949 for (i = 0; i < n; i++) {
950 int hexit = hexit_value(s[i]);
951 if (hexit < 0) {
952 *ok = false;
953 return UINTMAX_MAX;
954 }
955 value = (value << 4) + hexit;
956 }
957 *ok = true;
958 return value;
959 }
960
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.)
967 *
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. */
971 int
972 parse_int_string(const char *s, uint8_t *valuep, int field_width, char **tail)
973 {
974 unsigned long long int integer;
975 int i;
976
977 if (!strncmp(s, "0x", 2) || !strncmp(s, "0X", 2)) {
978 uint8_t *hexit_str;
979 int len = 0;
980 int val_idx;
981 int err = 0;
982
983 s += 2;
984 hexit_str = xmalloc(field_width * 2);
985
986 for (;;) {
987 uint8_t hexit;
988 bool ok;
989
990 s += strspn(s, " \t\r\n");
991 hexit = hexits_value(s, 1, &ok);
992 if (!ok) {
993 *tail = CONST_CAST(char *, s);
994 break;
995 }
996
997 if (hexit != 0 || len) {
998 if (DIV_ROUND_UP(len + 1, 2) > field_width) {
999 err = ERANGE;
1000 goto free;
1001 }
1002
1003 hexit_str[len] = hexit;
1004 len++;
1005 }
1006 s++;
1007 }
1008
1009 val_idx = field_width;
1010 for (i = len - 1; i >= 0; i -= 2) {
1011 val_idx--;
1012 valuep[val_idx] = hexit_str[i];
1013 if (i > 0) {
1014 valuep[val_idx] += hexit_str[i - 1] << 4;
1015 }
1016 }
1017
1018 memset(valuep, 0, val_idx);
1019
1020 free:
1021 free(hexit_str);
1022 return err;
1023 }
1024
1025 errno = 0;
1026 integer = strtoull(s, tail, 0);
1027 if (errno || s == *tail) {
1028 return errno ? errno : EINVAL;
1029 }
1030
1031 for (i = field_width - 1; i >= 0; i--) {
1032 valuep[i] = integer;
1033 integer >>= 8;
1034 }
1035 if (integer) {
1036 return ERANGE;
1037 }
1038
1039 return 0;
1040 }
1041
1042 /* Returns the current working directory as a malloc()'d string, or a null
1043 * pointer if the current working directory cannot be determined. */
1044 char *
1045 get_cwd(void)
1046 {
1047 long int path_max;
1048 size_t size;
1049
1050 /* Get maximum path length or at least a reasonable estimate. */
1051 #ifndef _WIN32
1052 path_max = pathconf(".", _PC_PATH_MAX);
1053 #else
1054 path_max = MAX_PATH;
1055 #endif
1056 size = (path_max < 0 ? 1024
1057 : path_max > 10240 ? 10240
1058 : path_max);
1059
1060 /* Get current working directory. */
1061 for (;;) {
1062 char *buf = xmalloc(size);
1063 if (getcwd(buf, size)) {
1064 return xrealloc(buf, strlen(buf) + 1);
1065 } else {
1066 int error = errno;
1067 free(buf);
1068 if (error != ERANGE) {
1069 VLOG_WARN("getcwd failed (%s)", ovs_strerror(error));
1070 return NULL;
1071 }
1072 size *= 2;
1073 }
1074 }
1075 }
1076
1077 static char *
1078 all_slashes_name(const char *s)
1079 {
1080 return xstrdup(s[0] == '/' && s[1] == '/' && s[2] != '/' ? "//"
1081 : s[0] == '/' ? "/"
1082 : ".");
1083 }
1084
1085 #ifndef _WIN32
1086 /* Returns the directory name portion of 'file_name' as a malloc()'d string,
1087 * similar to the POSIX dirname() function but thread-safe. */
1088 char *
1089 dir_name(const char *file_name)
1090 {
1091 size_t len = strlen(file_name);
1092 while (len > 0 && file_name[len - 1] == '/') {
1093 len--;
1094 }
1095 while (len > 0 && file_name[len - 1] != '/') {
1096 len--;
1097 }
1098 while (len > 0 && file_name[len - 1] == '/') {
1099 len--;
1100 }
1101 return len ? xmemdup0(file_name, len) : all_slashes_name(file_name);
1102 }
1103
1104 /* Returns the file name portion of 'file_name' as a malloc()'d string,
1105 * similar to the POSIX basename() function but thread-safe. */
1106 char *
1107 base_name(const char *file_name)
1108 {
1109 size_t end, start;
1110
1111 end = strlen(file_name);
1112 while (end > 0 && file_name[end - 1] == '/') {
1113 end--;
1114 }
1115
1116 if (!end) {
1117 return all_slashes_name(file_name);
1118 }
1119
1120 start = end;
1121 while (start > 0 && file_name[start - 1] != '/') {
1122 start--;
1123 }
1124
1125 return xmemdup0(file_name + start, end - start);
1126 }
1127 #endif /* _WIN32 */
1128
1129 bool
1130 is_file_name_absolute(const char *fn)
1131 {
1132 #ifdef _WIN32
1133 /* Use platform specific API */
1134 return !PathIsRelative(fn);
1135 #else
1136 /* An absolute path begins with /. */
1137 return fn[0] == '/';
1138 #endif
1139 }
1140
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.
1145 *
1146 * Returns a null pointer if 'dir' is null and getcwd() fails. */
1147 char *
1148 abs_file_name(const char *dir, const char *file_name)
1149 {
1150 /* If it's already absolute, return a copy. */
1151 if (is_file_name_absolute(file_name)) {
1152 return xstrdup(file_name);
1153 }
1154
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);
1160 }
1161
1162 #if _WIN32
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;
1169 #else
1170 /* Outside Windows, do the job ourselves. */
1171 char *cwd = get_cwd();
1172 if (!cwd) {
1173 return NULL;
1174 }
1175 char *abs_name = xasprintf("%s/%s", cwd, file_name);
1176 free(cwd);
1177 return abs_name;
1178 #endif
1179 }
1180
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. */
1184 static char *
1185 xreadlink(const char *filename)
1186 {
1187 #ifdef _WIN32
1188 errno = ENOENT;
1189 return NULL;
1190 #else
1191 size_t size;
1192
1193 for (size = 64; ; size *= 2) {
1194 char *buf = xmalloc(size);
1195 ssize_t retval = readlink(filename, buf, size);
1196 int error = errno;
1197
1198 if (retval >= 0 && retval < size) {
1199 buf[retval] = '\0';
1200 return buf;
1201 }
1202
1203 free(buf);
1204 if (retval < 0) {
1205 errno = error;
1206 return NULL;
1207 }
1208 }
1209 #endif
1210 }
1211
1212 /* Returns a version of 'filename' with symlinks in the final component
1213 * dereferenced. This differs from realpath() in that:
1214 *
1215 * - 'filename' need not exist.
1216 *
1217 * - If 'filename' does exist as a symlink, its referent need not exist.
1218 *
1219 * - Only symlinks in the final component of 'filename' are dereferenced.
1220 *
1221 * For Windows platform, this function returns a string that has the same
1222 * value as the passed string.
1223 *
1224 * The caller must eventually free the returned string (with free()). */
1225 char *
1226 follow_symlinks(const char *filename)
1227 {
1228 #ifndef _WIN32
1229 struct stat s;
1230 char *fn;
1231 int i;
1232
1233 fn = xstrdup(filename);
1234 for (i = 0; i < 10; i++) {
1235 char *linkname;
1236 char *next_fn;
1237
1238 if (lstat(fn, &s) != 0 || !S_ISLNK(s.st_mode)) {
1239 return fn;
1240 }
1241
1242 linkname = xreadlink(fn);
1243 if (!linkname) {
1244 VLOG_WARN("%s: readlink failed (%s)",
1245 filename, ovs_strerror(errno));
1246 return fn;
1247 }
1248
1249 if (linkname[0] == '/') {
1250 /* Target of symlink is absolute so use it raw. */
1251 next_fn = linkname;
1252 } else {
1253 /* Target of symlink is relative so add to 'fn''s directory. */
1254 char *dir = dir_name(fn);
1255
1256 if (!strcmp(dir, ".")) {
1257 next_fn = linkname;
1258 } else {
1259 char *separator = dir[strlen(dir) - 1] == '/' ? "" : "/";
1260 next_fn = xasprintf("%s%s%s", dir, separator, linkname);
1261 free(linkname);
1262 }
1263
1264 free(dir);
1265 }
1266
1267 free(fn);
1268 fn = next_fn;
1269 }
1270
1271 VLOG_WARN("%s: too many levels of symlinks", filename);
1272 free(fn);
1273 #endif
1274 return xstrdup(filename);
1275 }
1276
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) { }
1282
1283 /* Returns an appropriate delimiter for inserting just before the 0-based item
1284 * 'index' in a list that has 'total' items in it. */
1285 const char *
1286 english_list_delimiter(size_t index, size_t total)
1287 {
1288 return (index == 0 ? ""
1289 : index < total - 1 ? ", "
1290 : total > 2 ? ", and "
1291 : " and ");
1292 }
1293
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. */
1297 #else
1298 /* Returns the number of trailing 0-bits in 'n'. Undefined if 'n' == 0. */
1299 int
1300 raw_ctz(uint64_t n)
1301 {
1302 uint64_t k;
1303 int count = 63;
1304
1305 #define CTZ_STEP(X) \
1306 k = n << (X); \
1307 if (k) { \
1308 count -= X; \
1309 n = k; \
1310 }
1311 CTZ_STEP(32);
1312 CTZ_STEP(16);
1313 CTZ_STEP(8);
1314 CTZ_STEP(4);
1315 CTZ_STEP(2);
1316 CTZ_STEP(1);
1317 #undef CTZ_STEP
1318
1319 return count;
1320 }
1321
1322 /* Returns the number of leading 0-bits in 'n'. Undefined if 'n' == 0. */
1323 int
1324 raw_clz64(uint64_t n)
1325 {
1326 uint64_t k;
1327 int count = 63;
1328
1329 #define CLZ_STEP(X) \
1330 k = n >> (X); \
1331 if (k) { \
1332 count -= X; \
1333 n = k; \
1334 }
1335 CLZ_STEP(32);
1336 CLZ_STEP(16);
1337 CLZ_STEP(8);
1338 CLZ_STEP(4);
1339 CLZ_STEP(2);
1340 CLZ_STEP(1);
1341 #undef CLZ_STEP
1342
1343 return count;
1344 }
1345 #endif
1346
1347 #if NEED_COUNT_1BITS_8
1348 #define INIT1(X) \
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)
1363
1364 const uint8_t count_1bits_8[256] = {
1365 INIT64(0), INIT64(64), INIT64(128), INIT64(192)
1366 };
1367 #endif
1368
1369 /* Returns true if the 'n' bytes starting at 'p' are 'byte'. */
1370 bool
1371 is_all_byte(const void *p_, size_t n, uint8_t byte)
1372 {
1373 const uint8_t *p = p_;
1374 size_t i;
1375
1376 for (i = 0; i < n; i++) {
1377 if (p[i] != byte) {
1378 return false;
1379 }
1380 }
1381 return true;
1382 }
1383
1384 /* Returns true if the 'n' bytes starting at 'p' are zeros. */
1385 bool
1386 is_all_zeros(const void *p, size_t n)
1387 {
1388 return is_all_byte(p, n, 0);
1389 }
1390
1391 /* Returns true if the 'n' bytes starting at 'p' are 0xff. */
1392 bool
1393 is_all_ones(const void *p, size_t n)
1394 {
1395 return is_all_byte(p, n, 0xff);
1396 }
1397
1398 /* *dst |= *src for 'n' bytes. */
1399 void
1400 or_bytes(void *dst_, const void *src_, size_t n)
1401 {
1402 const uint8_t *src = src_;
1403 uint8_t *dst = dst_;
1404 size_t i;
1405
1406 for (i = 0; i < n; i++) {
1407 *dst++ |= *src++;
1408 }
1409 }
1410
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.
1414 *
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'.
1420 *
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.
1425 */
1426 void
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)
1430 {
1431 const uint8_t *src = src_;
1432 uint8_t *dst = dst_;
1433
1434 src += src_len - (src_ofs / 8 + 1);
1435 src_ofs %= 8;
1436
1437 dst += dst_len - (dst_ofs / 8 + 1);
1438 dst_ofs %= 8;
1439
1440 if (src_ofs == 0 && dst_ofs == 0) {
1441 unsigned int n_bytes = n_bits / 8;
1442 if (n_bytes) {
1443 dst -= n_bytes - 1;
1444 src -= n_bytes - 1;
1445 memcpy(dst, src, n_bytes);
1446
1447 n_bits %= 8;
1448 src--;
1449 dst--;
1450 }
1451 if (n_bits) {
1452 uint8_t mask = (1 << n_bits) - 1;
1453 *dst = (*dst & ~mask) | (*src & mask);
1454 }
1455 } else {
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;
1460
1461 *dst &= ~mask;
1462 *dst |= ((*src >> src_ofs) << dst_ofs) & mask;
1463
1464 src_ofs += chunk;
1465 if (src_ofs == 8) {
1466 src--;
1467 src_ofs = 0;
1468 }
1469 dst_ofs += chunk;
1470 if (dst_ofs == 8) {
1471 dst--;
1472 dst_ofs = 0;
1473 }
1474 n_bits -= chunk;
1475 }
1476 }
1477 }
1478
1479 /* Zeros the 'n_bits' bits starting from bit 'dst_ofs' in 'dst'. 'dst' is
1480 * 'dst_len' bytes long.
1481 *
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 -
1486 * 2], and so on.
1487 *
1488 * Required invariant:
1489 * dst_ofs + n_bits <= dst_len * 8
1490 */
1491 void
1492 bitwise_zero(void *dst_, unsigned int dst_len, unsigned dst_ofs,
1493 unsigned int n_bits)
1494 {
1495 uint8_t *dst = dst_;
1496
1497 if (!n_bits) {
1498 return;
1499 }
1500
1501 dst += dst_len - (dst_ofs / 8 + 1);
1502 dst_ofs %= 8;
1503
1504 if (dst_ofs) {
1505 unsigned int chunk = MIN(n_bits, 8 - dst_ofs);
1506
1507 *dst &= ~(((1 << chunk) - 1) << dst_ofs);
1508
1509 n_bits -= chunk;
1510 if (!n_bits) {
1511 return;
1512 }
1513
1514 dst--;
1515 }
1516
1517 while (n_bits >= 8) {
1518 *dst-- = 0;
1519 n_bits -= 8;
1520 }
1521
1522 if (n_bits) {
1523 *dst &= ~((1 << n_bits) - 1);
1524 }
1525 }
1526
1527 /* Sets to 1 all of the 'n_bits' bits starting from bit 'dst_ofs' in 'dst'.
1528 * 'dst' is 'dst_len' bytes long.
1529 *
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 -
1534 * 2], and so on.
1535 *
1536 * Required invariant:
1537 * dst_ofs + n_bits <= dst_len * 8
1538 */
1539 void
1540 bitwise_one(void *dst_, unsigned int dst_len, unsigned dst_ofs,
1541 unsigned int n_bits)
1542 {
1543 uint8_t *dst = dst_;
1544
1545 if (!n_bits) {
1546 return;
1547 }
1548
1549 dst += dst_len - (dst_ofs / 8 + 1);
1550 dst_ofs %= 8;
1551
1552 if (dst_ofs) {
1553 unsigned int chunk = MIN(n_bits, 8 - dst_ofs);
1554
1555 *dst |= ((1 << chunk) - 1) << dst_ofs;
1556
1557 n_bits -= chunk;
1558 if (!n_bits) {
1559 return;
1560 }
1561
1562 dst--;
1563 }
1564
1565 while (n_bits >= 8) {
1566 *dst-- = 0xff;
1567 n_bits -= 8;
1568 }
1569
1570 if (n_bits) {
1571 *dst |= (1 << n_bits) - 1;
1572 }
1573 }
1574
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'
1577 * bytes long.
1578 *
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 -
1583 * 2], and so on.
1584 *
1585 * Required invariant:
1586 * dst_ofs + n_bits <= dst_len * 8
1587 */
1588 bool
1589 bitwise_is_all_zeros(const void *p_, unsigned int len, unsigned int ofs,
1590 unsigned int n_bits)
1591 {
1592 const uint8_t *p = p_;
1593
1594 if (!n_bits) {
1595 return true;
1596 }
1597
1598 p += len - (ofs / 8 + 1);
1599 ofs %= 8;
1600
1601 if (ofs) {
1602 unsigned int chunk = MIN(n_bits, 8 - ofs);
1603
1604 if (*p & (((1 << chunk) - 1) << ofs)) {
1605 return false;
1606 }
1607
1608 n_bits -= chunk;
1609 if (!n_bits) {
1610 return true;
1611 }
1612
1613 p--;
1614 }
1615
1616 while (n_bits >= 8) {
1617 if (*p) {
1618 return false;
1619 }
1620 n_bits -= 8;
1621 p--;
1622 }
1623
1624 if (n_bits && *p & ((1 << n_bits) - 1)) {
1625 return false;
1626 }
1627
1628 return true;
1629 }
1630
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.
1634 *
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.
1639 *
1640 * Required invariant:
1641 * start <= end
1642 */
1643 unsigned int
1644 bitwise_scan(const void *p, unsigned int len, bool target, unsigned int start,
1645 unsigned int end)
1646 {
1647 unsigned int ofs;
1648
1649 for (ofs = start; ofs < end; ofs++) {
1650 if (bitwise_get_bit(p, len, ofs) == target) {
1651 break;
1652 }
1653 }
1654 return ofs;
1655 }
1656
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
1660 * long.
1661 *
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.
1666 *
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.
1670 *
1671 * Required invariant:
1672 * start >= end
1673 */
1674 int
1675 bitwise_rscan(const void *p, unsigned int len, bool target, int start, int end)
1676 {
1677 const uint8_t *s = p;
1678 int start_byte = len - (start / 8 + 1);
1679 int end_byte = len - (end / 8 + 1);
1680 int ofs_byte;
1681 int ofs;
1682 uint8_t the_byte;
1683
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) {
1689 break;
1690 }
1691 }
1692 if (ofs < 0) {
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))) {
1697 break;
1698 }
1699 }
1700 if (ofs_byte > end_byte) {
1701 return end;
1702 }
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) {
1707 break;
1708 }
1709 }
1710 }
1711 int ret = (len - ofs_byte) * 8 - (8 - ofs);
1712 if (ret < end) {
1713 return end;
1714 }
1715 return ret;
1716 }
1717
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.
1720 *
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 -
1725 * 2], and so on.
1726 *
1727 * Required invariants:
1728 * dst_ofs + n_bits <= dst_len * 8
1729 * n_bits <= 64
1730 */
1731 void
1732 bitwise_put(uint64_t value,
1733 void *dst, unsigned int dst_len, unsigned int dst_ofs,
1734 unsigned int n_bits)
1735 {
1736 ovs_be64 n_value = htonll(value);
1737 bitwise_copy(&n_value, sizeof n_value, 0,
1738 dst, dst_len, dst_ofs,
1739 n_bits);
1740 }
1741
1742 /* Returns the value of the 'n_bits' bits starting at bit 'src_ofs' in 'src',
1743 * which is 'src_len' bytes long.
1744 *
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 -
1749 * 2], and so on.
1750 *
1751 * Required invariants:
1752 * src_ofs + n_bits <= src_len * 8
1753 * n_bits <= 64
1754 */
1755 uint64_t
1756 bitwise_get(const void *src, unsigned int src_len,
1757 unsigned int src_ofs, unsigned int n_bits)
1758 {
1759 ovs_be64 value = htonll(0);
1760
1761 bitwise_copy(src, src_len, src_ofs,
1762 &value, sizeof value, 0,
1763 n_bits);
1764 return ntohll(value);
1765 }
1766
1767 /* Returns the value of the bit with offset 'ofs' in 'src', which is 'len'
1768 * bytes long.
1769 *
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
1774 * on.
1775 *
1776 * Required invariants:
1777 * ofs < len * 8
1778 */
1779 bool
1780 bitwise_get_bit(const void *src_, unsigned int len, unsigned int ofs)
1781 {
1782 const uint8_t *src = src_;
1783
1784 return (src[len - (ofs / 8 + 1)] & (1u << (ofs % 8))) != 0;
1785 }
1786
1787 /* Sets the bit with offset 'ofs' in 'dst', which is 'len' bytes long, to 0.
1788 *
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
1793 * on.
1794 *
1795 * Required invariants:
1796 * ofs < len * 8
1797 */
1798 void
1799 bitwise_put0(void *dst_, unsigned int len, unsigned int ofs)
1800 {
1801 uint8_t *dst = dst_;
1802
1803 dst[len - (ofs / 8 + 1)] &= ~(1u << (ofs % 8));
1804 }
1805
1806 /* Sets the bit with offset 'ofs' in 'dst', which is 'len' bytes long, to 1.
1807 *
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
1812 * on.
1813 *
1814 * Required invariants:
1815 * ofs < len * 8
1816 */
1817 void
1818 bitwise_put1(void *dst_, unsigned int len, unsigned int ofs)
1819 {
1820 uint8_t *dst = dst_;
1821
1822 dst[len - (ofs / 8 + 1)] |= 1u << (ofs % 8);
1823 }
1824
1825 /* Sets the bit with offset 'ofs' in 'dst', which is 'len' bytes long, to 'b'.
1826 *
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
1831 * on.
1832 *
1833 * Required invariants:
1834 * ofs < len * 8
1835 */
1836 void
1837 bitwise_put_bit(void *dst, unsigned int len, unsigned int ofs, bool b)
1838 {
1839 if (b) {
1840 bitwise_put1(dst, len, ofs);
1841 } else {
1842 bitwise_put0(dst, len, ofs);
1843 }
1844 }
1845
1846 /* Flips the bit with offset 'ofs' in 'dst', which is 'len' bytes long.
1847 *
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
1852 * on.
1853 *
1854 * Required invariants:
1855 * ofs < len * 8
1856 */
1857 void
1858 bitwise_toggle_bit(void *dst_, unsigned int len, unsigned int ofs)
1859 {
1860 uint8_t *dst = dst_;
1861
1862 dst[len - (ofs / 8 + 1)] ^= 1u << (ofs % 8);
1863 }
1864 \f
1865 /* ovs_scan */
1866
1867 struct scan_spec {
1868 unsigned int width;
1869 enum {
1870 SCAN_DISCARD,
1871 SCAN_CHAR,
1872 SCAN_SHORT,
1873 SCAN_INT,
1874 SCAN_LONG,
1875 SCAN_LLONG,
1876 SCAN_INTMAX_T,
1877 SCAN_PTRDIFF_T,
1878 SCAN_SIZE_T
1879 } type;
1880 };
1881
1882 static const char *
1883 skip_spaces(const char *s)
1884 {
1885 while (isspace((unsigned char) *s)) {
1886 s++;
1887 }
1888 return s;
1889 }
1890
1891 static const char *
1892 scan_int(const char *s, const struct scan_spec *spec, int base, va_list *args)
1893 {
1894 const char *start = s;
1895 uintmax_t value;
1896 bool negative;
1897 int n_digits;
1898
1899 negative = *s == '-';
1900 s += *s == '-' || *s == '+';
1901
1902 if ((!base || base == 16) && *s == '0' && (s[1] == 'x' || s[1] == 'X')) {
1903 base = 16;
1904 s += 2;
1905 } else if (!base) {
1906 base = *s == '0' ? 8 : 10;
1907 }
1908
1909 if (s - start >= spec->width) {
1910 return NULL;
1911 }
1912
1913 value = 0;
1914 n_digits = 0;
1915 while (s - start < spec->width) {
1916 int digit = hexit_value(*s);
1917
1918 if (digit < 0 || digit >= base) {
1919 break;
1920 }
1921 value = value * base + digit;
1922 n_digits++;
1923 s++;
1924 }
1925 if (!n_digits) {
1926 return NULL;
1927 }
1928
1929 if (negative) {
1930 value = -value;
1931 }
1932
1933 switch (spec->type) {
1934 case SCAN_DISCARD:
1935 break;
1936 case SCAN_CHAR:
1937 *va_arg(*args, char *) = value;
1938 break;
1939 case SCAN_SHORT:
1940 *va_arg(*args, short int *) = value;
1941 break;
1942 case SCAN_INT:
1943 *va_arg(*args, int *) = value;
1944 break;
1945 case SCAN_LONG:
1946 *va_arg(*args, long int *) = value;
1947 break;
1948 case SCAN_LLONG:
1949 *va_arg(*args, long long int *) = value;
1950 break;
1951 case SCAN_INTMAX_T:
1952 *va_arg(*args, intmax_t *) = value;
1953 break;
1954 case SCAN_PTRDIFF_T:
1955 *va_arg(*args, ptrdiff_t *) = value;
1956 break;
1957 case SCAN_SIZE_T:
1958 *va_arg(*args, size_t *) = value;
1959 break;
1960 }
1961 return s;
1962 }
1963
1964 static const char *
1965 skip_digits(const char *s)
1966 {
1967 while (*s >= '0' && *s <= '9') {
1968 s++;
1969 }
1970 return s;
1971 }
1972
1973 static const char *
1974 scan_float(const char *s, const struct scan_spec *spec, va_list *args)
1975 {
1976 const char *start = s;
1977 long double value;
1978 char *tail;
1979 char *copy;
1980 bool ok;
1981
1982 s += *s == '+' || *s == '-';
1983 s = skip_digits(s);
1984 if (*s == '.') {
1985 s = skip_digits(s + 1);
1986 }
1987 if (*s == 'e' || *s == 'E') {
1988 s++;
1989 s += *s == '+' || *s == '-';
1990 s = skip_digits(s);
1991 }
1992
1993 if (s - start > spec->width) {
1994 s = start + spec->width;
1995 }
1996
1997 copy = xmemdup0(start, s - start);
1998 value = strtold(copy, &tail);
1999 ok = *tail == '\0';
2000 free(copy);
2001 if (!ok) {
2002 return NULL;
2003 }
2004
2005 switch (spec->type) {
2006 case SCAN_DISCARD:
2007 break;
2008 case SCAN_INT:
2009 *va_arg(*args, float *) = value;
2010 break;
2011 case SCAN_LONG:
2012 *va_arg(*args, double *) = value;
2013 break;
2014 case SCAN_LLONG:
2015 *va_arg(*args, long double *) = value;
2016 break;
2017
2018 case SCAN_CHAR:
2019 case SCAN_SHORT:
2020 case SCAN_INTMAX_T:
2021 case SCAN_PTRDIFF_T:
2022 case SCAN_SIZE_T:
2023 OVS_NOT_REACHED();
2024 }
2025 return s;
2026 }
2027
2028 static void
2029 scan_output_string(const struct scan_spec *spec,
2030 const char *s, size_t n,
2031 va_list *args)
2032 {
2033 if (spec->type != SCAN_DISCARD) {
2034 char *out = va_arg(*args, char *);
2035 memcpy(out, s, n);
2036 out[n] = '\0';
2037 }
2038 }
2039
2040 static const char *
2041 scan_string(const char *s, const struct scan_spec *spec, va_list *args)
2042 {
2043 size_t n;
2044
2045 for (n = 0; n < spec->width; n++) {
2046 if (!s[n] || isspace((unsigned char) s[n])) {
2047 break;
2048 }
2049 }
2050 if (!n) {
2051 return NULL;
2052 }
2053
2054 scan_output_string(spec, s, n, args);
2055 return s + n;
2056 }
2057
2058 static const char *
2059 parse_scanset(const char *p_, unsigned long *set, bool *complemented)
2060 {
2061 const uint8_t *p = (const uint8_t *) p_;
2062
2063 *complemented = *p == '^';
2064 p += *complemented;
2065
2066 if (*p == ']') {
2067 bitmap_set1(set, ']');
2068 p++;
2069 }
2070
2071 while (*p && *p != ']') {
2072 if (p[1] == '-' && p[2] != ']' && p[2] > *p) {
2073 bitmap_set_multiple(set, *p, p[2] - *p + 1, true);
2074 p += 3;
2075 } else {
2076 bitmap_set1(set, *p++);
2077 }
2078 }
2079 if (*p == ']') {
2080 p++;
2081 }
2082 return (const char *) p;
2083 }
2084
2085 static const char *
2086 scan_set(const char *s, const struct scan_spec *spec, const char **pp,
2087 va_list *args)
2088 {
2089 unsigned long set[BITMAP_N_LONGS(UCHAR_MAX + 1)];
2090 bool complemented;
2091 unsigned int n;
2092
2093 /* Parse the scan set. */
2094 memset(set, 0, sizeof set);
2095 *pp = parse_scanset(*pp, set, &complemented);
2096
2097 /* Parse the data. */
2098 n = 0;
2099 while (s[n]
2100 && bitmap_is_set(set, (unsigned char) s[n]) == !complemented
2101 && n < spec->width) {
2102 n++;
2103 }
2104 if (!n) {
2105 return NULL;
2106 }
2107 scan_output_string(spec, s, n, args);
2108 return s + n;
2109 }
2110
2111 static const char *
2112 scan_chars(const char *s, const struct scan_spec *spec, va_list *args)
2113 {
2114 unsigned int n = spec->width == UINT_MAX ? 1 : spec->width;
2115
2116 if (strlen(s) < n) {
2117 return NULL;
2118 }
2119 if (spec->type != SCAN_DISCARD) {
2120 memcpy(va_arg(*args, char *), s, n);
2121 }
2122 return s + n;
2123 }
2124
2125 static bool
2126 ovs_scan__(const char *s, int *n, const char *format, va_list *args)
2127 {
2128 const char *const start = s;
2129 bool ok = false;
2130 const char *p;
2131
2132 p = format;
2133 while (*p != '\0') {
2134 struct scan_spec spec;
2135 unsigned char c = *p++;
2136 bool discard;
2137
2138 if (isspace(c)) {
2139 s = skip_spaces(s);
2140 continue;
2141 } else if (c != '%') {
2142 if (*s != c) {
2143 goto exit;
2144 }
2145 s++;
2146 continue;
2147 } else if (*p == '%') {
2148 if (*s++ != '%') {
2149 goto exit;
2150 }
2151 p++;
2152 continue;
2153 }
2154
2155 /* Parse '*' flag. */
2156 discard = *p == '*';
2157 p += discard;
2158
2159 /* Parse field width. */
2160 spec.width = 0;
2161 while (*p >= '0' && *p <= '9') {
2162 spec.width = spec.width * 10 + (*p++ - '0');
2163 }
2164 if (spec.width == 0) {
2165 spec.width = UINT_MAX;
2166 }
2167
2168 /* Parse type modifier. */
2169 switch (*p) {
2170 case 'h':
2171 if (p[1] == 'h') {
2172 spec.type = SCAN_CHAR;
2173 p += 2;
2174 } else {
2175 spec.type = SCAN_SHORT;
2176 p++;
2177 }
2178 break;
2179
2180 case 'j':
2181 spec.type = SCAN_INTMAX_T;
2182 p++;
2183 break;
2184
2185 case 'l':
2186 if (p[1] == 'l') {
2187 spec.type = SCAN_LLONG;
2188 p += 2;
2189 } else {
2190 spec.type = SCAN_LONG;
2191 p++;
2192 }
2193 break;
2194
2195 case 'L':
2196 case 'q':
2197 spec.type = SCAN_LLONG;
2198 p++;
2199 break;
2200
2201 case 't':
2202 spec.type = SCAN_PTRDIFF_T;
2203 p++;
2204 break;
2205
2206 case 'z':
2207 spec.type = SCAN_SIZE_T;
2208 p++;
2209 break;
2210
2211 default:
2212 spec.type = SCAN_INT;
2213 break;
2214 }
2215
2216 if (discard) {
2217 spec.type = SCAN_DISCARD;
2218 }
2219
2220 c = *p++;
2221 if (c != 'c' && c != 'n' && c != '[') {
2222 s = skip_spaces(s);
2223 }
2224 switch (c) {
2225 case 'd':
2226 s = scan_int(s, &spec, 10, args);
2227 break;
2228
2229 case 'i':
2230 s = scan_int(s, &spec, 0, args);
2231 break;
2232
2233 case 'o':
2234 s = scan_int(s, &spec, 8, args);
2235 break;
2236
2237 case 'u':
2238 s = scan_int(s, &spec, 10, args);
2239 break;
2240
2241 case 'x':
2242 case 'X':
2243 s = scan_int(s, &spec, 16, args);
2244 break;
2245
2246 case 'e':
2247 case 'f':
2248 case 'g':
2249 case 'E':
2250 case 'G':
2251 s = scan_float(s, &spec, args);
2252 break;
2253
2254 case 's':
2255 s = scan_string(s, &spec, args);
2256 break;
2257
2258 case '[':
2259 s = scan_set(s, &spec, &p, args);
2260 break;
2261
2262 case 'c':
2263 s = scan_chars(s, &spec, args);
2264 break;
2265
2266 case 'n':
2267 if (spec.type != SCAN_DISCARD) {
2268 *va_arg(*args, int *) = s - start;
2269 }
2270 break;
2271 }
2272
2273 if (!s) {
2274 goto exit;
2275 }
2276 }
2277 if (n) {
2278 *n = s - start;
2279 }
2280
2281 ok = true;
2282 exit:
2283 return ok;
2284 }
2285
2286 /* This is an implementation of the standard sscanf() function, with the
2287 * following exceptions:
2288 *
2289 * - It returns true if the entire format was successfully scanned and
2290 * converted, false if any conversion failed.
2291 *
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.
2298 *
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.
2302 *
2303 * - %p is not supported.
2304 */
2305 bool
2306 ovs_scan(const char *s, const char *format, ...)
2307 {
2308 va_list args;
2309 bool res;
2310
2311 va_start(args, format);
2312 res = ovs_scan__(s, NULL, format, &args);
2313 va_end(args);
2314 return res;
2315 }
2316
2317 /*
2318 * This function is similar to ovs_scan(), with an extra parameter `n` added to
2319 * return the number of scanned characters.
2320 */
2321 bool
2322 ovs_scan_len(const char *s, int *n, const char *format, ...)
2323 {
2324 va_list args;
2325 bool success;
2326 int n1;
2327
2328 va_start(args, format);
2329 success = ovs_scan__(s + *n, &n1, format, &args);
2330 va_end(args);
2331 if (success) {
2332 *n = *n + n1;
2333 }
2334 return success;
2335 }
2336
2337 void
2338 xsleep(unsigned int seconds)
2339 {
2340 ovsrcu_quiesce_start();
2341 #ifdef _WIN32
2342 Sleep(seconds * 1000);
2343 #else
2344 sleep(seconds);
2345 #endif
2346 ovsrcu_quiesce_end();
2347 }
2348
2349 /* High resolution sleep. */
2350 void
2351 xnanosleep(uint64_t nanoseconds)
2352 {
2353 ovsrcu_quiesce_start();
2354 #ifndef _WIN32
2355 int retval;
2356 struct timespec ts_sleep;
2357 nsec_to_timespec(nanoseconds, &ts_sleep);
2358
2359 int error = 0;
2360 do {
2361 retval = nanosleep(&ts_sleep, NULL);
2362 error = retval < 0 ? errno : 0;
2363 } while (error == EINTR);
2364 #else
2365 HANDLE timer = CreateWaitableTimer(NULL, FALSE, NULL);
2366 if (timer) {
2367 LARGE_INTEGER duetime;
2368 duetime.QuadPart = -nanoseconds;
2369 if (SetWaitableTimer(timer, &duetime, 0, NULL, NULL, FALSE)) {
2370 WaitForSingleObject(timer, INFINITE);
2371 } else {
2372 VLOG_ERR_ONCE("SetWaitableTimer Failed (%s)",
2373 ovs_lasterror_to_string());
2374 }
2375 CloseHandle(timer);
2376 } else {
2377 VLOG_ERR_ONCE("CreateWaitableTimer Failed (%s)",
2378 ovs_lasterror_to_string());
2379 }
2380 #endif
2381 ovsrcu_quiesce_end();
2382 }
2383
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
2386 * to `auto`.
2387 */
2388 bool
2389 is_stdout_a_tty(void)
2390 {
2391 char const *t = getenv("TERM");
2392 return (isatty(STDOUT_FILENO) && t && strcmp(t, "dumb") != 0);
2393 }
2394
2395 #ifdef _WIN32
2396 \f
2397 char *
2398 ovs_format_message(int error)
2399 {
2400 enum { BUFSIZE = sizeof strerror_buffer_get()->s };
2401 char *buffer = strerror_buffer_get()->s;
2402
2403 if (error == 0) {
2404 /* See ovs_strerror */
2405 return "Success";
2406 }
2407
2408 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
2409 NULL, error, 0, buffer, BUFSIZE, NULL);
2410 return buffer;
2411 }
2412
2413 /* Returns a null-terminated string that explains the last error.
2414 * Use this function to get the error string for WINAPI calls. */
2415 char *
2416 ovs_lasterror_to_string(void)
2417 {
2418 return ovs_format_message(GetLastError());
2419 }
2420
2421 int
2422 ftruncate(int fd, off_t length)
2423 {
2424 int error;
2425
2426 error = _chsize_s(fd, length);
2427 if (error) {
2428 return -1;
2429 }
2430 return 0;
2431 }
2432
2433 OVS_CONSTRUCTOR(winsock_start) {
2434 WSADATA wsaData;
2435 int error;
2436
2437 error = WSAStartup(MAKEWORD(2, 2), &wsaData);
2438 if (error != 0) {
2439 VLOG_FATAL("WSAStartup failed: %s", sock_strerror(sock_errno()));
2440 }
2441 }
2442 #endif