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