util: Expose function nullable_string_is_equal.
[cascardo/ovs.git] / lib / util.h
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016 Nicira, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #ifndef UTIL_H
18 #define UTIL_H 1
19
20 #include <arpa/inet.h>
21 #include <inttypes.h>
22 #include <limits.h>
23 #include <stdarg.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include "compiler.h"
28 #include "util.h"
29 #include "openvswitch/util.h"
30
31 extern char *program_name;
32
33 #define __ARRAY_SIZE_NOCHECK(ARRAY) (sizeof(ARRAY) / sizeof((ARRAY)[0]))
34 #ifdef __GNUC__
35 /* return 0 for array types, 1 otherwise */
36 #define __ARRAY_CHECK(ARRAY)                                    \
37     !__builtin_types_compatible_p(typeof(ARRAY), typeof(&ARRAY[0]))
38
39 /* compile-time fail if not array */
40 #define __ARRAY_FAIL(ARRAY) (sizeof(char[-2*!__ARRAY_CHECK(ARRAY)]))
41 #define __ARRAY_SIZE(ARRAY)                                     \
42     __builtin_choose_expr(__ARRAY_CHECK(ARRAY),                 \
43         __ARRAY_SIZE_NOCHECK(ARRAY), __ARRAY_FAIL(ARRAY))
44 #else
45 #define __ARRAY_SIZE(ARRAY) __ARRAY_SIZE_NOCHECK(ARRAY)
46 #endif
47
48
49 /* This system's cache line size, in bytes.
50  * Being wrong hurts performance but not correctness. */
51 #define CACHE_LINE_SIZE 64
52 BUILD_ASSERT_DECL(IS_POW2(CACHE_LINE_SIZE));
53
54 static inline void
55 ovs_prefetch_range(const void *start, size_t size)
56 {
57     const char *addr = (const char *)start;
58     size_t ofs;
59
60     for (ofs = 0; ofs < size; ofs += CACHE_LINE_SIZE) {
61         OVS_PREFETCH(addr + ofs);
62     }
63 }
64
65 #ifndef MIN
66 #define MIN(X, Y) ((X) < (Y) ? (X) : (Y))
67 #endif
68
69 #ifndef MAX
70 #define MAX(X, Y) ((X) > (Y) ? (X) : (Y))
71 #endif
72
73 #define OVS_NOT_REACHED() abort()
74
75 /* Use "%"PRIuSIZE to format size_t with printf(). */
76 #ifdef _WIN32
77 #define PRIdSIZE "Id"
78 #define PRIiSIZE "Ii"
79 #define PRIoSIZE "Io"
80 #define PRIuSIZE "Iu"
81 #define PRIxSIZE "Ix"
82 #define PRIXSIZE "IX"
83 #else
84 #define PRIdSIZE "zd"
85 #define PRIiSIZE "zi"
86 #define PRIoSIZE "zo"
87 #define PRIuSIZE "zu"
88 #define PRIxSIZE "zx"
89 #define PRIXSIZE "zX"
90 #endif
91
92 #ifndef _WIN32
93 typedef uint32_t HANDLE;
94 #endif
95
96 #ifdef  __cplusplus
97 extern "C" {
98 #endif
99
100 #define set_program_name(name) \
101         ovs_set_program_name(name, OVS_PACKAGE_VERSION)
102
103 const char *get_subprogram_name(void);
104     void set_subprogram_name(const char *);
105
106 void ovs_print_version(uint8_t min_ofp, uint8_t max_ofp);
107
108 OVS_NO_RETURN void out_of_memory(void);
109 void *xmalloc(size_t) MALLOC_LIKE;
110 void *xcalloc(size_t, size_t) MALLOC_LIKE;
111 void *xzalloc(size_t) MALLOC_LIKE;
112 void *xrealloc(void *, size_t);
113 void *xmemdup(const void *, size_t) MALLOC_LIKE;
114 char *xmemdup0(const char *, size_t) MALLOC_LIKE;
115 char *xstrdup(const char *) MALLOC_LIKE;
116 char *nullable_xstrdup(const char *) MALLOC_LIKE;
117 bool nullable_string_is_equal(const char *a, const char *b);
118 char *xasprintf(const char *format, ...) OVS_PRINTF_FORMAT(1, 2) MALLOC_LIKE;
119 char *xvasprintf(const char *format, va_list) OVS_PRINTF_FORMAT(1, 0) MALLOC_LIKE;
120 void *x2nrealloc(void *p, size_t *n, size_t s);
121
122 void *xmalloc_cacheline(size_t) MALLOC_LIKE;
123 void *xzalloc_cacheline(size_t) MALLOC_LIKE;
124 void free_cacheline(void *);
125
126 void ovs_strlcpy(char *dst, const char *src, size_t size);
127 void ovs_strzcpy(char *dst, const char *src, size_t size);
128
129 OVS_NO_RETURN void ovs_abort(int err_no, const char *format, ...)
130     OVS_PRINTF_FORMAT(2, 3);
131 OVS_NO_RETURN void ovs_abort_valist(int err_no, const char *format, va_list)
132     OVS_PRINTF_FORMAT(2, 0);
133 OVS_NO_RETURN void ovs_fatal(int err_no, const char *format, ...)
134     OVS_PRINTF_FORMAT(2, 3);
135 OVS_NO_RETURN void ovs_fatal_valist(int err_no, const char *format, va_list)
136     OVS_PRINTF_FORMAT(2, 0);
137 void ovs_error(int err_no, const char *format, ...) OVS_PRINTF_FORMAT(2, 3);
138 void ovs_error_valist(int err_no, const char *format, va_list)
139     OVS_PRINTF_FORMAT(2, 0);
140 const char *ovs_retval_to_string(int);
141 const char *ovs_strerror(int);
142 void ovs_hex_dump(FILE *, const void *, size_t, uintptr_t offset, bool ascii);
143
144 bool str_to_int(const char *, int base, int *);
145 bool str_to_long(const char *, int base, long *);
146 bool str_to_llong(const char *, int base, long long *);
147 bool str_to_uint(const char *, int base, unsigned int *);
148
149 bool ovs_scan(const char *s, const char *format, ...) OVS_SCANF_FORMAT(2, 3);
150 bool ovs_scan_len(const char *s, int *n, const char *format, ...);
151
152 bool str_to_double(const char *, double *);
153
154 int hexit_value(int c);
155 uintmax_t hexits_value(const char *s, size_t n, bool *ok);
156
157 int parse_int_string(const char *s, uint8_t *valuep, int field_width,
158                      char **tail);
159
160 const char *english_list_delimiter(size_t index, size_t total);
161
162 char *get_cwd(void);
163 #ifndef _WIN32
164 char *dir_name(const char *file_name);
165 char *base_name(const char *file_name);
166 #endif
167 char *abs_file_name(const char *dir, const char *file_name);
168
169 char *follow_symlinks(const char *filename);
170
171 void ignore(bool x OVS_UNUSED);
172 \f
173 /* Bitwise tests. */
174
175 /* Returns the number of trailing 0-bits in 'n'.  Undefined if 'n' == 0. */
176 #if __GNUC__ >= 4
177 static inline int
178 raw_ctz(uint64_t n)
179 {
180     /* With GCC 4.7 on 32-bit x86, if a 32-bit integer is passed as 'n', using
181      * a plain __builtin_ctzll() here always generates an out-of-line function
182      * call.  The test below helps it to emit a single 'bsf' instruction. */
183     return (__builtin_constant_p(n <= UINT32_MAX) && n <= UINT32_MAX
184             ? __builtin_ctz(n)
185             : __builtin_ctzll(n));
186 }
187
188 static inline int
189 raw_clz64(uint64_t n)
190 {
191     return __builtin_clzll(n);
192 }
193 #elif _MSC_VER
194 static inline int
195 raw_ctz(uint64_t n)
196 {
197 #ifdef _WIN64
198     unsigned long r = 0;
199     _BitScanForward64(&r, n);
200     return r;
201 #else
202     unsigned long low = n, high, r = 0;
203     if (_BitScanForward(&r, low)) {
204         return r;
205     }
206     high = n >> 32;
207     _BitScanForward(&r, high);
208     return r + 32;
209 #endif
210 }
211
212 static inline int
213 raw_clz64(uint64_t n)
214 {
215 #ifdef _WIN64
216     unsigned long r = 0;
217     _BitScanReverse64(&r, n);
218     return 63 - r;
219 #else
220     unsigned long low, high = n >> 32, r = 0;
221     if (_BitScanReverse(&r, high)) {
222         return 31 - r;
223     }
224     low = n;
225     _BitScanReverse(&r, low);
226     return 63 - r;
227 #endif
228 }
229 #else
230 /* Defined in util.c. */
231 int raw_ctz(uint64_t n);
232 int raw_clz64(uint64_t n);
233 #endif
234
235 /* Returns the number of trailing 0-bits in 'n', or 32 if 'n' is 0. */
236 static inline int
237 ctz32(uint32_t n)
238 {
239     return n ? raw_ctz(n) : 32;
240 }
241
242 /* Returns the number of trailing 0-bits in 'n', or 64 if 'n' is 0. */
243 static inline int
244 ctz64(uint64_t n)
245 {
246     return n ? raw_ctz(n) : 64;
247 }
248
249 /* Returns the number of leading 0-bits in 'n', or 32 if 'n' is 0. */
250 static inline int
251 clz32(uint32_t n)
252 {
253     return n ? raw_clz64(n) - 32 : 32;
254 }
255
256 /* Returns the number of leading 0-bits in 'n', or 64 if 'n' is 0. */
257 static inline int
258 clz64(uint64_t n)
259 {
260     return n ? raw_clz64(n) : 64;
261 }
262
263 /* Given a word 'n', calculates floor(log_2('n')).  This is equivalent
264  * to finding the bit position of the most significant one bit in 'n'.  It is
265  * an error to call this function with 'n' == 0. */
266 static inline int
267 log_2_floor(uint64_t n)
268 {
269     return 63 - raw_clz64(n);
270 }
271
272 /* Given a word 'n', calculates ceil(log_2('n')).  It is an error to
273  * call this function with 'n' == 0. */
274 static inline int
275 log_2_ceil(uint64_t n)
276 {
277     return log_2_floor(n) + !is_pow2(n);
278 }
279
280 /* unsigned int count_1bits(uint64_t x):
281  *
282  * Returns the number of 1-bits in 'x', between 0 and 64 inclusive. */
283 #if UINTPTR_MAX == UINT64_MAX
284 static inline unsigned int
285 count_1bits(uint64_t x)
286 {
287 #if __GNUC__ >= 4 && __POPCNT__
288     return __builtin_popcountll(x);
289 #else
290     /* This portable implementation is the fastest one we know of for 64
291      * bits, and about 3x faster than GCC 4.7 __builtin_popcountll(). */
292     const uint64_t h55 = UINT64_C(0x5555555555555555);
293     const uint64_t h33 = UINT64_C(0x3333333333333333);
294     const uint64_t h0F = UINT64_C(0x0F0F0F0F0F0F0F0F);
295     const uint64_t h01 = UINT64_C(0x0101010101010101);
296     x -= (x >> 1) & h55;               /* Count of each 2 bits in-place. */
297     x = (x & h33) + ((x >> 2) & h33);  /* Count of each 4 bits in-place. */
298     x = (x + (x >> 4)) & h0F;          /* Count of each 8 bits in-place. */
299     return (x * h01) >> 56;            /* Sum of all bytes. */
300 #endif
301 }
302 #else /* Not 64-bit. */
303 #if __GNUC__ >= 4 && __POPCNT__
304 static inline unsigned int
305 count_1bits_32__(uint32_t x)
306 {
307     return __builtin_popcount(x);
308 }
309 #else
310 #define NEED_COUNT_1BITS_8 1
311 extern const uint8_t count_1bits_8[256];
312 static inline unsigned int
313 count_1bits_32__(uint32_t x)
314 {
315     /* This portable implementation is the fastest one we know of for 32 bits,
316      * and faster than GCC __builtin_popcount(). */
317     return (count_1bits_8[x & 0xff] +
318             count_1bits_8[(x >> 8) & 0xff] +
319             count_1bits_8[(x >> 16) & 0xff] +
320             count_1bits_8[x >> 24]);
321 }
322 #endif
323 static inline unsigned int
324 count_1bits(uint64_t x)
325 {
326     return count_1bits_32__(x) + count_1bits_32__(x >> 32);
327 }
328 #endif
329
330 /* Returns the rightmost 1-bit in 'x' (e.g. 01011000 => 00001000), or 0 if 'x'
331  * is 0. */
332 static inline uintmax_t
333 rightmost_1bit(uintmax_t x)
334 {
335     return x & -x;
336 }
337
338 /* Returns 'x' with its rightmost 1-bit changed to a zero (e.g. 01011000 =>
339  * 01010000), or 0 if 'x' is 0. */
340 static inline uintmax_t
341 zero_rightmost_1bit(uintmax_t x)
342 {
343     return x & (x - 1);
344 }
345
346 /* Returns the index of the rightmost 1-bit in 'x' (e.g. 01011000 => 3), or an
347  * undefined value if 'x' is 0. */
348 static inline int
349 rightmost_1bit_idx(uint64_t x)
350 {
351     return ctz64(x);
352 }
353
354 /* Returns the index of the leftmost 1-bit in 'x' (e.g. 01011000 => 6), or an
355  * undefined value if 'x' is 0. */
356 static inline uint32_t
357 leftmost_1bit_idx(uint64_t x)
358 {
359     return log_2_floor(x);
360 }
361
362 /* Return a ovs_be32 prefix in network byte order with 'plen' highest bits set.
363  * Shift with 32 is undefined behavior, but we rather use 64-bit shift than
364  * compare. */
365 static inline ovs_be32 be32_prefix_mask(int plen)
366 {
367     return htonl((uint64_t)UINT32_MAX << (32 - plen));
368 }
369 \f
370 bool is_all_zeros(const void *, size_t);
371 bool is_all_ones(const void *, size_t);
372 void bitwise_copy(const void *src, unsigned int src_len, unsigned int src_ofs,
373                   void *dst, unsigned int dst_len, unsigned int dst_ofs,
374                   unsigned int n_bits);
375 void bitwise_zero(void *dst_, unsigned int dst_len, unsigned dst_ofs,
376                   unsigned int n_bits);
377 void bitwise_one(void *dst_, unsigned int dst_len, unsigned dst_ofs,
378                  unsigned int n_bits);
379 bool bitwise_is_all_zeros(const void *, unsigned int len, unsigned int ofs,
380                           unsigned int n_bits);
381 unsigned int bitwise_scan(const void *, unsigned int len,
382                           bool target, unsigned int start, unsigned int end);
383 int bitwise_rscan(const void *, unsigned int len, bool target,
384                   int start, int end);
385 void bitwise_put(uint64_t value,
386                  void *dst, unsigned int dst_len, unsigned int dst_ofs,
387                  unsigned int n_bits);
388 uint64_t bitwise_get(const void *src, unsigned int src_len,
389                      unsigned int src_ofs, unsigned int n_bits);
390 bool bitwise_get_bit(const void *src, unsigned int len, unsigned int ofs);
391 void bitwise_put0(void *dst, unsigned int len, unsigned int ofs);
392 void bitwise_put1(void *dst, unsigned int len, unsigned int ofs);
393 void bitwise_put_bit(void *dst, unsigned int len, unsigned int ofs, bool);
394 void bitwise_toggle_bit(void *dst, unsigned int len, unsigned int ofs);
395
396 /* Returns non-zero if the parameters have equal value. */
397 static inline int
398 ovs_u128_equals(const ovs_u128 a, const ovs_u128 b)
399 {
400     return (a.u64.hi == b.u64.hi) && (a.u64.lo == b.u64.lo);
401 }
402
403 /* Returns true if 'val' is 0. */
404 static inline bool
405 ovs_u128_is_zero(const ovs_u128 val)
406 {
407     return !(val.u64.hi || val.u64.lo);
408 }
409
410 /* Returns true if 'val' is all ones. */
411 static inline bool
412 ovs_u128_is_ones(const ovs_u128 val)
413 {
414     return ovs_u128_equals(val, OVS_U128_MAX);
415 }
416
417 /* Returns non-zero if the parameters have equal value. */
418 static inline int
419 ovs_be128_equals(const ovs_be128 a, const ovs_be128 b)
420 {
421     return (a.be64.hi == b.be64.hi) && (a.be64.lo == b.be64.lo);
422 }
423
424 /* Returns true if 'val' is 0. */
425 static inline bool
426 ovs_be128_is_zero(const ovs_be128 val)
427 {
428     return !(val.be64.hi || val.be64.lo);
429 }
430
431 static inline ovs_u128
432 ovs_u128_and(const ovs_u128 a, const ovs_u128 b)
433 {
434     ovs_u128 dst;
435
436     dst.u64.hi = a.u64.hi & b.u64.hi;
437     dst.u64.lo = a.u64.lo & b.u64.lo;
438
439     return dst;
440 }
441
442 void xsleep(unsigned int seconds);
443
444 bool is_stdout_a_tty(void);
445
446 #ifdef _WIN32
447 \f
448 char *ovs_format_message(int error);
449 char *ovs_lasterror_to_string(void);
450 int ftruncate(int fd, off_t length);
451 #endif
452
453 #ifdef  __cplusplus
454 }
455 #endif
456
457 #endif /* util.h */