2 * Copyright (c) 2008, 2009, 2010 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.
28 VLOG_DEFINE_THIS_MODULE(util);
30 COVERAGE_DEFINE(util_xalloc);
32 const char *program_name;
37 ovs_fatal(0, "virtual memory exhausted");
41 xcalloc(size_t count, size_t size)
43 void *p = count && size ? calloc(count, size) : malloc(1);
44 COVERAGE_INC(util_xalloc);
54 return xcalloc(1, size);
60 void *p = malloc(size ? size : 1);
61 COVERAGE_INC(util_xalloc);
69 xrealloc(void *p, size_t size)
71 p = realloc(p, size ? size : 1);
72 COVERAGE_INC(util_xalloc);
80 xmemdup(const void *p_, size_t size)
82 void *p = xmalloc(size);
88 xmemdup0(const char *p_, size_t length)
90 char *p = xmalloc(length + 1);
91 memcpy(p, p_, length);
97 xstrdup(const char *s)
99 return xmemdup0(s, strlen(s));
103 xvasprintf(const char *format, va_list args)
109 va_copy(args2, args);
110 needed = vsnprintf(NULL, 0, format, args);
112 s = xmalloc(needed + 1);
114 vsnprintf(s, needed + 1, format, args2);
121 x2nrealloc(void *p, size_t *n, size_t s)
123 *n = *n == 0 ? 1 : 2 * *n;
124 return xrealloc(p, *n * s);
128 xasprintf(const char *format, ...)
133 va_start(args, format);
134 s = xvasprintf(format, args);
141 ovs_strlcpy(char *dst, const char *src, size_t size)
144 size_t n = strlen(src);
145 size_t n_copy = MIN(n, size - 1);
146 memcpy(dst, src, n_copy);
152 ovs_fatal(int err_no, const char *format, ...)
156 fprintf(stderr, "%s: ", program_name);
157 va_start(args, format);
158 vfprintf(stderr, format, args);
161 fprintf(stderr, " (%s)",
162 err_no == EOF ? "end of file" : strerror(err_no));
169 ovs_error(int err_no, const char *format, ...)
171 int save_errno = errno;
174 fprintf(stderr, "%s: ", program_name);
175 va_start(args, format);
176 vfprintf(stderr, format, args);
179 fprintf(stderr, " (%s)",
180 err_no == EOF ? "end of file" : strerror(err_no));
187 /* Sets program_name based on 'argv0'. Should be called at the beginning of
188 * main(), as "set_program_name(argv[0]);". */
189 void set_program_name(const char *argv0)
191 const char *slash = strrchr(argv0, '/');
192 program_name = slash ? slash + 1 : argv0;
195 /* Print the version information for the program. */
197 ovs_print_version(char *date, char *time,
198 uint8_t min_ofp, uint8_t max_ofp)
200 printf("%s (Open vSwitch) "VERSION BUILDNR"\n", program_name);
201 printf("Compiled %s %s\n", date, time);
202 if (min_ofp || max_ofp) {
203 printf("OpenFlow versions %#x:%#x\n", min_ofp, max_ofp);
207 /* Writes the 'size' bytes in 'buf' to 'stream' as hex bytes arranged 16 per
208 * line. Numeric offsets are also included, starting at 'ofs' for the first
209 * byte in 'buf'. If 'ascii' is true then the corresponding ASCII characters
210 * are also rendered alongside. */
212 ovs_hex_dump(FILE *stream, const void *buf_, size_t size,
213 uintptr_t ofs, bool ascii)
215 const uint8_t *buf = buf_;
216 const size_t per_line = 16; /* Maximum bytes per line. */
220 size_t start, end, n;
223 /* Number of bytes on this line. */
224 start = ofs % per_line;
226 if (end - start > size)
231 fprintf(stream, "%08jx ", (uintmax_t) ROUND_DOWN(ofs, per_line));
232 for (i = 0; i < start; i++)
233 fprintf(stream, " ");
235 fprintf(stream, "%02hhx%c",
236 buf[i - start], i == per_line / 2 - 1? '-' : ' ');
239 for (; i < per_line; i++)
240 fprintf(stream, " ");
241 fprintf(stream, "|");
242 for (i = 0; i < start; i++)
243 fprintf(stream, " ");
244 for (; i < end; i++) {
245 int c = buf[i - start];
246 putc(c >= 32 && c < 127 ? c : '.', stream);
248 for (; i < per_line; i++)
249 fprintf(stream, " ");
250 fprintf(stream, "|");
252 fprintf(stream, "\n");
261 str_to_int(const char *s, int base, int *i)
264 bool ok = str_to_llong(s, base, &ll);
270 str_to_long(const char *s, int base, long *li)
273 bool ok = str_to_llong(s, base, &ll);
279 str_to_llong(const char *s, int base, long long *x)
281 int save_errno = errno;
284 *x = strtoll(s, &tail, base);
285 if (errno == EINVAL || errno == ERANGE || tail == s || *tail != '\0') {
296 str_to_uint(const char *s, int base, unsigned int *u)
298 return str_to_int(s, base, (int *) u);
302 str_to_ulong(const char *s, int base, unsigned long *ul)
304 return str_to_long(s, base, (long *) ul);
308 str_to_ullong(const char *s, int base, unsigned long long *ull)
310 return str_to_llong(s, base, (long long *) ull);
313 /* Converts floating-point string 's' into a double. If successful, stores
314 * the double in '*d' and returns true; on failure, stores 0 in '*d' and
317 * Underflow (e.g. "1e-9999") is not considered an error, but overflow
318 * (e.g. "1e9999)" is. */
320 str_to_double(const char *s, double *d)
322 int save_errno = errno;
325 *d = strtod(s, &tail);
326 if (errno == EINVAL || (errno == ERANGE && *d != 0)
327 || tail == s || *tail != '\0') {
337 /* Returns the value of 'c' as a hexadecimal digit. */
342 case '0': case '1': case '2': case '3': case '4':
343 case '5': case '6': case '7': case '8': case '9':
369 /* Returns the integer value of the 'n' hexadecimal digits starting at 's', or
370 * UINT_MAX if one of those "digits" is not really a hex digit. If 'ok' is
371 * nonnull, '*ok' is set to true if the conversion succeeds or to false if a
372 * non-hex digit is detected. */
374 hexits_value(const char *s, size_t n, bool *ok)
380 for (i = 0; i < n; i++) {
381 int hexit = hexit_value(s[i]);
388 value = (value << 4) + hexit;
396 /* Returns the current working directory as a malloc()'d string, or a null
397 * pointer if the current working directory cannot be determined. */
404 /* Get maximum path length or at least a reasonable estimate. */
405 path_max = pathconf(".", _PC_PATH_MAX);
406 size = (path_max < 0 ? 1024
407 : path_max > 10240 ? 10240
410 /* Get current working directory. */
412 char *buf = xmalloc(size);
413 if (getcwd(buf, size)) {
414 return xrealloc(buf, strlen(buf) + 1);
418 if (error != ERANGE) {
419 VLOG_WARN("getcwd failed (%s)", strerror(error));
428 all_slashes_name(const char *s)
430 return xstrdup(s[0] == '/' && s[1] == '/' && s[2] != '/' ? "//"
435 /* Returns the directory name portion of 'file_name' as a malloc()'d string,
436 * similar to the POSIX dirname() function but thread-safe. */
438 dir_name(const char *file_name)
440 size_t len = strlen(file_name);
441 while (len > 0 && file_name[len - 1] == '/') {
444 while (len > 0 && file_name[len - 1] != '/') {
447 while (len > 0 && file_name[len - 1] == '/') {
450 return len ? xmemdup0(file_name, len) : all_slashes_name(file_name);
453 /* Returns the file name portion of 'file_name' as a malloc()'d string,
454 * similar to the POSIX basename() function but thread-safe. */
456 base_name(const char *file_name)
460 end = strlen(file_name);
461 while (end > 0 && file_name[end - 1] == '/') {
466 return all_slashes_name(file_name);
470 while (start > 0 && file_name[start - 1] != '/') {
474 return xmemdup0(file_name + start, end - start);
477 /* If 'file_name' starts with '/', returns a copy of 'file_name'. Otherwise,
478 * returns an absolute path to 'file_name' considering it relative to 'dir',
479 * which itself must be absolute. 'dir' may be null or the empty string, in
480 * which case the current working directory is used.
482 * Returns a null pointer if 'dir' is null and getcwd() fails. */
484 abs_file_name(const char *dir, const char *file_name)
486 if (file_name[0] == '/') {
487 return xstrdup(file_name);
488 } else if (dir && dir[0]) {
489 char *separator = dir[strlen(dir) - 1] == '/' ? "" : "/";
490 return xasprintf("%s%s%s", dir, separator, file_name);
492 char *cwd = get_cwd();
494 char *abs_name = xasprintf("%s/%s", cwd, file_name);
504 /* Pass a value to this function if it is marked with
505 * __attribute__((warn_unused_result)) and you genuinely want to ignore
506 * its return value. (Note that every scalar type can be implicitly
507 * converted to bool.) */
508 void ignore(bool x OVS_UNUSED) { }