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;
36 static char *program_version;
41 ovs_abort(0, "virtual memory exhausted");
45 xcalloc(size_t count, size_t size)
47 void *p = count && size ? calloc(count, size) : malloc(1);
48 COVERAGE_INC(util_xalloc);
58 return xcalloc(1, size);
64 void *p = malloc(size ? size : 1);
65 COVERAGE_INC(util_xalloc);
73 xrealloc(void *p, size_t size)
75 p = realloc(p, size ? size : 1);
76 COVERAGE_INC(util_xalloc);
84 xmemdup(const void *p_, size_t size)
86 void *p = xmalloc(size);
92 xmemdup0(const char *p_, size_t length)
94 char *p = xmalloc(length + 1);
95 memcpy(p, p_, length);
101 xstrdup(const char *s)
103 return xmemdup0(s, strlen(s));
107 xvasprintf(const char *format, va_list args)
113 va_copy(args2, args);
114 needed = vsnprintf(NULL, 0, format, args);
116 s = xmalloc(needed + 1);
118 vsnprintf(s, needed + 1, format, args2);
125 x2nrealloc(void *p, size_t *n, size_t s)
127 *n = *n == 0 ? 1 : 2 * *n;
128 return xrealloc(p, *n * s);
132 xasprintf(const char *format, ...)
137 va_start(args, format);
138 s = xvasprintf(format, args);
144 /* Similar to strlcpy() from OpenBSD, but it never reads more than 'size - 1'
145 * bytes from 'src' and doesn't return anything. */
147 ovs_strlcpy(char *dst, const char *src, size_t size)
150 size_t len = strnlen(src, size - 1);
151 memcpy(dst, src, len);
156 /* Copies 'src' to 'dst'. Reads no more than 'size - 1' bytes from 'src'.
157 * Always null-terminates 'dst' (if 'size' is nonzero), and writes a zero byte
158 * to every otherwise unused byte in 'dst'.
160 * Except for performance, the following call:
161 * ovs_strzcpy(dst, src, size);
162 * is equivalent to these two calls:
163 * memset(dst, '\0', size);
164 * ovs_strlcpy(dst, src, size);
166 * (Thus, ovs_strzcpy() is similar to strncpy() without some of the pitfalls.)
169 ovs_strzcpy(char *dst, const char *src, size_t size)
172 size_t len = strnlen(src, size - 1);
173 memcpy(dst, src, len);
174 memset(dst + len, '\0', size - len);
178 /* Prints 'format' on stderr, formatting it like printf() does. If 'err_no' is
179 * nonzero, then it is formatted with ovs_retval_to_string() and appended to
180 * the message inside parentheses. Then, terminates with abort().
182 * This function is preferred to ovs_fatal() in a situation where it would make
183 * sense for a monitoring process to restart the daemon.
185 * 'format' should not end with a new-line, because this function will add one
188 ovs_abort(int err_no, const char *format, ...)
192 va_start(args, format);
193 ovs_error_valist(err_no, format, args);
199 /* Prints 'format' on stderr, formatting it like printf() does. If 'err_no' is
200 * nonzero, then it is formatted with ovs_retval_to_string() and appended to
201 * the message inside parentheses. Then, terminates with EXIT_FAILURE.
203 * 'format' should not end with a new-line, because this function will add one
206 ovs_fatal(int err_no, const char *format, ...)
210 va_start(args, format);
211 ovs_fatal_valist(err_no, format, args);
214 /* Same as ovs_fatal() except that the arguments are supplied as a va_list. */
216 ovs_fatal_valist(int err_no, const char *format, va_list args)
218 ovs_error_valist(err_no, format, args);
222 /* Prints 'format' on stderr, formatting it like printf() does. If 'err_no' is
223 * nonzero, then it is formatted with ovs_retval_to_string() and appended to
224 * the message inside parentheses.
226 * 'format' should not end with a new-line, because this function will add one
229 ovs_error(int err_no, const char *format, ...)
233 va_start(args, format);
234 ovs_error_valist(err_no, format, args);
238 /* Same as ovs_error() except that the arguments are supplied as a va_list. */
240 ovs_error_valist(int err_no, const char *format, va_list args)
242 int save_errno = errno;
244 fprintf(stderr, "%s: ", program_name);
245 vfprintf(stderr, format, args);
247 fprintf(stderr, " (%s)", ovs_retval_to_string(err_no));
254 /* Many OVS functions return an int which is one of:
257 * - EOF: end of file (not necessarily an error; depends on the function called)
259 * Returns the appropriate human-readable string. The caller must copy the
260 * string if it wants to hold onto it, as the storage may be overwritten on
261 * subsequent function calls.
264 ovs_retval_to_string(int retval)
266 static char unknown[48];
272 return strerror(retval);
275 return "End of file";
277 snprintf(unknown, sizeof unknown, "***unknown return value: %d***", retval);
281 /* Sets global "program_name" and "program_version" variables. Should
282 * be called at the beginning of main() with "argv[0]" as the argument
285 * The 'date' and 'time' arguments should likely be called with
286 * "__DATE__" and "__TIME__" to use the time the binary was built.
287 * Alternatively, the "set_program_name" macro may be called to do this
291 set_program_name__(const char *argv0, const char *date, const char *time)
293 const char *slash = strrchr(argv0, '/');
294 program_name = slash ? slash + 1 : argv0;
296 free(program_version);
297 program_version = xasprintf("%s (Open vSwitch) "VERSION BUILDNR"\n"
299 program_name, date, time);
302 /* Returns a pointer to a string describing the program version. The
303 * caller must not modify or free the returned string.
306 get_program_version(void)
308 return program_version;
311 /* Print the version information for the program. */
313 ovs_print_version(uint8_t min_ofp, uint8_t max_ofp)
315 printf("%s", program_version);
316 if (min_ofp || max_ofp) {
317 printf("OpenFlow versions %#x:%#x\n", min_ofp, max_ofp);
321 /* Writes the 'size' bytes in 'buf' to 'stream' as hex bytes arranged 16 per
322 * line. Numeric offsets are also included, starting at 'ofs' for the first
323 * byte in 'buf'. If 'ascii' is true then the corresponding ASCII characters
324 * are also rendered alongside. */
326 ovs_hex_dump(FILE *stream, const void *buf_, size_t size,
327 uintptr_t ofs, bool ascii)
329 const uint8_t *buf = buf_;
330 const size_t per_line = 16; /* Maximum bytes per line. */
334 size_t start, end, n;
337 /* Number of bytes on this line. */
338 start = ofs % per_line;
340 if (end - start > size)
345 fprintf(stream, "%08jx ", (uintmax_t) ROUND_DOWN(ofs, per_line));
346 for (i = 0; i < start; i++)
347 fprintf(stream, " ");
349 fprintf(stream, "%02hhx%c",
350 buf[i - start], i == per_line / 2 - 1? '-' : ' ');
353 for (; i < per_line; i++)
354 fprintf(stream, " ");
355 fprintf(stream, "|");
356 for (i = 0; i < start; i++)
357 fprintf(stream, " ");
358 for (; i < end; i++) {
359 int c = buf[i - start];
360 putc(c >= 32 && c < 127 ? c : '.', stream);
362 for (; i < per_line; i++)
363 fprintf(stream, " ");
364 fprintf(stream, "|");
366 fprintf(stream, "\n");
375 str_to_int(const char *s, int base, int *i)
378 bool ok = str_to_llong(s, base, &ll);
384 str_to_long(const char *s, int base, long *li)
387 bool ok = str_to_llong(s, base, &ll);
393 str_to_llong(const char *s, int base, long long *x)
395 int save_errno = errno;
398 *x = strtoll(s, &tail, base);
399 if (errno == EINVAL || errno == ERANGE || tail == s || *tail != '\0') {
410 str_to_uint(const char *s, int base, unsigned int *u)
412 return str_to_int(s, base, (int *) u);
416 str_to_ulong(const char *s, int base, unsigned long *ul)
418 return str_to_long(s, base, (long *) ul);
422 str_to_ullong(const char *s, int base, unsigned long long *ull)
424 return str_to_llong(s, base, (long long *) ull);
427 /* Converts floating-point string 's' into a double. If successful, stores
428 * the double in '*d' and returns true; on failure, stores 0 in '*d' and
431 * Underflow (e.g. "1e-9999") is not considered an error, but overflow
432 * (e.g. "1e9999)" is. */
434 str_to_double(const char *s, double *d)
436 int save_errno = errno;
439 *d = strtod(s, &tail);
440 if (errno == EINVAL || (errno == ERANGE && *d != 0)
441 || tail == s || *tail != '\0') {
451 /* Returns the value of 'c' as a hexadecimal digit. */
456 case '0': case '1': case '2': case '3': case '4':
457 case '5': case '6': case '7': case '8': case '9':
483 /* Returns the integer value of the 'n' hexadecimal digits starting at 's', or
484 * UINT_MAX if one of those "digits" is not really a hex digit. If 'ok' is
485 * nonnull, '*ok' is set to true if the conversion succeeds or to false if a
486 * non-hex digit is detected. */
488 hexits_value(const char *s, size_t n, bool *ok)
494 for (i = 0; i < n; i++) {
495 int hexit = hexit_value(s[i]);
502 value = (value << 4) + hexit;
510 /* Returns the current working directory as a malloc()'d string, or a null
511 * pointer if the current working directory cannot be determined. */
518 /* Get maximum path length or at least a reasonable estimate. */
519 path_max = pathconf(".", _PC_PATH_MAX);
520 size = (path_max < 0 ? 1024
521 : path_max > 10240 ? 10240
524 /* Get current working directory. */
526 char *buf = xmalloc(size);
527 if (getcwd(buf, size)) {
528 return xrealloc(buf, strlen(buf) + 1);
532 if (error != ERANGE) {
533 VLOG_WARN("getcwd failed (%s)", strerror(error));
542 all_slashes_name(const char *s)
544 return xstrdup(s[0] == '/' && s[1] == '/' && s[2] != '/' ? "//"
549 /* Returns the directory name portion of 'file_name' as a malloc()'d string,
550 * similar to the POSIX dirname() function but thread-safe. */
552 dir_name(const char *file_name)
554 size_t len = strlen(file_name);
555 while (len > 0 && file_name[len - 1] == '/') {
558 while (len > 0 && file_name[len - 1] != '/') {
561 while (len > 0 && file_name[len - 1] == '/') {
564 return len ? xmemdup0(file_name, len) : all_slashes_name(file_name);
567 /* Returns the file name portion of 'file_name' as a malloc()'d string,
568 * similar to the POSIX basename() function but thread-safe. */
570 base_name(const char *file_name)
574 end = strlen(file_name);
575 while (end > 0 && file_name[end - 1] == '/') {
580 return all_slashes_name(file_name);
584 while (start > 0 && file_name[start - 1] != '/') {
588 return xmemdup0(file_name + start, end - start);
591 /* If 'file_name' starts with '/', returns a copy of 'file_name'. Otherwise,
592 * returns an absolute path to 'file_name' considering it relative to 'dir',
593 * which itself must be absolute. 'dir' may be null or the empty string, in
594 * which case the current working directory is used.
596 * Returns a null pointer if 'dir' is null and getcwd() fails. */
598 abs_file_name(const char *dir, const char *file_name)
600 if (file_name[0] == '/') {
601 return xstrdup(file_name);
602 } else if (dir && dir[0]) {
603 char *separator = dir[strlen(dir) - 1] == '/' ? "" : "/";
604 return xasprintf("%s%s%s", dir, separator, file_name);
606 char *cwd = get_cwd();
608 char *abs_name = xasprintf("%s/%s", cwd, file_name);
618 /* Pass a value to this function if it is marked with
619 * __attribute__((warn_unused_result)) and you genuinely want to ignore
620 * its return value. (Note that every scalar type can be implicitly
621 * converted to bool.) */
622 void ignore(bool x OVS_UNUSED) { }
624 /* Returns an appropriate delimiter for inserting just before the 0-based item
625 * 'index' in a list that has 'total' items in it. */
627 english_list_delimiter(size_t index, size_t total)
629 return (index == 0 ? ""
630 : index < total - 1 ? ", "
631 : total > 2 ? ", and "
635 /* Given a 32 bit word 'n', calculates floor(log_2('n')). This is equivalent
636 * to finding the bit position of the most significant one bit in 'n'. It is
637 * an error to call this function with 'n' == 0. */
639 log_2_floor(uint32_t n)
643 #if !defined(UINT_MAX) || !defined(UINT32_MAX)
644 #error "Someone screwed up the #includes."
645 #elif __GNUC__ >= 4 && UINT_MAX == UINT32_MAX
646 return 31 - __builtin_clz(n);
651 #define BIN_SEARCH_STEP(BITS) \
652 if (n >= (1 << BITS)) { \
661 #undef BIN_SEARCH_STEP