]> git.proxmox.com Git - mirror_ovs.git/blame - lib/util.c
dpif-netdev: Fix few comments.
[mirror_ovs.git] / lib / util.c
CommitLineData
064af421 1/*
2225c0b9 2 * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016 Nicira, Inc.
064af421 3 *
a14bc59f
BP
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:
064af421 7 *
a14bc59f
BP
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.
064af421
BP
15 */
16
17#include <config.h>
18#include "util.h"
ed2232fc 19#include <ctype.h>
064af421 20#include <errno.h>
711e0157 21#include <limits.h>
5fcbed74 22#include <pthread.h>
064af421 23#include <stdarg.h>
711e0157 24#include <stdint.h>
064af421
BP
25#include <stdio.h>
26#include <stdlib.h>
27#include <string.h>
fee0c963 28#include <sys/stat.h>
daf03c53 29#include <unistd.h>
ed2232fc 30#include "bitmap.h"
ddc4f8e2 31#include "byte-order.h"
064af421 32#include "coverage.h"
275eebb9 33#include "ovs-rcu.h"
728a8b14 34#include "ovs-thread.h"
64559798 35#include "socket-util.h"
ff1d2c16 36#include "timeval.h"
e6211adc 37#include "openvswitch/vlog.h"
1805ee4b
EM
38#ifdef HAVE_PTHREAD_SET_NAME_NP
39#include <pthread_np.h>
40#endif
daf03c53 41
d98e6007 42VLOG_DEFINE_THIS_MODULE(util);
5136ce49 43
ff1d2c16
BB
44#ifdef __linux__
45#define LINUX 1
46#include <asm/param.h>
47#else
48#define LINUX 0
49#endif
50
d76f09ea
BP
51COVERAGE_DEFINE(util_xalloc);
52
781dee08 53/* argv[0] without directory names. */
91e12f0d 54char *program_name;
781dee08 55
bc9fb3a9
BP
56/* Name for the currently running thread or process, for log messages, process
57 * listings, and debuggers. */
58DEFINE_PER_THREAD_MALLOCED_DATA(char *, subprogram_name);
781dee08
BP
59
60/* --version option output. */
55d5bb44 61static char *program_version;
064af421 62
315ea327 63/* Buffer used by ovs_strerror() and ovs_format_message(). */
2ba4f163
BP
64DEFINE_STATIC_PER_THREAD_DATA(struct { char s[128]; },
65 strerror_buffer,
66 { "" });
5fcbed74 67
ac01d085
GS
68static char *xreadlink(const char *filename);
69
4749f73d
BP
70void
71ovs_assert_failure(const char *where, const char *function,
72 const char *condition)
73{
74 /* Prevent an infinite loop (or stack overflow) in case VLOG_ABORT happens
75 * to trigger an assertion failure of its own. */
76 static int reentry = 0;
77
78 switch (reentry++) {
79 case 0:
80 VLOG_ABORT("%s: assertion %s failed in %s()",
81 where, condition, function);
428b2edd 82 OVS_NOT_REACHED();
4749f73d
BP
83
84 case 1:
85 fprintf(stderr, "%s: assertion %s failed in %s()",
86 where, condition, function);
87 abort();
88
89 default:
90 abort();
91 }
92}
93
064af421 94void
d295e8e9 95out_of_memory(void)
064af421 96{
c1c8308a 97 ovs_abort(0, "virtual memory exhausted");
064af421
BP
98}
99
100void *
d295e8e9 101xcalloc(size_t count, size_t size)
064af421
BP
102{
103 void *p = count && size ? calloc(count, size) : malloc(1);
104 COVERAGE_INC(util_xalloc);
105 if (p == NULL) {
106 out_of_memory();
107 }
108 return p;
109}
110
ec6fde61
BP
111void *
112xzalloc(size_t size)
113{
114 return xcalloc(1, size);
115}
116
064af421 117void *
d295e8e9 118xmalloc(size_t size)
064af421
BP
119{
120 void *p = malloc(size ? size : 1);
121 COVERAGE_INC(util_xalloc);
122 if (p == NULL) {
123 out_of_memory();
124 }
125 return p;
126}
127
128void *
d295e8e9 129xrealloc(void *p, size_t size)
064af421
BP
130{
131 p = realloc(p, size ? size : 1);
132 COVERAGE_INC(util_xalloc);
133 if (p == NULL) {
134 out_of_memory();
135 }
136 return p;
137}
138
139void *
140xmemdup(const void *p_, size_t size)
141{
142 void *p = xmalloc(size);
316d0932 143 nullable_memcpy(p, p_, size);
064af421
BP
144 return p;
145}
146
147char *
148xmemdup0(const char *p_, size_t length)
149{
150 char *p = xmalloc(length + 1);
151 memcpy(p, p_, length);
152 p[length] = '\0';
153 return p;
154}
155
156char *
d295e8e9 157xstrdup(const char *s)
064af421
BP
158{
159 return xmemdup0(s, strlen(s));
160}
161
2225c0b9
BP
162char * MALLOC_LIKE
163nullable_xstrdup(const char *s)
164{
165 return s ? xstrdup(s) : NULL;
166}
167
aacf18c3
IM
168bool
169nullable_string_is_equal(const char *a, const char *b)
170{
171 return a ? b && !strcmp(a, b) : !b;
172}
173
064af421
BP
174char *
175xvasprintf(const char *format, va_list args)
176{
177 va_list args2;
178 size_t needed;
179 char *s;
180
181 va_copy(args2, args);
182 needed = vsnprintf(NULL, 0, format, args);
183
184 s = xmalloc(needed + 1);
185
186 vsnprintf(s, needed + 1, format, args2);
187 va_end(args2);
188
189 return s;
190}
191
192void *
193x2nrealloc(void *p, size_t *n, size_t s)
194{
195 *n = *n == 0 ? 1 : 2 * *n;
196 return xrealloc(p, *n * s);
197}
198
2fec66db
BP
199/* The desired minimum alignment for an allocated block of memory. */
200#define MEM_ALIGN MAX(sizeof(void *), 8)
201BUILD_ASSERT_DECL(IS_POW2(MEM_ALIGN));
202BUILD_ASSERT_DECL(CACHE_LINE_SIZE >= MEM_ALIGN);
203
204/* Allocates and returns 'size' bytes of memory in dedicated cache lines. That
205 * is, the memory block returned will not share a cache line with other data,
206 * avoiding "false sharing". (The memory returned will not be at the start of
207 * a cache line, though, so don't assume such alignment.)
208 *
209 * Use free_cacheline() to free the returned memory block. */
210void *
211xmalloc_cacheline(size_t size)
212{
3dc62a6c
YT
213#ifdef HAVE_POSIX_MEMALIGN
214 void *p;
215 int error;
216
217 COVERAGE_INC(util_xalloc);
218 error = posix_memalign(&p, CACHE_LINE_SIZE, size ? size : 1);
219 if (error != 0) {
220 out_of_memory();
221 }
222 return p;
223#else
2fec66db
BP
224 void **payload;
225 void *base;
226
227 /* Allocate room for:
228 *
229 * - Up to CACHE_LINE_SIZE - 1 bytes before the payload, so that the
230 * start of the payload doesn't potentially share a cache line.
231 *
232 * - A payload consisting of a void *, followed by padding out to
233 * MEM_ALIGN bytes, followed by 'size' bytes of user data.
234 *
235 * - Space following the payload up to the end of the cache line, so
236 * that the end of the payload doesn't potentially share a cache line
237 * with some following block. */
238 base = xmalloc((CACHE_LINE_SIZE - 1)
239 + ROUND_UP(MEM_ALIGN + size, CACHE_LINE_SIZE));
240
241 /* Locate the payload and store a pointer to the base at the beginning. */
242 payload = (void **) ROUND_UP((uintptr_t) base, CACHE_LINE_SIZE);
243 *payload = base;
244
245 return (char *) payload + MEM_ALIGN;
3dc62a6c 246#endif
2fec66db
BP
247}
248
249/* Like xmalloc_cacheline() but clears the allocated memory to all zero
250 * bytes. */
251void *
252xzalloc_cacheline(size_t size)
253{
254 void *p = xmalloc_cacheline(size);
255 memset(p, 0, size);
256 return p;
257}
258
259/* Frees a memory block allocated with xmalloc_cacheline() or
260 * xzalloc_cacheline(). */
261void
262free_cacheline(void *p)
263{
3dc62a6c
YT
264#ifdef HAVE_POSIX_MEMALIGN
265 free(p);
266#else
2fec66db
BP
267 if (p) {
268 free(*(void **) ((uintptr_t) p - MEM_ALIGN));
269 }
3dc62a6c 270#endif
2fec66db
BP
271}
272
064af421
BP
273char *
274xasprintf(const char *format, ...)
275{
276 va_list args;
277 char *s;
278
279 va_start(args, format);
280 s = xvasprintf(format, args);
281 va_end(args);
282
283 return s;
284}
285
e868fb3d
BP
286/* Similar to strlcpy() from OpenBSD, but it never reads more than 'size - 1'
287 * bytes from 'src' and doesn't return anything. */
064af421
BP
288void
289ovs_strlcpy(char *dst, const char *src, size_t size)
290{
291 if (size > 0) {
e868fb3d
BP
292 size_t len = strnlen(src, size - 1);
293 memcpy(dst, src, len);
294 dst[len] = '\0';
064af421
BP
295 }
296}
297
71d7c22f
BP
298/* Copies 'src' to 'dst'. Reads no more than 'size - 1' bytes from 'src'.
299 * Always null-terminates 'dst' (if 'size' is nonzero), and writes a zero byte
300 * to every otherwise unused byte in 'dst'.
301 *
302 * Except for performance, the following call:
303 * ovs_strzcpy(dst, src, size);
304 * is equivalent to these two calls:
305 * memset(dst, '\0', size);
306 * ovs_strlcpy(dst, src, size);
307 *
308 * (Thus, ovs_strzcpy() is similar to strncpy() without some of the pitfalls.)
309 */
310void
311ovs_strzcpy(char *dst, const char *src, size_t size)
312{
313 if (size > 0) {
314 size_t len = strnlen(src, size - 1);
315 memcpy(dst, src, len);
316 memset(dst + len, '\0', size - len);
317 }
318}
319
c1c8308a
BP
320/* Prints 'format' on stderr, formatting it like printf() does. If 'err_no' is
321 * nonzero, then it is formatted with ovs_retval_to_string() and appended to
322 * the message inside parentheses. Then, terminates with abort().
323 *
324 * This function is preferred to ovs_fatal() in a situation where it would make
325 * sense for a monitoring process to restart the daemon.
326 *
327 * 'format' should not end with a new-line, because this function will add one
328 * itself. */
329void
330ovs_abort(int err_no, const char *format, ...)
331{
332 va_list args;
333
334 va_start(args, format);
d41d4b71
BP
335 ovs_abort_valist(err_no, format, args);
336}
c1c8308a 337
d41d4b71
BP
338/* Same as ovs_abort() except that the arguments are supplied as a va_list. */
339void
340ovs_abort_valist(int err_no, const char *format, va_list args)
341{
342 ovs_error_valist(err_no, format, args);
c1c8308a
BP
343 abort();
344}
345
346/* Prints 'format' on stderr, formatting it like printf() does. If 'err_no' is
347 * nonzero, then it is formatted with ovs_retval_to_string() and appended to
348 * the message inside parentheses. Then, terminates with EXIT_FAILURE.
349 *
350 * 'format' should not end with a new-line, because this function will add one
351 * itself. */
064af421
BP
352void
353ovs_fatal(int err_no, const char *format, ...)
354{
355 va_list args;
356
064af421 357 va_start(args, format);
fcaddd4d
BP
358 ovs_fatal_valist(err_no, format, args);
359}
064af421 360
fcaddd4d
BP
361/* Same as ovs_fatal() except that the arguments are supplied as a va_list. */
362void
363ovs_fatal_valist(int err_no, const char *format, va_list args)
364{
365 ovs_error_valist(err_no, format, args);
064af421
BP
366 exit(EXIT_FAILURE);
367}
368
c1c8308a
BP
369/* Prints 'format' on stderr, formatting it like printf() does. If 'err_no' is
370 * nonzero, then it is formatted with ovs_retval_to_string() and appended to
371 * the message inside parentheses.
372 *
373 * 'format' should not end with a new-line, because this function will add one
374 * itself. */
064af421
BP
375void
376ovs_error(int err_no, const char *format, ...)
377{
064af421
BP
378 va_list args;
379
064af421 380 va_start(args, format);
c1c8308a 381 ovs_error_valist(err_no, format, args);
064af421 382 va_end(args);
c1c8308a
BP
383}
384
385/* Same as ovs_error() except that the arguments are supplied as a va_list. */
386void
387ovs_error_valist(int err_no, const char *format, va_list args)
388{
bc9fb3a9 389 const char *subprogram_name = get_subprogram_name();
c1c8308a
BP
390 int save_errno = errno;
391
781dee08
BP
392 if (subprogram_name[0]) {
393 fprintf(stderr, "%s(%s): ", program_name, subprogram_name);
394 } else {
395 fprintf(stderr, "%s: ", program_name);
396 }
397
c1c8308a 398 vfprintf(stderr, format, args);
0fec26b0 399 if (err_no != 0) {
c18ea70d 400 fprintf(stderr, " (%s)", ovs_retval_to_string(err_no));
0fec26b0 401 }
064af421
BP
402 putc('\n', stderr);
403
404 errno = save_errno;
405}
406
c18ea70d
AE
407/* Many OVS functions return an int which is one of:
408 * - 0: no error yet
409 * - >0: errno value
410 * - EOF: end of file (not necessarily an error; depends on the function called)
411 *
412 * Returns the appropriate human-readable string. The caller must copy the
413 * string if it wants to hold onto it, as the storage may be overwritten on
414 * subsequent function calls.
415 */
416const char *
417ovs_retval_to_string(int retval)
418{
5fcbed74
BP
419 return (!retval ? ""
420 : retval == EOF ? "End of file"
421 : ovs_strerror(retval));
422}
c18ea70d 423
b26f46a4
GS
424/* This function returns the string describing the error number in 'error'
425 * for POSIX platforms. For Windows, this function can be used for C library
426 * calls. For socket calls that are also used in Windows, use sock_strerror()
427 * instead. For WINAPI calls, look at ovs_lasterror_to_string(). */
5fcbed74
BP
428const char *
429ovs_strerror(int error)
430{
431 enum { BUFSIZE = sizeof strerror_buffer_get()->s };
432 int save_errno;
433 char *buffer;
434 char *s;
435
11b7f938
YT
436 if (error == 0) {
437 /*
438 * strerror(0) varies among platforms:
439 *
440 * Success
441 * No error
442 * Undefined error: 0
443 *
444 * We want to provide a consistent result here because
445 * our testsuite has test cases which strictly matches
446 * log messages containing this string.
447 */
448 return "Success";
449 }
450
5fcbed74
BP
451 save_errno = errno;
452 buffer = strerror_buffer_get()->s;
453
454#if STRERROR_R_CHAR_P
455 /* GNU style strerror_r() might return an immutable static string, or it
456 * might write and return 'buffer', but in either case we can pass the
457 * returned string directly to the caller. */
458 s = strerror_r(error, buffer, BUFSIZE);
459#else /* strerror_r() returns an int. */
460 s = buffer;
461 if (strerror_r(error, buffer, BUFSIZE)) {
462 /* strerror_r() is only allowed to fail on ERANGE (because the buffer
463 * is too short). We don't check the actual failure reason because
464 * POSIX requires strerror_r() to return the error but old glibc
465 * (before 2.13) returns -1 and sets errno. */
5865a8af 466 snprintf(buffer, BUFSIZE, "Unknown error %d", error);
c18ea70d 467 }
5fcbed74
BP
468#endif
469
470 errno = save_errno;
471
472 return s;
c18ea70d
AE
473}
474
55d5bb44
JP
475/* Sets global "program_name" and "program_version" variables. Should
476 * be called at the beginning of main() with "argv[0]" as the argument
477 * to 'argv0'.
478 *
e385ef55
EJ
479 * 'version' should contain the version of the caller's program. If 'version'
480 * is the same as the VERSION #define, the caller is assumed to be part of Open
481 * vSwitch. Otherwise, it is assumed to be an external program linking against
482 * the Open vSwitch libraries.
483 *
55d5bb44
JP
484 */
485void
fa54d373 486ovs_set_program_name(const char *argv0, const char *version)
064af421 487{
ed596d3a 488 char *basename;
91e12f0d 489#ifdef _WIN32
ed596d3a 490 size_t max_len = strlen(argv0) + 1;
fda546bd 491
144ccc02 492 SetErrorMode(GetErrorMode() | SEM_NOGPFAULTERRORBOX);
c9f80f7f 493 _set_output_format(_TWO_DIGIT_EXPONENT);
144ccc02 494
ed596d3a
GS
495 basename = xmalloc(max_len);
496 _splitpath_s(argv0, NULL, 0, NULL, 0, basename, max_len, NULL, 0);
ed596d3a 497#else
064af421 498 const char *slash = strrchr(argv0, '/');
91e12f0d 499 basename = xstrdup(slash ? slash + 1 : argv0);
ed596d3a 500#endif
55d5bb44 501
91e12f0d
AA
502 assert_single_threaded();
503 free(program_name);
7f2f24e3
SM
504 /* Remove libtool prefix, if it is there */
505 if (strncmp(basename, "lt-", 3) == 0) {
506 char *tmp_name = basename;
507 basename = xstrdup(basename + 3);
508 free(tmp_name);
509 }
91e12f0d 510 program_name = basename;
e385ef55 511
7f2f24e3 512 free(program_version);
e385ef55 513 if (!strcmp(version, VERSION)) {
fa54d373
MC
514 program_version = xasprintf("%s (Open vSwitch) "VERSION"\n",
515 program_name);
e385ef55
EJ
516 } else {
517 program_version = xasprintf("%s %s\n"
fa54d373
MC
518 "Open vSwitch Library "VERSION"\n",
519 program_name, version);
e385ef55 520 }
55d5bb44
JP
521}
522
bc9fb3a9
BP
523/* Returns the name of the currently running thread or process. */
524const char *
525get_subprogram_name(void)
526{
527 const char *name = subprogram_name_get();
528 return name ? name : "";
529}
530
40e7cf56
BP
531/* Sets 'subprogram_name' as the name of the currently running thread or
532 * process. (This appears in log messages and may also be visible in system
533 * process listings and debuggers.) */
bc9fb3a9 534void
40e7cf56 535set_subprogram_name(const char *subprogram_name)
bc9fb3a9 536{
40e7cf56 537 char *pname = xstrdup(subprogram_name ? subprogram_name : program_name);
d710edc4
BP
538 free(subprogram_name_set(pname));
539
8a8cd0ac 540#if HAVE_GLIBC_PTHREAD_SETNAME_NP
e584f6a8 541 pthread_setname_np(pthread_self(), pname);
8a8cd0ac 542#elif HAVE_NETBSD_PTHREAD_SETNAME_NP
e584f6a8 543 pthread_setname_np(pthread_self(), "%s", pname);
0f13e650 544#elif HAVE_PTHREAD_SET_NAME_NP
e584f6a8 545 pthread_set_name_np(pthread_self(), pname);
0f13e650 546#endif
bc9fb3a9
BP
547}
548
ff1d2c16
BB
549unsigned int
550get_page_size(void)
551{
552 static unsigned int cached;
553
554 if (!cached) {
555#ifndef _WIN32
556 long int value = sysconf(_SC_PAGESIZE);
557#else
558 long int value;
559 SYSTEM_INFO sysinfo;
560 GetSystemInfo(&sysinfo);
561 value = sysinfo.dwPageSize;
562#endif
563 if (value >= 0) {
564 cached = value;
565 }
566 }
567
568 return cached;
569}
570
571/* Returns the time at which the system booted, as the number of milliseconds
572 * since the epoch, or 0 if the time of boot cannot be determined. */
573long long int
574get_boot_time(void)
575{
576 static long long int cache_expiration = LLONG_MIN;
577 static long long int boot_time;
578
579 ovs_assert(LINUX);
580
581 if (time_msec() >= cache_expiration) {
582 static const char stat_file[] = "/proc/stat";
583 char line[128];
584 FILE *stream;
585
586 cache_expiration = time_msec() + 5 * 1000;
587
588 stream = fopen(stat_file, "r");
589 if (!stream) {
590 VLOG_ERR_ONCE("%s: open failed (%s)",
591 stat_file, ovs_strerror(errno));
592 return boot_time;
593 }
594
595 while (fgets(line, sizeof line, stream)) {
596 long long int btime;
597 if (ovs_scan(line, "btime %lld", &btime)) {
598 boot_time = btime * 1000;
599 goto done;
600 }
601 }
602 VLOG_ERR_ONCE("%s: btime not found", stat_file);
603 done:
604 fclose(stream);
605 }
606 return boot_time;
607}
608
55d5bb44
JP
609/* Returns a pointer to a string describing the program version. The
610 * caller must not modify or free the returned string.
b53055f4 611 */
55d5bb44 612const char *
b0248b2a 613ovs_get_program_version(void)
55d5bb44
JP
614{
615 return program_version;
064af421
BP
616}
617
b0248b2a
TG
618/* Returns a pointer to a string describing the program name. The
619 * caller must not modify or free the returned string.
620 */
621const char *
622ovs_get_program_name(void)
623{
624 return program_name;
625}
626
064af421
BP
627/* Print the version information for the program. */
628void
55d5bb44 629ovs_print_version(uint8_t min_ofp, uint8_t max_ofp)
064af421 630{
55d5bb44 631 printf("%s", program_version);
064af421
BP
632 if (min_ofp || max_ofp) {
633 printf("OpenFlow versions %#x:%#x\n", min_ofp, max_ofp);
634 }
635}
636
637/* Writes the 'size' bytes in 'buf' to 'stream' as hex bytes arranged 16 per
638 * line. Numeric offsets are also included, starting at 'ofs' for the first
639 * byte in 'buf'. If 'ascii' is true then the corresponding ASCII characters
640 * are also rendered alongside. */
641void
642ovs_hex_dump(FILE *stream, const void *buf_, size_t size,
643 uintptr_t ofs, bool ascii)
644{
645 const uint8_t *buf = buf_;
646 const size_t per_line = 16; /* Maximum bytes per line. */
647
648 while (size > 0)
649 {
650 size_t start, end, n;
651 size_t i;
652
653 /* Number of bytes on this line. */
654 start = ofs % per_line;
655 end = per_line;
656 if (end - start > size)
657 end = start + size;
658 n = end - start;
659
660 /* Print line. */
34582733 661 fprintf(stream, "%08"PRIxMAX" ", (uintmax_t) ROUND_DOWN(ofs, per_line));
064af421
BP
662 for (i = 0; i < start; i++)
663 fprintf(stream, " ");
664 for (; i < end; i++)
34582733 665 fprintf(stream, "%02x%c",
064af421
BP
666 buf[i - start], i == per_line / 2 - 1? '-' : ' ');
667 if (ascii)
668 {
669 for (; i < per_line; i++)
670 fprintf(stream, " ");
671 fprintf(stream, "|");
672 for (i = 0; i < start; i++)
673 fprintf(stream, " ");
674 for (; i < end; i++) {
675 int c = buf[i - start];
676 putc(c >= 32 && c < 127 ? c : '.', stream);
677 }
678 for (; i < per_line; i++)
679 fprintf(stream, " ");
680 fprintf(stream, "|");
681 }
682 fprintf(stream, "\n");
683
684 ofs += n;
685 buf += n;
686 size -= n;
687 }
688}
689
690bool
691str_to_int(const char *s, int base, int *i)
692{
693 long long ll;
694 bool ok = str_to_llong(s, base, &ll);
695 *i = ll;
696 return ok;
697}
698
699bool
700str_to_long(const char *s, int base, long *li)
701{
702 long long ll;
703 bool ok = str_to_llong(s, base, &ll);
704 *li = ll;
705 return ok;
706}
707
708bool
709str_to_llong(const char *s, int base, long long *x)
710{
064af421 711 char *tail;
1ab39058
LR
712 bool ok = str_to_llong_with_tail(s, &tail, base, x);
713 if (*tail != '\0') {
714 *x = 0;
715 return false;
716 }
717 return ok;
718}
719
720bool
721str_to_llong_with_tail(const char *s, char **tail, int base, long long *x)
722{
723 int save_errno = errno;
064af421 724 errno = 0;
1ab39058
LR
725 *x = strtoll(s, tail, base);
726 if (errno == EINVAL || errno == ERANGE || *tail == s) {
064af421
BP
727 errno = save_errno;
728 *x = 0;
729 return false;
730 } else {
731 errno = save_errno;
732 return true;
733 }
734}
735
4c21aa06
ZK
736bool
737str_to_uint(const char *s, int base, unsigned int *u)
738{
739 long long ll;
740 bool ok = str_to_llong(s, base, &ll);
741 if (!ok || ll < 0 || ll > UINT_MAX) {
a42023ee
AZ
742 *u = 0;
743 return false;
4c21aa06 744 } else {
a42023ee
AZ
745 *u = ll;
746 return true;
4c21aa06
ZK
747 }
748}
749
1ab39058
LR
750bool
751str_to_llong_range(const char *s, int base, long long *begin,
752 long long *end)
753{
754 char *tail;
755 if (str_to_llong_with_tail(s, &tail, base, begin)
756 && *tail == '-'
757 && str_to_llong(tail + 1, base, end)) {
758 return true;
759 }
760 *begin = 0;
761 *end = 0;
762 return false;
763}
764
f38b84ea
BP
765/* Converts floating-point string 's' into a double. If successful, stores
766 * the double in '*d' and returns true; on failure, stores 0 in '*d' and
767 * returns false.
768 *
769 * Underflow (e.g. "1e-9999") is not considered an error, but overflow
770 * (e.g. "1e9999)" is. */
771bool
772str_to_double(const char *s, double *d)
773{
774 int save_errno = errno;
775 char *tail;
776 errno = 0;
777 *d = strtod(s, &tail);
778 if (errno == EINVAL || (errno == ERANGE && *d != 0)
779 || tail == s || *tail != '\0') {
780 errno = save_errno;
781 *d = 0;
782 return false;
783 } else {
784 errno = save_errno;
785 return true;
786 }
787}
788
789/* Returns the value of 'c' as a hexadecimal digit. */
790int
791hexit_value(int c)
792{
793 switch (c) {
794 case '0': case '1': case '2': case '3': case '4':
795 case '5': case '6': case '7': case '8': case '9':
796 return c - '0';
797
798 case 'a': case 'A':
799 return 0xa;
800
801 case 'b': case 'B':
802 return 0xb;
803
804 case 'c': case 'C':
805 return 0xc;
806
807 case 'd': case 'D':
808 return 0xd;
809
810 case 'e': case 'E':
811 return 0xe;
812
813 case 'f': case 'F':
814 return 0xf;
f38b84ea 815
09246b99
BP
816 default:
817 return -1;
818 }
f38b84ea 819}
29d4af60 820
bf971267 821/* Returns the integer value of the 'n' hexadecimal digits starting at 's', or
0429d959
BP
822 * UINTMAX_MAX if one of those "digits" is not really a hex digit. Sets '*ok'
823 * to true if the conversion succeeds or to false if a non-hex digit is
824 * detected. */
825uintmax_t
bf971267
BP
826hexits_value(const char *s, size_t n, bool *ok)
827{
0429d959 828 uintmax_t value;
bf971267
BP
829 size_t i;
830
831 value = 0;
832 for (i = 0; i < n; i++) {
833 int hexit = hexit_value(s[i]);
834 if (hexit < 0) {
0429d959
BP
835 *ok = false;
836 return UINTMAX_MAX;
bf971267
BP
837 }
838 value = (value << 4) + hexit;
839 }
0429d959 840 *ok = true;
bf971267
BP
841 return value;
842}
843
e7ae59f9
JG
844/* Parses the string in 's' as an integer in either hex or decimal format and
845 * puts the result right justified in the array 'valuep' that is 'field_width'
846 * big. If the string is in hex format, the value may be arbitrarily large;
847 * integers are limited to 64-bit values. (The rationale is that decimal is
848 * likely to represent a number and 64 bits is a reasonable maximum whereas
849 * hex could either be a number or a byte string.)
850 *
851 * On return 'tail' points to the first character in the string that was
852 * not parsed as part of the value. ERANGE is returned if the value is too
853 * large to fit in the given field. */
854int
855parse_int_string(const char *s, uint8_t *valuep, int field_width, char **tail)
856{
857 unsigned long long int integer;
858 int i;
859
860 if (!strncmp(s, "0x", 2) || !strncmp(s, "0X", 2)) {
861 uint8_t *hexit_str;
862 int len = 0;
863 int val_idx;
864 int err = 0;
865
866 s += 2;
867 hexit_str = xmalloc(field_width * 2);
868
869 for (;;) {
870 uint8_t hexit;
871 bool ok;
872
873 s += strspn(s, " \t\r\n");
874 hexit = hexits_value(s, 1, &ok);
875 if (!ok) {
876 *tail = CONST_CAST(char *, s);
877 break;
878 }
879
880 if (hexit != 0 || len) {
881 if (DIV_ROUND_UP(len + 1, 2) > field_width) {
882 err = ERANGE;
883 goto free;
884 }
885
886 hexit_str[len] = hexit;
887 len++;
888 }
889 s++;
890 }
891
892 val_idx = field_width;
893 for (i = len - 1; i >= 0; i -= 2) {
894 val_idx--;
895 valuep[val_idx] = hexit_str[i];
896 if (i > 0) {
897 valuep[val_idx] += hexit_str[i - 1] << 4;
898 }
899 }
900
901 memset(valuep, 0, val_idx);
902
903free:
904 free(hexit_str);
a42023ee 905 return err;
e7ae59f9
JG
906 }
907
908 errno = 0;
909 integer = strtoull(s, tail, 0);
910 if (errno) {
911 return errno;
912 }
913
914 for (i = field_width - 1; i >= 0; i--) {
915 valuep[i] = integer;
916 integer >>= 8;
917 }
918 if (integer) {
919 return ERANGE;
920 }
921
922 return 0;
923}
924
daf03c53
BP
925/* Returns the current working directory as a malloc()'d string, or a null
926 * pointer if the current working directory cannot be determined. */
927char *
928get_cwd(void)
929{
930 long int path_max;
931 size_t size;
932
933 /* Get maximum path length or at least a reasonable estimate. */
661c32dc 934#ifndef _WIN32
daf03c53 935 path_max = pathconf(".", _PC_PATH_MAX);
661c32dc
GS
936#else
937 path_max = MAX_PATH;
938#endif
daf03c53
BP
939 size = (path_max < 0 ? 1024
940 : path_max > 10240 ? 10240
941 : path_max);
942
943 /* Get current working directory. */
944 for (;;) {
945 char *buf = xmalloc(size);
946 if (getcwd(buf, size)) {
947 return xrealloc(buf, strlen(buf) + 1);
948 } else {
949 int error = errno;
950 free(buf);
951 if (error != ERANGE) {
10a89ef0 952 VLOG_WARN("getcwd failed (%s)", ovs_strerror(error));
daf03c53
BP
953 return NULL;
954 }
955 size *= 2;
956 }
957 }
958}
959
e1aff6f9
BP
960static char *
961all_slashes_name(const char *s)
962{
963 return xstrdup(s[0] == '/' && s[1] == '/' && s[2] != '/' ? "//"
964 : s[0] == '/' ? "/"
965 : ".");
966}
967
3c1150ce 968#ifndef _WIN32
29d4af60
BP
969/* Returns the directory name portion of 'file_name' as a malloc()'d string,
970 * similar to the POSIX dirname() function but thread-safe. */
971char *
972dir_name(const char *file_name)
973{
974 size_t len = strlen(file_name);
975 while (len > 0 && file_name[len - 1] == '/') {
976 len--;
977 }
978 while (len > 0 && file_name[len - 1] != '/') {
979 len--;
980 }
981 while (len > 0 && file_name[len - 1] == '/') {
982 len--;
983 }
e1aff6f9
BP
984 return len ? xmemdup0(file_name, len) : all_slashes_name(file_name);
985}
986
987/* Returns the file name portion of 'file_name' as a malloc()'d string,
988 * similar to the POSIX basename() function but thread-safe. */
989char *
990base_name(const char *file_name)
991{
992 size_t end, start;
993
994 end = strlen(file_name);
995 while (end > 0 && file_name[end - 1] == '/') {
996 end--;
997 }
998
999 if (!end) {
1000 return all_slashes_name(file_name);
29d4af60 1001 }
e1aff6f9
BP
1002
1003 start = end;
1004 while (start > 0 && file_name[start - 1] != '/') {
1005 start--;
1006 }
1007
1008 return xmemdup0(file_name + start, end - start);
29d4af60 1009}
3c1150ce 1010#endif /* _WIN32 */
18b9283b 1011
daf03c53
BP
1012/* If 'file_name' starts with '/', returns a copy of 'file_name'. Otherwise,
1013 * returns an absolute path to 'file_name' considering it relative to 'dir',
1014 * which itself must be absolute. 'dir' may be null or the empty string, in
1015 * which case the current working directory is used.
1016 *
ee8749ca
AS
1017 * Additionally on Windows, if 'file_name' has a ':', returns a copy of
1018 * 'file_name'
1019 *
daf03c53
BP
1020 * Returns a null pointer if 'dir' is null and getcwd() fails. */
1021char *
1022abs_file_name(const char *dir, const char *file_name)
1023{
1024 if (file_name[0] == '/') {
1025 return xstrdup(file_name);
ee8749ca
AS
1026#ifdef _WIN32
1027 } else if (strchr(file_name, ':')) {
1028 return xstrdup(file_name);
1029#endif
daf03c53
BP
1030 } else if (dir && dir[0]) {
1031 char *separator = dir[strlen(dir) - 1] == '/' ? "" : "/";
1032 return xasprintf("%s%s%s", dir, separator, file_name);
1033 } else {
1034 char *cwd = get_cwd();
1035 if (cwd) {
1036 char *abs_name = xasprintf("%s/%s", cwd, file_name);
1037 free(cwd);
1038 return abs_name;
1039 } else {
1040 return NULL;
1041 }
1042 }
1043}
1044
fee0c963
BP
1045/* Like readlink(), but returns the link name as a null-terminated string in
1046 * allocated memory that the caller must eventually free (with free()).
1047 * Returns NULL on error, in which case errno is set appropriately. */
ac01d085 1048static char *
fee0c963
BP
1049xreadlink(const char *filename)
1050{
f984769f
AS
1051#ifdef _WIN32
1052 errno = ENOENT;
1053 return NULL;
1054#else
fee0c963
BP
1055 size_t size;
1056
1057 for (size = 64; ; size *= 2) {
1058 char *buf = xmalloc(size);
1059 ssize_t retval = readlink(filename, buf, size);
1060 int error = errno;
1061
1062 if (retval >= 0 && retval < size) {
1063 buf[retval] = '\0';
1064 return buf;
1065 }
1066
1067 free(buf);
1068 if (retval < 0) {
1069 errno = error;
1070 return NULL;
1071 }
1072 }
f984769f 1073#endif
fee0c963
BP
1074}
1075
1076/* Returns a version of 'filename' with symlinks in the final component
1077 * dereferenced. This differs from realpath() in that:
1078 *
1079 * - 'filename' need not exist.
1080 *
1081 * - If 'filename' does exist as a symlink, its referent need not exist.
1082 *
1083 * - Only symlinks in the final component of 'filename' are dereferenced.
1084 *
e9f56e84
GS
1085 * For Windows platform, this function returns a string that has the same
1086 * value as the passed string.
1087 *
fee0c963
BP
1088 * The caller must eventually free the returned string (with free()). */
1089char *
1090follow_symlinks(const char *filename)
1091{
e9f56e84 1092#ifndef _WIN32
fee0c963
BP
1093 struct stat s;
1094 char *fn;
1095 int i;
1096
1097 fn = xstrdup(filename);
1098 for (i = 0; i < 10; i++) {
1099 char *linkname;
1100 char *next_fn;
1101
1102 if (lstat(fn, &s) != 0 || !S_ISLNK(s.st_mode)) {
1103 return fn;
1104 }
1105
1106 linkname = xreadlink(fn);
1107 if (!linkname) {
10a89ef0
BP
1108 VLOG_WARN("%s: readlink failed (%s)",
1109 filename, ovs_strerror(errno));
fee0c963
BP
1110 return fn;
1111 }
1112
1113 if (linkname[0] == '/') {
1114 /* Target of symlink is absolute so use it raw. */
1115 next_fn = linkname;
1116 } else {
1117 /* Target of symlink is relative so add to 'fn''s directory. */
1118 char *dir = dir_name(fn);
1119
1120 if (!strcmp(dir, ".")) {
1121 next_fn = linkname;
1122 } else {
1123 char *separator = dir[strlen(dir) - 1] == '/' ? "" : "/";
1124 next_fn = xasprintf("%s%s%s", dir, separator, linkname);
1125 free(linkname);
1126 }
1127
1128 free(dir);
1129 }
1130
1131 free(fn);
1132 fn = next_fn;
1133 }
1134
1135 VLOG_WARN("%s: too many levels of symlinks", filename);
1136 free(fn);
e9f56e84 1137#endif
fee0c963
BP
1138 return xstrdup(filename);
1139}
daf03c53 1140
18b9283b 1141/* Pass a value to this function if it is marked with
d295e8e9
JP
1142 * __attribute__((warn_unused_result)) and you genuinely want to ignore
1143 * its return value. (Note that every scalar type can be implicitly
18b9283b 1144 * converted to bool.) */
c69ee87c 1145void ignore(bool x OVS_UNUSED) { }
44b4d050
BP
1146
1147/* Returns an appropriate delimiter for inserting just before the 0-based item
1148 * 'index' in a list that has 'total' items in it. */
1149const char *
1150english_list_delimiter(size_t index, size_t total)
1151{
1152 return (index == 0 ? ""
1153 : index < total - 1 ? ", "
1154 : total > 2 ? ", and "
1155 : " and ");
1156}
711e0157 1157
0ee140fb 1158/* Returns the number of trailing 0-bits in 'n'. Undefined if 'n' == 0. */
25f45143 1159#if __GNUC__ >= 4 || _MSC_VER
0ee140fb 1160/* Defined inline in util.h. */
aad29cd1 1161#else
8c947903 1162/* Returns the number of trailing 0-bits in 'n'. Undefined if 'n' == 0. */
481da12c 1163int
d43d314e 1164raw_ctz(uint64_t n)
0ee140fb 1165{
d43d314e
BP
1166 uint64_t k;
1167 int count = 63;
aad29cd1
BP
1168
1169#define CTZ_STEP(X) \
0ee140fb
BP
1170 k = n << (X); \
1171 if (k) { \
1172 count -= X; \
1173 n = k; \
1174 }
d43d314e 1175 CTZ_STEP(32);
0ee140fb
BP
1176 CTZ_STEP(16);
1177 CTZ_STEP(8);
1178 CTZ_STEP(4);
1179 CTZ_STEP(2);
1180 CTZ_STEP(1);
aad29cd1
BP
1181#undef CTZ_STEP
1182
0ee140fb 1183 return count;
aad29cd1 1184}
8c947903
JR
1185
1186/* Returns the number of leading 0-bits in 'n'. Undefined if 'n' == 0. */
1187int
1188raw_clz64(uint64_t n)
1189{
1190 uint64_t k;
1191 int count = 63;
1192
1193#define CLZ_STEP(X) \
1194 k = n >> (X); \
1195 if (k) { \
1196 count -= X; \
1197 n = k; \
1198 }
1199 CLZ_STEP(32);
1200 CLZ_STEP(16);
1201 CLZ_STEP(8);
1202 CLZ_STEP(4);
1203 CLZ_STEP(2);
1204 CLZ_STEP(1);
1205#undef CLZ_STEP
1206
1207 return count;
1208}
0ee140fb 1209#endif
75a75043 1210
381657b3 1211#if NEED_COUNT_1BITS_8
a656cb77
BP
1212#define INIT1(X) \
1213 ((((X) & (1 << 0)) != 0) + \
1214 (((X) & (1 << 1)) != 0) + \
1215 (((X) & (1 << 2)) != 0) + \
1216 (((X) & (1 << 3)) != 0) + \
1217 (((X) & (1 << 4)) != 0) + \
1218 (((X) & (1 << 5)) != 0) + \
1219 (((X) & (1 << 6)) != 0) + \
1220 (((X) & (1 << 7)) != 0))
1221#define INIT2(X) INIT1(X), INIT1((X) + 1)
1222#define INIT4(X) INIT2(X), INIT2((X) + 2)
1223#define INIT8(X) INIT4(X), INIT4((X) + 4)
1224#define INIT16(X) INIT8(X), INIT8((X) + 8)
1225#define INIT32(X) INIT16(X), INIT16((X) + 16)
1226#define INIT64(X) INIT32(X), INIT32((X) + 32)
1227
c3cc4d2d
JR
1228const uint8_t count_1bits_8[256] = {
1229 INIT64(0), INIT64(64), INIT64(128), INIT64(192)
1230};
1231#endif
2a4ca27c 1232
75a75043
BP
1233/* Returns true if the 'n' bytes starting at 'p' are zeros. */
1234bool
53cb9c3e 1235is_all_zeros(const void *p_, size_t n)
75a75043 1236{
53cb9c3e 1237 const uint8_t *p = p_;
75a75043
BP
1238 size_t i;
1239
1240 for (i = 0; i < n; i++) {
1241 if (p[i] != 0x00) {
1242 return false;
1243 }
1244 }
1245 return true;
1246}
1247
1248/* Returns true if the 'n' bytes starting at 'p' are 0xff. */
1249bool
53cb9c3e 1250is_all_ones(const void *p_, size_t n)
75a75043 1251{
53cb9c3e 1252 const uint8_t *p = p_;
75a75043
BP
1253 size_t i;
1254
1255 for (i = 0; i < n; i++) {
1256 if (p[i] != 0xff) {
1257 return false;
1258 }
1259 }
1260 return true;
1261}
1262
ddc4f8e2
BP
1263/* Copies 'n_bits' bits starting from bit 'src_ofs' in 'src' to the 'n_bits'
1264 * starting from bit 'dst_ofs' in 'dst'. 'src' is 'src_len' bytes long and
1265 * 'dst' is 'dst_len' bytes long.
1266 *
1267 * If you consider all of 'src' to be a single unsigned integer in network byte
1268 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1269 * with value 1 in src[src_len - 1], bit 1 is the bit with value 2, bit 2 is
1270 * the bit with value 4, ..., bit 8 is the bit with value 1 in src[src_len -
1271 * 2], and so on. Similarly for 'dst'.
1272 *
1273 * Required invariants:
1274 * src_ofs + n_bits <= src_len * 8
1275 * dst_ofs + n_bits <= dst_len * 8
1276 * 'src' and 'dst' must not overlap.
1277 */
1278void
1279bitwise_copy(const void *src_, unsigned int src_len, unsigned int src_ofs,
1280 void *dst_, unsigned int dst_len, unsigned int dst_ofs,
1281 unsigned int n_bits)
1282{
1283 const uint8_t *src = src_;
1284 uint8_t *dst = dst_;
1285
1286 src += src_len - (src_ofs / 8 + 1);
1287 src_ofs %= 8;
1288
1289 dst += dst_len - (dst_ofs / 8 + 1);
1290 dst_ofs %= 8;
1291
1292 if (src_ofs == 0 && dst_ofs == 0) {
1293 unsigned int n_bytes = n_bits / 8;
1294 if (n_bytes) {
1295 dst -= n_bytes - 1;
1296 src -= n_bytes - 1;
1297 memcpy(dst, src, n_bytes);
1298
1299 n_bits %= 8;
1300 src--;
1301 dst--;
1302 }
1303 if (n_bits) {
1304 uint8_t mask = (1 << n_bits) - 1;
1305 *dst = (*dst & ~mask) | (*src & mask);
1306 }
1307 } else {
1308 while (n_bits > 0) {
1309 unsigned int max_copy = 8 - MAX(src_ofs, dst_ofs);
1310 unsigned int chunk = MIN(n_bits, max_copy);
1311 uint8_t mask = ((1 << chunk) - 1) << dst_ofs;
1312
1313 *dst &= ~mask;
1314 *dst |= ((*src >> src_ofs) << dst_ofs) & mask;
1315
1316 src_ofs += chunk;
1317 if (src_ofs == 8) {
1318 src--;
1319 src_ofs = 0;
1320 }
1321 dst_ofs += chunk;
1322 if (dst_ofs == 8) {
1323 dst--;
1324 dst_ofs = 0;
1325 }
1326 n_bits -= chunk;
1327 }
1328 }
1329}
1330
6cc7ea5e
BP
1331/* Zeros the 'n_bits' bits starting from bit 'dst_ofs' in 'dst'. 'dst' is
1332 * 'dst_len' bytes long.
1333 *
1334 * If you consider all of 'dst' to be a single unsigned integer in network byte
1335 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1336 * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
1337 * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
1338 * 2], and so on.
1339 *
1340 * Required invariant:
1341 * dst_ofs + n_bits <= dst_len * 8
1342 */
1343void
1344bitwise_zero(void *dst_, unsigned int dst_len, unsigned dst_ofs,
1345 unsigned int n_bits)
1346{
1347 uint8_t *dst = dst_;
1348
1349 if (!n_bits) {
1350 return;
1351 }
1352
1353 dst += dst_len - (dst_ofs / 8 + 1);
1354 dst_ofs %= 8;
1355
1356 if (dst_ofs) {
1357 unsigned int chunk = MIN(n_bits, 8 - dst_ofs);
1358
1359 *dst &= ~(((1 << chunk) - 1) << dst_ofs);
1360
1361 n_bits -= chunk;
1362 if (!n_bits) {
1363 return;
1364 }
1365
1366 dst--;
1367 }
1368
1369 while (n_bits >= 8) {
1370 *dst-- = 0;
1371 n_bits -= 8;
1372 }
1373
1374 if (n_bits) {
1375 *dst &= ~((1 << n_bits) - 1);
1376 }
1377}
1378
c2dd4932
BP
1379/* Sets to 1 all of the 'n_bits' bits starting from bit 'dst_ofs' in 'dst'.
1380 * 'dst' is 'dst_len' bytes long.
1381 *
1382 * If you consider all of 'dst' to be a single unsigned integer in network byte
1383 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1384 * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
1385 * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
1386 * 2], and so on.
1387 *
1388 * Required invariant:
1389 * dst_ofs + n_bits <= dst_len * 8
1390 */
1391void
1392bitwise_one(void *dst_, unsigned int dst_len, unsigned dst_ofs,
1393 unsigned int n_bits)
1394{
1395 uint8_t *dst = dst_;
1396
1397 if (!n_bits) {
1398 return;
1399 }
1400
1401 dst += dst_len - (dst_ofs / 8 + 1);
1402 dst_ofs %= 8;
1403
1404 if (dst_ofs) {
1405 unsigned int chunk = MIN(n_bits, 8 - dst_ofs);
1406
1407 *dst |= ((1 << chunk) - 1) << dst_ofs;
1408
1409 n_bits -= chunk;
1410 if (!n_bits) {
1411 return;
1412 }
1413
1414 dst--;
1415 }
1416
1417 while (n_bits >= 8) {
1418 *dst-- = 0xff;
1419 n_bits -= 8;
1420 }
1421
1422 if (n_bits) {
1423 *dst |= (1 << n_bits) - 1;
1424 }
1425}
1426
79a010aa
BP
1427/* Scans the 'n_bits' bits starting from bit 'dst_ofs' in 'dst' for 1-bits.
1428 * Returns false if any 1-bits are found, otherwise true. 'dst' is 'dst_len'
1429 * bytes long.
1430 *
1431 * If you consider all of 'dst' to be a single unsigned integer in network byte
1432 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1433 * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
1434 * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
1435 * 2], and so on.
1436 *
1437 * Required invariant:
1438 * dst_ofs + n_bits <= dst_len * 8
1439 */
1440bool
1441bitwise_is_all_zeros(const void *p_, unsigned int len, unsigned int ofs,
1442 unsigned int n_bits)
1443{
1444 const uint8_t *p = p_;
1445
1446 if (!n_bits) {
1447 return true;
1448 }
1449
1450 p += len - (ofs / 8 + 1);
1451 ofs %= 8;
1452
1453 if (ofs) {
1454 unsigned int chunk = MIN(n_bits, 8 - ofs);
1455
1456 if (*p & (((1 << chunk) - 1) << ofs)) {
1457 return false;
1458 }
1459
1460 n_bits -= chunk;
1461 if (!n_bits) {
1462 return true;
1463 }
1464
1465 p--;
1466 }
1467
1468 while (n_bits >= 8) {
1469 if (*p) {
1470 return false;
1471 }
1472 n_bits -= 8;
1473 p--;
1474 }
1475
1476 if (n_bits && *p & ((1 << n_bits) - 1)) {
1477 return false;
1478 }
1479
1480 return true;
1481}
1482
95a92d5a
BP
1483/* Scans the bits in 'p' that have bit offsets 'start' (inclusive) through
1484 * 'end' (exclusive) for the first bit with value 'target'. If one is found,
1485 * returns its offset, otherwise 'end'. 'p' is 'len' bytes long.
099c06e3
BP
1486 *
1487 * If you consider all of 'p' to be a single unsigned integer in network byte
1488 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1489 * with value 1 in p[len - 1], bit 1 is the bit with value 2, bit 2 is the bit
1490 * with value 4, ..., bit 8 is the bit with value 1 in p[len - 2], and so on.
1491 *
1492 * Required invariant:
1493 * start <= end
1494 */
1495unsigned int
95a92d5a 1496bitwise_scan(const void *p, unsigned int len, bool target, unsigned int start,
099c06e3
BP
1497 unsigned int end)
1498{
099c06e3
BP
1499 unsigned int ofs;
1500
1501 for (ofs = start; ofs < end; ofs++) {
95a92d5a 1502 if (bitwise_get_bit(p, len, ofs) == target) {
099c06e3
BP
1503 break;
1504 }
1505 }
1506 return ofs;
1507}
1508
95a92d5a
BP
1509/* Scans the bits in 'p' that have bit offsets 'start' (inclusive) through
1510 * 'end' (exclusive) for the first bit with value 'target', in reverse order.
1511 * If one is found, returns its offset, otherwise 'end'. 'p' is 'len' bytes
1512 * long.
1513 *
1514 * If you consider all of 'p' to be a single unsigned integer in network byte
1515 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1516 * with value 1 in p[len - 1], bit 1 is the bit with value 2, bit 2 is the bit
1517 * with value 4, ..., bit 8 is the bit with value 1 in p[len - 2], and so on.
1518 *
1519 * To scan an entire bit array in reverse order, specify start == len * 8 - 1
1520 * and end == -1, in which case the return value is nonnegative if successful
1521 * and -1 if no 'target' match is found.
1522 *
1523 * Required invariant:
1524 * start >= end
1525 */
1526int
1527bitwise_rscan(const void *p, unsigned int len, bool target, int start, int end)
1528{
76adea87
HZ
1529 const uint8_t *s = p;
1530 int start_byte = len - (start / 8 + 1);
1531 int end_byte = len - (end / 8 + 1);
1532 int ofs_byte;
95a92d5a 1533 int ofs;
76adea87 1534 uint8_t the_byte;
95a92d5a 1535
76adea87
HZ
1536 /* Find the target in the start_byte from starting offset */
1537 ofs_byte = start_byte;
1538 the_byte = s[ofs_byte];
1539 for (ofs = start % 8; ofs >= 0; ofs--) {
1540 if (((the_byte & (1u << ofs)) != 0) == target) {
95a92d5a
BP
1541 break;
1542 }
1543 }
76adea87
HZ
1544 if (ofs < 0) {
1545 /* Target not found in start byte, continue searching byte by byte */
1546 for (ofs_byte = start_byte + 1; ofs_byte <= end_byte; ofs_byte++) {
1547 if ((target && s[ofs_byte])
1548 || (!target && (s[ofs_byte] != 0xff))) {
1549 break;
1550 }
1551 }
1552 if (ofs_byte > end_byte) {
1553 return end;
1554 }
1555 the_byte = s[ofs_byte];
1556 /* Target is in the_byte, find it bit by bit */
1557 for (ofs = 7; ofs >= 0; ofs--) {
1558 if (((the_byte & (1u << ofs)) != 0) == target) {
1559 break;
1560 }
1561 }
1562 }
1563 int ret = (len - ofs_byte) * 8 - (8 - ofs);
1564 if (ret < end) {
1565 return end;
1566 }
1567 return ret;
95a92d5a 1568}
099c06e3 1569
ddc4f8e2
BP
1570/* Copies the 'n_bits' low-order bits of 'value' into the 'n_bits' bits
1571 * starting at bit 'dst_ofs' in 'dst', which is 'dst_len' bytes long.
1572 *
1573 * If you consider all of 'dst' to be a single unsigned integer in network byte
1574 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1575 * with value 1 in dst[dst_len - 1], bit 1 is the bit with value 2, bit 2 is
1576 * the bit with value 4, ..., bit 8 is the bit with value 1 in dst[dst_len -
1577 * 2], and so on.
1578 *
1579 * Required invariants:
1580 * dst_ofs + n_bits <= dst_len * 8
1581 * n_bits <= 64
1582 */
1583void
1584bitwise_put(uint64_t value,
1585 void *dst, unsigned int dst_len, unsigned int dst_ofs,
1586 unsigned int n_bits)
1587{
1588 ovs_be64 n_value = htonll(value);
1589 bitwise_copy(&n_value, sizeof n_value, 0,
1590 dst, dst_len, dst_ofs,
1591 n_bits);
1592}
1593
1594/* Returns the value of the 'n_bits' bits starting at bit 'src_ofs' in 'src',
1595 * which is 'src_len' bytes long.
1596 *
1597 * If you consider all of 'src' to be a single unsigned integer in network byte
1598 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1599 * with value 1 in src[src_len - 1], bit 1 is the bit with value 2, bit 2 is
1600 * the bit with value 4, ..., bit 8 is the bit with value 1 in src[src_len -
1601 * 2], and so on.
1602 *
1603 * Required invariants:
1604 * src_ofs + n_bits <= src_len * 8
1605 * n_bits <= 64
1606 */
1607uint64_t
1608bitwise_get(const void *src, unsigned int src_len,
1609 unsigned int src_ofs, unsigned int n_bits)
1610{
1611 ovs_be64 value = htonll(0);
1612
1613 bitwise_copy(src, src_len, src_ofs,
1614 &value, sizeof value, 0,
1615 n_bits);
1616 return ntohll(value);
1617}
95a92d5a
BP
1618
1619/* Returns the value of the bit with offset 'ofs' in 'src', which is 'len'
1620 * bytes long.
1621 *
1622 * If you consider all of 'src' to be a single unsigned integer in network byte
1623 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1624 * with value 1 in src[len - 1], bit 1 is the bit with value 2, bit 2 is the
1625 * bit with value 4, ..., bit 8 is the bit with value 1 in src[len - 2], and so
1626 * on.
1627 *
1628 * Required invariants:
1629 * ofs < len * 8
1630 */
1631bool
1632bitwise_get_bit(const void *src_, unsigned int len, unsigned int ofs)
1633{
1634 const uint8_t *src = src_;
1635
1636 return (src[len - (ofs / 8 + 1)] & (1u << (ofs % 8))) != 0;
1637}
1638
1639/* Sets the bit with offset 'ofs' in 'dst', which is 'len' bytes long, to 0.
1640 *
1641 * If you consider all of 'dst' to be a single unsigned integer in network byte
1642 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1643 * with value 1 in dst[len - 1], bit 1 is the bit with value 2, bit 2 is the
1644 * bit with value 4, ..., bit 8 is the bit with value 1 in dst[len - 2], and so
1645 * on.
1646 *
1647 * Required invariants:
1648 * ofs < len * 8
1649 */
1650void
1651bitwise_put0(void *dst_, unsigned int len, unsigned int ofs)
1652{
1653 uint8_t *dst = dst_;
1654
1655 dst[len - (ofs / 8 + 1)] &= ~(1u << (ofs % 8));
1656}
1657
1658/* Sets the bit with offset 'ofs' in 'dst', which is 'len' bytes long, to 1.
1659 *
1660 * If you consider all of 'dst' to be a single unsigned integer in network byte
1661 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1662 * with value 1 in dst[len - 1], bit 1 is the bit with value 2, bit 2 is the
1663 * bit with value 4, ..., bit 8 is the bit with value 1 in dst[len - 2], and so
1664 * on.
1665 *
1666 * Required invariants:
1667 * ofs < len * 8
1668 */
1669void
1670bitwise_put1(void *dst_, unsigned int len, unsigned int ofs)
1671{
1672 uint8_t *dst = dst_;
1673
1674 dst[len - (ofs / 8 + 1)] |= 1u << (ofs % 8);
1675}
1676
1677/* Sets the bit with offset 'ofs' in 'dst', which is 'len' bytes long, to 'b'.
1678 *
1679 * If you consider all of 'dst' to be a single unsigned integer in network byte
1680 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1681 * with value 1 in dst[len - 1], bit 1 is the bit with value 2, bit 2 is the
1682 * bit with value 4, ..., bit 8 is the bit with value 1 in dst[len - 2], and so
1683 * on.
1684 *
1685 * Required invariants:
1686 * ofs < len * 8
1687 */
1688void
1689bitwise_put_bit(void *dst, unsigned int len, unsigned int ofs, bool b)
1690{
1691 if (b) {
1692 bitwise_put1(dst, len, ofs);
1693 } else {
1694 bitwise_put0(dst, len, ofs);
1695 }
1696}
1697
1698/* Flips the bit with offset 'ofs' in 'dst', which is 'len' bytes long.
1699 *
1700 * If you consider all of 'dst' to be a single unsigned integer in network byte
1701 * order, then bit N is the bit with value 2**N. That is, bit 0 is the bit
1702 * with value 1 in dst[len - 1], bit 1 is the bit with value 2, bit 2 is the
1703 * bit with value 4, ..., bit 8 is the bit with value 1 in dst[len - 2], and so
1704 * on.
1705 *
1706 * Required invariants:
1707 * ofs < len * 8
1708 */
1709void
1710bitwise_toggle_bit(void *dst_, unsigned int len, unsigned int ofs)
1711{
1712 uint8_t *dst = dst_;
1713
1714 dst[len - (ofs / 8 + 1)] ^= 1u << (ofs % 8);
1715}
ed2232fc
BP
1716\f
1717/* ovs_scan */
1718
1719struct scan_spec {
1720 unsigned int width;
1721 enum {
1722 SCAN_DISCARD,
1723 SCAN_CHAR,
1724 SCAN_SHORT,
1725 SCAN_INT,
1726 SCAN_LONG,
1727 SCAN_LLONG,
1728 SCAN_INTMAX_T,
1729 SCAN_PTRDIFF_T,
1730 SCAN_SIZE_T
1731 } type;
1732};
1733
1734static const char *
1735skip_spaces(const char *s)
1736{
1737 while (isspace((unsigned char) *s)) {
1738 s++;
1739 }
1740 return s;
1741}
1742
1743static const char *
1744scan_int(const char *s, const struct scan_spec *spec, int base, va_list *args)
1745{
1746 const char *start = s;
1747 uintmax_t value;
1748 bool negative;
1749 int n_digits;
1750
1751 negative = *s == '-';
1752 s += *s == '-' || *s == '+';
1753
1754 if ((!base || base == 16) && *s == '0' && (s[1] == 'x' || s[1] == 'X')) {
1755 base = 16;
1756 s += 2;
1757 } else if (!base) {
1758 base = *s == '0' ? 8 : 10;
1759 }
1760
1761 if (s - start >= spec->width) {
1762 return NULL;
1763 }
1764
1765 value = 0;
1766 n_digits = 0;
1767 while (s - start < spec->width) {
1768 int digit = hexit_value(*s);
1769
1770 if (digit < 0 || digit >= base) {
1771 break;
1772 }
1773 value = value * base + digit;
1774 n_digits++;
1775 s++;
1776 }
1777 if (!n_digits) {
1778 return NULL;
1779 }
1780
1781 if (negative) {
1782 value = -value;
1783 }
1784
1785 switch (spec->type) {
1786 case SCAN_DISCARD:
1787 break;
1788 case SCAN_CHAR:
1789 *va_arg(*args, char *) = value;
1790 break;
1791 case SCAN_SHORT:
1792 *va_arg(*args, short int *) = value;
1793 break;
1794 case SCAN_INT:
1795 *va_arg(*args, int *) = value;
1796 break;
1797 case SCAN_LONG:
1798 *va_arg(*args, long int *) = value;
1799 break;
1800 case SCAN_LLONG:
1801 *va_arg(*args, long long int *) = value;
1802 break;
1803 case SCAN_INTMAX_T:
1804 *va_arg(*args, intmax_t *) = value;
1805 break;
1806 case SCAN_PTRDIFF_T:
1807 *va_arg(*args, ptrdiff_t *) = value;
1808 break;
1809 case SCAN_SIZE_T:
1810 *va_arg(*args, size_t *) = value;
1811 break;
1812 }
1813 return s;
1814}
1815
1816static const char *
1817skip_digits(const char *s)
1818{
1819 while (*s >= '0' && *s <= '9') {
1820 s++;
1821 }
1822 return s;
1823}
1824
1825static const char *
1826scan_float(const char *s, const struct scan_spec *spec, va_list *args)
1827{
1828 const char *start = s;
1829 long double value;
1830 char *tail;
1831 char *copy;
1832 bool ok;
1833
1834 s += *s == '+' || *s == '-';
1835 s = skip_digits(s);
1836 if (*s == '.') {
1837 s = skip_digits(s + 1);
1838 }
1839 if (*s == 'e' || *s == 'E') {
1840 s++;
1841 s += *s == '+' || *s == '-';
1842 s = skip_digits(s);
1843 }
1844
1845 if (s - start > spec->width) {
1846 s = start + spec->width;
1847 }
1848
1849 copy = xmemdup0(start, s - start);
1850 value = strtold(copy, &tail);
1851 ok = *tail == '\0';
1852 free(copy);
1853 if (!ok) {
1854 return NULL;
1855 }
1856
1857 switch (spec->type) {
1858 case SCAN_DISCARD:
1859 break;
1860 case SCAN_INT:
1861 *va_arg(*args, float *) = value;
1862 break;
1863 case SCAN_LONG:
1864 *va_arg(*args, double *) = value;
1865 break;
1866 case SCAN_LLONG:
1867 *va_arg(*args, long double *) = value;
1868 break;
1869
1870 case SCAN_CHAR:
1871 case SCAN_SHORT:
1872 case SCAN_INTMAX_T:
1873 case SCAN_PTRDIFF_T:
1874 case SCAN_SIZE_T:
428b2edd 1875 OVS_NOT_REACHED();
ed2232fc
BP
1876 }
1877 return s;
1878}
1879
1880static void
1881scan_output_string(const struct scan_spec *spec,
1882 const char *s, size_t n,
1883 va_list *args)
1884{
1885 if (spec->type != SCAN_DISCARD) {
1886 char *out = va_arg(*args, char *);
1887 memcpy(out, s, n);
1888 out[n] = '\0';
1889 }
1890}
1891
1892static const char *
1893scan_string(const char *s, const struct scan_spec *spec, va_list *args)
1894{
1895 size_t n;
1896
1897 for (n = 0; n < spec->width; n++) {
1898 if (!s[n] || isspace((unsigned char) s[n])) {
1899 break;
1900 }
1901 }
1902 if (!n) {
1903 return NULL;
1904 }
1905
1906 scan_output_string(spec, s, n, args);
1907 return s + n;
1908}
1909
1910static const char *
1911parse_scanset(const char *p_, unsigned long *set, bool *complemented)
1912{
1913 const uint8_t *p = (const uint8_t *) p_;
1914
1915 *complemented = *p == '^';
1916 p += *complemented;
1917
1918 if (*p == ']') {
1919 bitmap_set1(set, ']');
1920 p++;
1921 }
1922
1923 while (*p && *p != ']') {
1924 if (p[1] == '-' && p[2] != ']' && p[2] > *p) {
1925 bitmap_set_multiple(set, *p, p[2] - *p + 1, true);
1926 p += 3;
1927 } else {
1928 bitmap_set1(set, *p++);
1929 }
1930 }
1931 if (*p == ']') {
1932 p++;
1933 }
1934 return (const char *) p;
1935}
1936
1937static const char *
1938scan_set(const char *s, const struct scan_spec *spec, const char **pp,
1939 va_list *args)
1940{
1941 unsigned long set[BITMAP_N_LONGS(UCHAR_MAX + 1)];
1942 bool complemented;
1943 unsigned int n;
1944
1945 /* Parse the scan set. */
1946 memset(set, 0, sizeof set);
1947 *pp = parse_scanset(*pp, set, &complemented);
1948
1949 /* Parse the data. */
1950 n = 0;
1951 while (s[n]
1952 && bitmap_is_set(set, (unsigned char) s[n]) == !complemented
1953 && n < spec->width) {
1954 n++;
1955 }
1956 if (!n) {
1957 return NULL;
1958 }
1959 scan_output_string(spec, s, n, args);
1960 return s + n;
1961}
1962
1963static const char *
1964scan_chars(const char *s, const struct scan_spec *spec, va_list *args)
1965{
31499678 1966 unsigned int n = spec->width == UINT_MAX ? 1 : spec->width;
ed2232fc
BP
1967
1968 if (strlen(s) < n) {
1969 return NULL;
1970 }
1971 if (spec->type != SCAN_DISCARD) {
1972 memcpy(va_arg(*args, char *), s, n);
1973 }
1974 return s + n;
1975}
1976
f071cbba
PS
1977static bool
1978ovs_scan__(const char *s, int *n, const char *format, va_list *args)
ed2232fc
BP
1979{
1980 const char *const start = s;
1981 bool ok = false;
1982 const char *p;
ed2232fc 1983
037821cf 1984 p = format;
ed2232fc
BP
1985 while (*p != '\0') {
1986 struct scan_spec spec;
1987 unsigned char c = *p++;
1988 bool discard;
1989
1990 if (isspace(c)) {
1991 s = skip_spaces(s);
1992 continue;
1993 } else if (c != '%') {
1994 if (*s != c) {
1995 goto exit;
1996 }
1997 s++;
1998 continue;
1999 } else if (*p == '%') {
2000 if (*s++ != '%') {
2001 goto exit;
2002 }
2003 p++;
2004 continue;
2005 }
2006
2007 /* Parse '*' flag. */
2008 discard = *p == '*';
2009 p += discard;
2010
2011 /* Parse field width. */
2012 spec.width = 0;
2013 while (*p >= '0' && *p <= '9') {
2014 spec.width = spec.width * 10 + (*p++ - '0');
2015 }
2016 if (spec.width == 0) {
2017 spec.width = UINT_MAX;
2018 }
2019
2020 /* Parse type modifier. */
2021 switch (*p) {
2022 case 'h':
2023 if (p[1] == 'h') {
2024 spec.type = SCAN_CHAR;
2025 p += 2;
2026 } else {
2027 spec.type = SCAN_SHORT;
2028 p++;
2029 }
2030 break;
2031
2032 case 'j':
2033 spec.type = SCAN_INTMAX_T;
2034 p++;
2035 break;
2036
2037 case 'l':
2038 if (p[1] == 'l') {
2039 spec.type = SCAN_LLONG;
2040 p += 2;
2041 } else {
2042 spec.type = SCAN_LONG;
2043 p++;
2044 }
2045 break;
2046
2047 case 'L':
2048 case 'q':
2049 spec.type = SCAN_LLONG;
2050 p++;
2051 break;
2052
2053 case 't':
2054 spec.type = SCAN_PTRDIFF_T;
2055 p++;
2056 break;
2057
2058 case 'z':
2059 spec.type = SCAN_SIZE_T;
2060 p++;
2061 break;
2062
2063 default:
2064 spec.type = SCAN_INT;
2065 break;
2066 }
2067
2068 if (discard) {
2069 spec.type = SCAN_DISCARD;
2070 }
2071
2072 c = *p++;
2073 if (c != 'c' && c != 'n' && c != '[') {
2074 s = skip_spaces(s);
2075 }
2076 switch (c) {
2077 case 'd':
f071cbba 2078 s = scan_int(s, &spec, 10, args);
ed2232fc
BP
2079 break;
2080
2081 case 'i':
f071cbba 2082 s = scan_int(s, &spec, 0, args);
ed2232fc
BP
2083 break;
2084
2085 case 'o':
f071cbba 2086 s = scan_int(s, &spec, 8, args);
ed2232fc
BP
2087 break;
2088
2089 case 'u':
f071cbba 2090 s = scan_int(s, &spec, 10, args);
ed2232fc
BP
2091 break;
2092
2093 case 'x':
2094 case 'X':
f071cbba 2095 s = scan_int(s, &spec, 16, args);
ed2232fc
BP
2096 break;
2097
2098 case 'e':
2099 case 'f':
2100 case 'g':
2101 case 'E':
2102 case 'G':
f071cbba 2103 s = scan_float(s, &spec, args);
ed2232fc
BP
2104 break;
2105
2106 case 's':
f071cbba 2107 s = scan_string(s, &spec, args);
ed2232fc
BP
2108 break;
2109
2110 case '[':
f071cbba 2111 s = scan_set(s, &spec, &p, args);
ed2232fc
BP
2112 break;
2113
2114 case 'c':
f071cbba 2115 s = scan_chars(s, &spec, args);
ed2232fc
BP
2116 break;
2117
2118 case 'n':
2119 if (spec.type != SCAN_DISCARD) {
f071cbba 2120 *va_arg(*args, int *) = s - start;
ed2232fc
BP
2121 }
2122 break;
2123 }
2124
2125 if (!s) {
2126 goto exit;
2127 }
2128 }
f071cbba
PS
2129 if (n) {
2130 *n = s - start;
2131 }
ed2232fc 2132
f071cbba 2133 ok = true;
ed2232fc 2134exit:
ed2232fc
BP
2135 return ok;
2136}
2137
f071cbba
PS
2138/* This is an implementation of the standard sscanf() function, with the
2139 * following exceptions:
2140 *
2141 * - It returns true if the entire format was successfully scanned and
2142 * converted, false if any conversion failed.
2143 *
2144 * - The standard doesn't define sscanf() behavior when an out-of-range value
2145 * is scanned, e.g. if a "%"PRIi8 conversion scans "-1" or "0x1ff". Some
2146 * implementations consider this an error and stop scanning. This
2147 * implementation never considers an out-of-range value an error; instead,
2148 * it stores the least-significant bits of the converted value in the
2149 * destination, e.g. the value 255 for both examples earlier.
2150 *
2151 * - Only single-byte characters are supported, that is, the 'l' modifier
2152 * on %s, %[, and %c is not supported. The GNU extension 'a' modifier is
2153 * also not supported.
2154 *
2155 * - %p is not supported.
2156 */
2157bool
2158ovs_scan(const char *s, const char *format, ...)
2159{
2160 va_list args;
2161 bool res;
2162
2163 va_start(args, format);
2164 res = ovs_scan__(s, NULL, format, &args);
2165 va_end(args);
2166 return res;
2167}
2168
2169/*
938a73da
BP
2170 * This function is similar to ovs_scan(), with an extra parameter `n` added to
2171 * return the number of scanned characters.
f071cbba
PS
2172 */
2173bool
2174ovs_scan_len(const char *s, int *n, const char *format, ...)
2175{
2176 va_list args;
2177 bool success;
2178 int n1;
2179
2180 va_start(args, format);
2181 success = ovs_scan__(s + *n, &n1, format, &args);
2182 va_end(args);
2183 if (success) {
2184 *n = *n + n1;
2185 }
2186 return success;
2187}
2188
5fd2f418 2189void
275eebb9
PS
2190xsleep(unsigned int seconds)
2191{
275eebb9 2192 ovsrcu_quiesce_start();
5fd2f418
GS
2193#ifdef _WIN32
2194 Sleep(seconds * 1000);
2195#else
2196 sleep(seconds);
2197#endif
275eebb9 2198 ovsrcu_quiesce_end();
275eebb9
PS
2199}
2200
20174b74
QM
2201/* Determine whether standard output is a tty or not. This is useful to decide
2202 * whether to use color output or not when --color option for utilities is set
2203 * to `auto`.
2204 */
2205bool
2206is_stdout_a_tty(void)
2207{
2208 char const *t = getenv("TERM");
2209 return (isatty(STDOUT_FILENO) && t && strcmp(t, "dumb") != 0);
2210}
2211
06f14c92
GS
2212#ifdef _WIN32
2213\f
06f14c92 2214char *
315ea327 2215ovs_format_message(int error)
06f14c92 2216{
315ea327
GS
2217 enum { BUFSIZE = sizeof strerror_buffer_get()->s };
2218 char *buffer = strerror_buffer_get()->s;
2219
11b7f938
YT
2220 if (error == 0) {
2221 /* See ovs_strerror */
2222 return "Success";
2223 }
2224
315ea327
GS
2225 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
2226 NULL, error, 0, buffer, BUFSIZE, NULL);
06f14c92
GS
2227 return buffer;
2228}
315ea327
GS
2229
2230/* Returns a null-terminated string that explains the last error.
2231 * Use this function to get the error string for WINAPI calls. */
2232char *
2233ovs_lasterror_to_string(void)
2234{
2235 return ovs_format_message(GetLastError());
2236}
daa04db8
GS
2237
2238int
2239ftruncate(int fd, off_t length)
2240{
2241 int error;
2242
2243 error = _chsize_s(fd, length);
2244 if (error) {
2245 return -1;
2246 }
2247 return 0;
2248}
64559798
GS
2249
2250OVS_CONSTRUCTOR(winsock_start) {
2251 WSADATA wsaData;
2252 int error;
2253
2254 error = WSAStartup(MAKEWORD(2, 2), &wsaData);
2255 if (error != 0) {
2256 VLOG_FATAL("WSAStartup failed: %s", sock_strerror(sock_errno()));
2257 }
2258}
06f14c92 2259#endif