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 const char *program_name;
35 ovs_fatal(0, "virtual memory exhausted");
39 xcalloc(size_t count, size_t size)
41 void *p = count && size ? calloc(count, size) : malloc(1);
42 COVERAGE_INC(util_xalloc);
52 return xcalloc(1, size);
58 void *p = malloc(size ? size : 1);
59 COVERAGE_INC(util_xalloc);
67 xrealloc(void *p, size_t size)
69 p = realloc(p, size ? size : 1);
70 COVERAGE_INC(util_xalloc);
78 xmemdup(const void *p_, size_t size)
80 void *p = xmalloc(size);
86 xmemdup0(const char *p_, size_t length)
88 char *p = xmalloc(length + 1);
89 memcpy(p, p_, length);
95 xstrdup(const char *s)
97 return xmemdup0(s, strlen(s));
101 xvasprintf(const char *format, va_list args)
107 va_copy(args2, args);
108 needed = vsnprintf(NULL, 0, format, args);
110 s = xmalloc(needed + 1);
112 vsnprintf(s, needed + 1, format, args2);
119 x2nrealloc(void *p, size_t *n, size_t s)
121 *n = *n == 0 ? 1 : 2 * *n;
122 return xrealloc(p, *n * s);
126 xasprintf(const char *format, ...)
131 va_start(args, format);
132 s = xvasprintf(format, args);
139 ovs_strlcpy(char *dst, const char *src, size_t size)
142 size_t n = strlen(src);
143 size_t n_copy = MIN(n, size - 1);
144 memcpy(dst, src, n_copy);
150 ovs_fatal(int err_no, const char *format, ...)
154 fprintf(stderr, "%s: ", program_name);
155 va_start(args, format);
156 vfprintf(stderr, format, args);
159 fprintf(stderr, " (%s)",
160 err_no == EOF ? "end of file" : strerror(err_no));
167 ovs_error(int err_no, const char *format, ...)
169 int save_errno = errno;
172 fprintf(stderr, "%s: ", program_name);
173 va_start(args, format);
174 vfprintf(stderr, format, args);
177 fprintf(stderr, " (%s)",
178 err_no == EOF ? "end of file" : strerror(err_no));
185 /* Sets program_name based on 'argv0'. Should be called at the beginning of
186 * main(), as "set_program_name(argv[0]);". */
187 void set_program_name(const char *argv0)
189 const char *slash = strrchr(argv0, '/');
190 program_name = slash ? slash + 1 : argv0;
193 /* Print the version information for the program. */
195 ovs_print_version(char *date, char *time,
196 uint8_t min_ofp, uint8_t max_ofp)
198 printf("%s (Open vSwitch) "VERSION BUILDNR"\n", program_name);
199 printf("Compiled %s %s\n", date, time);
200 if (min_ofp || max_ofp) {
201 printf("OpenFlow versions %#x:%#x\n", min_ofp, max_ofp);
205 /* Writes the 'size' bytes in 'buf' to 'stream' as hex bytes arranged 16 per
206 * line. Numeric offsets are also included, starting at 'ofs' for the first
207 * byte in 'buf'. If 'ascii' is true then the corresponding ASCII characters
208 * are also rendered alongside. */
210 ovs_hex_dump(FILE *stream, const void *buf_, size_t size,
211 uintptr_t ofs, bool ascii)
213 const uint8_t *buf = buf_;
214 const size_t per_line = 16; /* Maximum bytes per line. */
218 size_t start, end, n;
221 /* Number of bytes on this line. */
222 start = ofs % per_line;
224 if (end - start > size)
229 fprintf(stream, "%08jx ", (uintmax_t) ROUND_DOWN(ofs, per_line));
230 for (i = 0; i < start; i++)
231 fprintf(stream, " ");
233 fprintf(stream, "%02hhx%c",
234 buf[i - start], i == per_line / 2 - 1? '-' : ' ');
237 for (; i < per_line; i++)
238 fprintf(stream, " ");
239 fprintf(stream, "|");
240 for (i = 0; i < start; i++)
241 fprintf(stream, " ");
242 for (; i < end; i++) {
243 int c = buf[i - start];
244 putc(c >= 32 && c < 127 ? c : '.', stream);
246 for (; i < per_line; i++)
247 fprintf(stream, " ");
248 fprintf(stream, "|");
250 fprintf(stream, "\n");
259 str_to_int(const char *s, int base, int *i)
262 bool ok = str_to_llong(s, base, &ll);
268 str_to_long(const char *s, int base, long *li)
271 bool ok = str_to_llong(s, base, &ll);
277 str_to_llong(const char *s, int base, long long *x)
279 int save_errno = errno;
282 *x = strtoll(s, &tail, base);
283 if (errno == EINVAL || errno == ERANGE || tail == s || *tail != '\0') {
294 str_to_uint(const char *s, int base, unsigned int *u)
296 return str_to_int(s, base, (int *) u);
300 str_to_ulong(const char *s, int base, unsigned long *ul)
302 return str_to_long(s, base, (long *) ul);
306 str_to_ullong(const char *s, int base, unsigned long long *ull)
308 return str_to_llong(s, base, (long long *) ull);
311 /* Converts floating-point string 's' into a double. If successful, stores
312 * the double in '*d' and returns true; on failure, stores 0 in '*d' and
315 * Underflow (e.g. "1e-9999") is not considered an error, but overflow
316 * (e.g. "1e9999)" is. */
318 str_to_double(const char *s, double *d)
320 int save_errno = errno;
323 *d = strtod(s, &tail);
324 if (errno == EINVAL || (errno == ERANGE && *d != 0)
325 || tail == s || *tail != '\0') {
335 /* Returns the value of 'c' as a hexadecimal digit. */
340 case '0': case '1': case '2': case '3': case '4':
341 case '5': case '6': case '7': case '8': case '9':
366 /* Returns the current working directory as a malloc()'d string, or a null
367 * pointer if the current working directory cannot be determined. */
374 /* Get maximum path length or at least a reasonable estimate. */
375 path_max = pathconf(".", _PC_PATH_MAX);
376 size = (path_max < 0 ? 1024
377 : path_max > 10240 ? 10240
380 /* Get current working directory. */
382 char *buf = xmalloc(size);
383 if (getcwd(buf, size)) {
384 return xrealloc(buf, strlen(buf) + 1);
388 if (error != ERANGE) {
389 VLOG_WARN("getcwd failed (%s)", strerror(error));
397 /* Returns the directory name portion of 'file_name' as a malloc()'d string,
398 * similar to the POSIX dirname() function but thread-safe. */
400 dir_name(const char *file_name)
402 size_t len = strlen(file_name);
403 while (len > 0 && file_name[len - 1] == '/') {
406 while (len > 0 && file_name[len - 1] != '/') {
409 while (len > 0 && file_name[len - 1] == '/') {
413 return xstrdup((file_name[0] == '/'
414 && file_name[1] == '/'
415 && file_name[2] != '/') ? "//"
416 : file_name[0] == '/' ? "/"
419 return xmemdup0(file_name, len);
423 /* If 'file_name' starts with '/', returns a copy of 'file_name'. Otherwise,
424 * returns an absolute path to 'file_name' considering it relative to 'dir',
425 * which itself must be absolute. 'dir' may be null or the empty string, in
426 * which case the current working directory is used.
428 * Returns a null pointer if 'dir' is null and getcwd() fails. */
430 abs_file_name(const char *dir, const char *file_name)
432 if (file_name[0] == '/') {
433 return xstrdup(file_name);
434 } else if (dir && dir[0]) {
435 char *separator = dir[strlen(dir) - 1] == '/' ? "" : "/";
436 return xasprintf("%s%s%s", dir, separator, file_name);
438 char *cwd = get_cwd();
440 char *abs_name = xasprintf("%s/%s", cwd, file_name);
450 /* Pass a value to this function if it is marked with
451 * __attribute__((warn_unused_result)) and you genuinely want to ignore
452 * its return value. (Note that every scalar type can be implicitly
453 * converted to bool.) */
454 void ignore(bool x OVS_UNUSED) { }