2 * Copyright (c) 2008, 2009, 2010, 2011 Nicira Networks.
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:
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
31 VLOG_DEFINE_THIS_MODULE(util);
33 COVERAGE_DEFINE(util_xalloc);
35 const char *program_name;
40 ovs_abort(0, "virtual memory exhausted");
44 xcalloc(size_t count, size_t size)
46 void *p = count && size ? calloc(count, size) : malloc(1);
47 COVERAGE_INC(util_xalloc);
57 return xcalloc(1, size);
63 void *p = malloc(size ? size : 1);
64 COVERAGE_INC(util_xalloc);
72 xrealloc(void *p, size_t size)
74 p = realloc(p, size ? size : 1);
75 COVERAGE_INC(util_xalloc);
83 xmemdup(const void *p_, size_t size)
85 void *p = xmalloc(size);
91 xmemdup0(const char *p_, size_t length)
93 char *p = xmalloc(length + 1);
94 memcpy(p, p_, length);
100 xstrdup(const char *s)
102 return xmemdup0(s, strlen(s));
106 xvasprintf(const char *format, va_list args)
112 va_copy(args2, args);
113 needed = vsnprintf(NULL, 0, format, args);
115 s = xmalloc(needed + 1);
117 vsnprintf(s, needed + 1, format, args2);
124 x2nrealloc(void *p, size_t *n, size_t s)
126 *n = *n == 0 ? 1 : 2 * *n;
127 return xrealloc(p, *n * s);
131 xasprintf(const char *format, ...)
136 va_start(args, format);
137 s = xvasprintf(format, args);
143 /* Similar to strlcpy() from OpenBSD, but it never reads more than 'size - 1'
144 * bytes from 'src' and doesn't return anything. */
146 ovs_strlcpy(char *dst, const char *src, size_t size)
149 size_t len = strnlen(src, size - 1);
150 memcpy(dst, src, len);
155 /* Copies 'src' to 'dst'. Reads no more than 'size - 1' bytes from 'src'.
156 * Always null-terminates 'dst' (if 'size' is nonzero), and writes a zero byte
157 * to every otherwise unused byte in 'dst'.
159 * Except for performance, the following call:
160 * ovs_strzcpy(dst, src, size);
161 * is equivalent to these two calls:
162 * memset(dst, '\0', size);
163 * ovs_strlcpy(dst, src, size);
165 * (Thus, ovs_strzcpy() is similar to strncpy() without some of the pitfalls.)
168 ovs_strzcpy(char *dst, const char *src, size_t size)
171 size_t len = strnlen(src, size - 1);
172 memcpy(dst, src, len);
173 memset(dst + len, '\0', size - len);
177 /* Prints 'format' on stderr, formatting it like printf() does. If 'err_no' is
178 * nonzero, then it is formatted with ovs_retval_to_string() and appended to
179 * the message inside parentheses. Then, terminates with abort().
181 * This function is preferred to ovs_fatal() in a situation where it would make
182 * sense for a monitoring process to restart the daemon.
184 * 'format' should not end with a new-line, because this function will add one
187 ovs_abort(int err_no, const char *format, ...)
191 va_start(args, format);
192 ovs_error_valist(err_no, format, args);
198 /* Prints 'format' on stderr, formatting it like printf() does. If 'err_no' is
199 * nonzero, then it is formatted with ovs_retval_to_string() and appended to
200 * the message inside parentheses. Then, terminates with EXIT_FAILURE.
202 * 'format' should not end with a new-line, because this function will add one
205 ovs_fatal(int err_no, const char *format, ...)
209 va_start(args, format);
210 ovs_fatal_valist(err_no, format, args);
213 /* Same as ovs_fatal() except that the arguments are supplied as a va_list. */
215 ovs_fatal_valist(int err_no, const char *format, va_list args)
217 ovs_error_valist(err_no, format, args);
221 /* Prints 'format' on stderr, formatting it like printf() does. If 'err_no' is
222 * nonzero, then it is formatted with ovs_retval_to_string() and appended to
223 * the message inside parentheses.
225 * 'format' should not end with a new-line, because this function will add one
228 ovs_error(int err_no, const char *format, ...)
232 va_start(args, format);
233 ovs_error_valist(err_no, format, args);
237 /* Same as ovs_error() except that the arguments are supplied as a va_list. */
239 ovs_error_valist(int err_no, const char *format, va_list args)
241 int save_errno = errno;
243 fprintf(stderr, "%s: ", program_name);
244 vfprintf(stderr, format, args);
246 fprintf(stderr, " (%s)", ovs_retval_to_string(err_no));
253 /* Many OVS functions return an int which is one of:
256 * - EOF: end of file (not necessarily an error; depends on the function called)
258 * Returns the appropriate human-readable string. The caller must copy the
259 * string if it wants to hold onto it, as the storage may be overwritten on
260 * subsequent function calls.
263 ovs_retval_to_string(int retval)
265 static char unknown[48];
271 return strerror(retval);
274 return "End of file";
276 snprintf(unknown, sizeof unknown, "***unknown return value: %d***", retval);
280 /* Sets program_name based on 'argv0'. Should be called at the beginning of
281 * main(), as "set_program_name(argv[0]);". */
282 void set_program_name(const char *argv0)
284 const char *slash = strrchr(argv0, '/');
285 program_name = slash ? slash + 1 : argv0;
288 /* Print the version information for the program. */
290 ovs_print_version(char *date, char *time,
291 uint8_t min_ofp, uint8_t max_ofp)
293 printf("%s (Open vSwitch) "VERSION BUILDNR"\n", program_name);
294 printf("Compiled %s %s\n", date, time);
295 if (min_ofp || max_ofp) {
296 printf("OpenFlow versions %#x:%#x\n", min_ofp, max_ofp);
300 /* Writes the 'size' bytes in 'buf' to 'stream' as hex bytes arranged 16 per
301 * line. Numeric offsets are also included, starting at 'ofs' for the first
302 * byte in 'buf'. If 'ascii' is true then the corresponding ASCII characters
303 * are also rendered alongside. */
305 ovs_hex_dump(FILE *stream, const void *buf_, size_t size,
306 uintptr_t ofs, bool ascii)
308 const uint8_t *buf = buf_;
309 const size_t per_line = 16; /* Maximum bytes per line. */
313 size_t start, end, n;
316 /* Number of bytes on this line. */
317 start = ofs % per_line;
319 if (end - start > size)
324 fprintf(stream, "%08jx ", (uintmax_t) ROUND_DOWN(ofs, per_line));
325 for (i = 0; i < start; i++)
326 fprintf(stream, " ");
328 fprintf(stream, "%02hhx%c",
329 buf[i - start], i == per_line / 2 - 1? '-' : ' ');
332 for (; i < per_line; i++)
333 fprintf(stream, " ");
334 fprintf(stream, "|");
335 for (i = 0; i < start; i++)
336 fprintf(stream, " ");
337 for (; i < end; i++) {
338 int c = buf[i - start];
339 putc(c >= 32 && c < 127 ? c : '.', stream);
341 for (; i < per_line; i++)
342 fprintf(stream, " ");
343 fprintf(stream, "|");
345 fprintf(stream, "\n");
354 str_to_int(const char *s, int base, int *i)
357 bool ok = str_to_llong(s, base, &ll);
363 str_to_long(const char *s, int base, long *li)
366 bool ok = str_to_llong(s, base, &ll);
372 str_to_llong(const char *s, int base, long long *x)
374 int save_errno = errno;
377 *x = strtoll(s, &tail, base);
378 if (errno == EINVAL || errno == ERANGE || tail == s || *tail != '\0') {
389 str_to_uint(const char *s, int base, unsigned int *u)
391 return str_to_int(s, base, (int *) u);
395 str_to_ulong(const char *s, int base, unsigned long *ul)
397 return str_to_long(s, base, (long *) ul);
401 str_to_ullong(const char *s, int base, unsigned long long *ull)
403 return str_to_llong(s, base, (long long *) ull);
406 /* Converts floating-point string 's' into a double. If successful, stores
407 * the double in '*d' and returns true; on failure, stores 0 in '*d' and
410 * Underflow (e.g. "1e-9999") is not considered an error, but overflow
411 * (e.g. "1e9999)" is. */
413 str_to_double(const char *s, double *d)
415 int save_errno = errno;
418 *d = strtod(s, &tail);
419 if (errno == EINVAL || (errno == ERANGE && *d != 0)
420 || tail == s || *tail != '\0') {
430 /* Returns the value of 'c' as a hexadecimal digit. */
435 case '0': case '1': case '2': case '3': case '4':
436 case '5': case '6': case '7': case '8': case '9':
462 /* Returns the integer value of the 'n' hexadecimal digits starting at 's', or
463 * UINT_MAX if one of those "digits" is not really a hex digit. If 'ok' is
464 * nonnull, '*ok' is set to true if the conversion succeeds or to false if a
465 * non-hex digit is detected. */
467 hexits_value(const char *s, size_t n, bool *ok)
473 for (i = 0; i < n; i++) {
474 int hexit = hexit_value(s[i]);
481 value = (value << 4) + hexit;
489 /* Returns the current working directory as a malloc()'d string, or a null
490 * pointer if the current working directory cannot be determined. */
497 /* Get maximum path length or at least a reasonable estimate. */
498 path_max = pathconf(".", _PC_PATH_MAX);
499 size = (path_max < 0 ? 1024
500 : path_max > 10240 ? 10240
503 /* Get current working directory. */
505 char *buf = xmalloc(size);
506 if (getcwd(buf, size)) {
507 return xrealloc(buf, strlen(buf) + 1);
511 if (error != ERANGE) {
512 VLOG_WARN("getcwd failed (%s)", strerror(error));
521 all_slashes_name(const char *s)
523 return xstrdup(s[0] == '/' && s[1] == '/' && s[2] != '/' ? "//"
528 /* Returns the directory name portion of 'file_name' as a malloc()'d string,
529 * similar to the POSIX dirname() function but thread-safe. */
531 dir_name(const char *file_name)
533 size_t len = strlen(file_name);
534 while (len > 0 && file_name[len - 1] == '/') {
537 while (len > 0 && file_name[len - 1] != '/') {
540 while (len > 0 && file_name[len - 1] == '/') {
543 return len ? xmemdup0(file_name, len) : all_slashes_name(file_name);
546 /* Returns the file name portion of 'file_name' as a malloc()'d string,
547 * similar to the POSIX basename() function but thread-safe. */
549 base_name(const char *file_name)
553 end = strlen(file_name);
554 while (end > 0 && file_name[end - 1] == '/') {
559 return all_slashes_name(file_name);
563 while (start > 0 && file_name[start - 1] != '/') {
567 return xmemdup0(file_name + start, end - start);
570 /* If 'file_name' starts with '/', returns a copy of 'file_name'. Otherwise,
571 * returns an absolute path to 'file_name' considering it relative to 'dir',
572 * which itself must be absolute. 'dir' may be null or the empty string, in
573 * which case the current working directory is used.
575 * Returns a null pointer if 'dir' is null and getcwd() fails. */
577 abs_file_name(const char *dir, const char *file_name)
579 if (file_name[0] == '/') {
580 return xstrdup(file_name);
581 } else if (dir && dir[0]) {
582 char *separator = dir[strlen(dir) - 1] == '/' ? "" : "/";
583 return xasprintf("%s%s%s", dir, separator, file_name);
585 char *cwd = get_cwd();
587 char *abs_name = xasprintf("%s/%s", cwd, file_name);
597 /* Pass a value to this function if it is marked with
598 * __attribute__((warn_unused_result)) and you genuinely want to ignore
599 * its return value. (Note that every scalar type can be implicitly
600 * converted to bool.) */
601 void ignore(bool x OVS_UNUSED) { }
603 /* Returns an appropriate delimiter for inserting just before the 0-based item
604 * 'index' in a list that has 'total' items in it. */
606 english_list_delimiter(size_t index, size_t total)
608 return (index == 0 ? ""
609 : index < total - 1 ? ", "
610 : total > 2 ? ", and "
614 /* Given a 32 bit word 'n', calculates floor(log_2('n')). This is equivalent
615 * to finding the bit position of the most significant one bit in 'n'. It is
616 * an error to call this function with 'n' == 0. */
618 log_2_floor(uint32_t n)
622 #if !defined(UINT_MAX) || !defined(UINT32_MAX)
623 #error "Someone screwed up the #includes."
624 #elif __GNUC__ >= 4 && UINT_MAX == UINT32_MAX
625 return 31 - __builtin_clz(n);
630 #define BIN_SEARCH_STEP(BITS) \
631 if (n >= (1 << BITS)) { \
640 #undef BIN_SEARCH_STEP