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