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