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