util: New ovs_retval_to_string() function.
[sliver-openvswitch.git] / lib / util.c
1 /*
2  * Copyright (c) 2008, 2009, 2010 Nicira Networks.
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 #include <config.h>
18 #include "util.h"
19 #include <errno.h>
20 #include <stdarg.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <unistd.h>
25 #include "coverage.h"
26 #include "vlog.h"
27
28 VLOG_DEFINE_THIS_MODULE(util);
29
30 COVERAGE_DEFINE(util_xalloc);
31
32 const char *program_name;
33
34 void
35 out_of_memory(void)
36 {
37     ovs_fatal(0, "virtual memory exhausted");
38 }
39
40 void *
41 xcalloc(size_t count, size_t size)
42 {
43     void *p = count && size ? calloc(count, size) : malloc(1);
44     COVERAGE_INC(util_xalloc);
45     if (p == NULL) {
46         out_of_memory();
47     }
48     return p;
49 }
50
51 void *
52 xzalloc(size_t size)
53 {
54     return xcalloc(1, size);
55 }
56
57 void *
58 xmalloc(size_t size)
59 {
60     void *p = malloc(size ? size : 1);
61     COVERAGE_INC(util_xalloc);
62     if (p == NULL) {
63         out_of_memory();
64     }
65     return p;
66 }
67
68 void *
69 xrealloc(void *p, size_t size)
70 {
71     p = realloc(p, size ? size : 1);
72     COVERAGE_INC(util_xalloc);
73     if (p == NULL) {
74         out_of_memory();
75     }
76     return p;
77 }
78
79 void *
80 xmemdup(const void *p_, size_t size)
81 {
82     void *p = xmalloc(size);
83     memcpy(p, p_, size);
84     return p;
85 }
86
87 char *
88 xmemdup0(const char *p_, size_t length)
89 {
90     char *p = xmalloc(length + 1);
91     memcpy(p, p_, length);
92     p[length] = '\0';
93     return p;
94 }
95
96 char *
97 xstrdup(const char *s)
98 {
99     return xmemdup0(s, strlen(s));
100 }
101
102 char *
103 xvasprintf(const char *format, va_list args)
104 {
105     va_list args2;
106     size_t needed;
107     char *s;
108
109     va_copy(args2, args);
110     needed = vsnprintf(NULL, 0, format, args);
111
112     s = xmalloc(needed + 1);
113
114     vsnprintf(s, needed + 1, format, args2);
115     va_end(args2);
116
117     return s;
118 }
119
120 void *
121 x2nrealloc(void *p, size_t *n, size_t s)
122 {
123     *n = *n == 0 ? 1 : 2 * *n;
124     return xrealloc(p, *n * s);
125 }
126
127 char *
128 xasprintf(const char *format, ...)
129 {
130     va_list args;
131     char *s;
132
133     va_start(args, format);
134     s = xvasprintf(format, args);
135     va_end(args);
136
137     return s;
138 }
139
140 void
141 ovs_strlcpy(char *dst, const char *src, size_t size)
142 {
143     if (size > 0) {
144         size_t n = strlen(src);
145         size_t n_copy = MIN(n, size - 1);
146         memcpy(dst, src, n_copy);
147         dst[n_copy] = '\0';
148     }
149 }
150
151 void
152 ovs_fatal(int err_no, const char *format, ...)
153 {
154     va_list args;
155
156     fprintf(stderr, "%s: ", program_name);
157     va_start(args, format);
158     vfprintf(stderr, format, args);
159     va_end(args);
160     if (err_no != 0)
161         fprintf(stderr, " (%s)", ovs_retval_to_string(err_no));
162     putc('\n', stderr);
163
164     exit(EXIT_FAILURE);
165 }
166
167 void
168 ovs_error(int err_no, const char *format, ...)
169 {
170     int save_errno = errno;
171     va_list args;
172
173     fprintf(stderr, "%s: ", program_name);
174     va_start(args, format);
175     vfprintf(stderr, format, args);
176     va_end(args);
177     if (err_no != 0) {
178         fprintf(stderr, " (%s)", ovs_retval_to_string(err_no));
179     }
180     putc('\n', stderr);
181
182     errno = save_errno;
183 }
184
185 /* Many OVS functions return an int which is one of:
186  * - 0: no error yet
187  * - >0: errno value
188  * - EOF: end of file (not necessarily an error; depends on the function called)
189  *
190  * Returns the appropriate human-readable string. The caller must copy the
191  * string if it wants to hold onto it, as the storage may be overwritten on
192  * subsequent function calls.
193  */
194 const char *
195 ovs_retval_to_string(int retval)
196 {
197     static char unknown[48];
198
199     if (!retval) {
200         return "";
201     }
202     if (retval > 0) {
203         return strerror(retval);
204     }
205     if (retval == EOF) {
206         return "End of file";
207     }
208     snprintf(unknown, sizeof unknown, "***unknown return value: %d***", retval);
209     return unknown;
210 }
211
212 /* Sets program_name based on 'argv0'.  Should be called at the beginning of
213  * main(), as "set_program_name(argv[0]);".  */
214 void set_program_name(const char *argv0)
215 {
216     const char *slash = strrchr(argv0, '/');
217     program_name = slash ? slash + 1 : argv0;
218 }
219
220 /* Print the version information for the program.  */
221 void
222 ovs_print_version(char *date, char *time,
223                   uint8_t min_ofp, uint8_t max_ofp)
224 {
225     printf("%s (Open vSwitch) "VERSION BUILDNR"\n", program_name);
226     printf("Compiled %s %s\n", date, time);
227     if (min_ofp || max_ofp) {
228         printf("OpenFlow versions %#x:%#x\n", min_ofp, max_ofp);
229     }
230 }
231
232 /* Writes the 'size' bytes in 'buf' to 'stream' as hex bytes arranged 16 per
233  * line.  Numeric offsets are also included, starting at 'ofs' for the first
234  * byte in 'buf'.  If 'ascii' is true then the corresponding ASCII characters
235  * are also rendered alongside. */
236 void
237 ovs_hex_dump(FILE *stream, const void *buf_, size_t size,
238              uintptr_t ofs, bool ascii)
239 {
240   const uint8_t *buf = buf_;
241   const size_t per_line = 16; /* Maximum bytes per line. */
242
243   while (size > 0)
244     {
245       size_t start, end, n;
246       size_t i;
247
248       /* Number of bytes on this line. */
249       start = ofs % per_line;
250       end = per_line;
251       if (end - start > size)
252         end = start + size;
253       n = end - start;
254
255       /* Print line. */
256       fprintf(stream, "%08jx  ", (uintmax_t) ROUND_DOWN(ofs, per_line));
257       for (i = 0; i < start; i++)
258         fprintf(stream, "   ");
259       for (; i < end; i++)
260         fprintf(stream, "%02hhx%c",
261                 buf[i - start], i == per_line / 2 - 1? '-' : ' ');
262       if (ascii)
263         {
264           for (; i < per_line; i++)
265             fprintf(stream, "   ");
266           fprintf(stream, "|");
267           for (i = 0; i < start; i++)
268             fprintf(stream, " ");
269           for (; i < end; i++) {
270               int c = buf[i - start];
271               putc(c >= 32 && c < 127 ? c : '.', stream);
272           }
273           for (; i < per_line; i++)
274             fprintf(stream, " ");
275           fprintf(stream, "|");
276         }
277       fprintf(stream, "\n");
278
279       ofs += n;
280       buf += n;
281       size -= n;
282     }
283 }
284
285 bool
286 str_to_int(const char *s, int base, int *i)
287 {
288     long long ll;
289     bool ok = str_to_llong(s, base, &ll);
290     *i = ll;
291     return ok;
292 }
293
294 bool
295 str_to_long(const char *s, int base, long *li)
296 {
297     long long ll;
298     bool ok = str_to_llong(s, base, &ll);
299     *li = ll;
300     return ok;
301 }
302
303 bool
304 str_to_llong(const char *s, int base, long long *x)
305 {
306     int save_errno = errno;
307     char *tail;
308     errno = 0;
309     *x = strtoll(s, &tail, base);
310     if (errno == EINVAL || errno == ERANGE || tail == s || *tail != '\0') {
311         errno = save_errno;
312         *x = 0;
313         return false;
314     } else {
315         errno = save_errno;
316         return true;
317     }
318 }
319
320 bool
321 str_to_uint(const char *s, int base, unsigned int *u)
322 {
323     return str_to_int(s, base, (int *) u);
324 }
325
326 bool
327 str_to_ulong(const char *s, int base, unsigned long *ul)
328 {
329     return str_to_long(s, base, (long *) ul);
330 }
331
332 bool
333 str_to_ullong(const char *s, int base, unsigned long long *ull)
334 {
335     return str_to_llong(s, base, (long long *) ull);
336 }
337
338 /* Converts floating-point string 's' into a double.  If successful, stores
339  * the double in '*d' and returns true; on failure, stores 0 in '*d' and
340  * returns false.
341  *
342  * Underflow (e.g. "1e-9999") is not considered an error, but overflow
343  * (e.g. "1e9999)" is. */
344 bool
345 str_to_double(const char *s, double *d)
346 {
347     int save_errno = errno;
348     char *tail;
349     errno = 0;
350     *d = strtod(s, &tail);
351     if (errno == EINVAL || (errno == ERANGE && *d != 0)
352         || tail == s || *tail != '\0') {
353         errno = save_errno;
354         *d = 0;
355         return false;
356     } else {
357         errno = save_errno;
358         return true;
359     }
360 }
361
362 /* Returns the value of 'c' as a hexadecimal digit. */
363 int
364 hexit_value(int c)
365 {
366     switch (c) {
367     case '0': case '1': case '2': case '3': case '4':
368     case '5': case '6': case '7': case '8': case '9':
369         return c - '0';
370
371     case 'a': case 'A':
372         return 0xa;
373
374     case 'b': case 'B':
375         return 0xb;
376
377     case 'c': case 'C':
378         return 0xc;
379
380     case 'd': case 'D':
381         return 0xd;
382
383     case 'e': case 'E':
384         return 0xe;
385
386     case 'f': case 'F':
387         return 0xf;
388
389     default:
390         return -1;
391     }
392 }
393
394 /* Returns the integer value of the 'n' hexadecimal digits starting at 's', or
395  * UINT_MAX if one of those "digits" is not really a hex digit.  If 'ok' is
396  * nonnull, '*ok' is set to true if the conversion succeeds or to false if a
397  * non-hex digit is detected. */
398 unsigned int
399 hexits_value(const char *s, size_t n, bool *ok)
400 {
401     unsigned int value;
402     size_t i;
403
404     value = 0;
405     for (i = 0; i < n; i++) {
406         int hexit = hexit_value(s[i]);
407         if (hexit < 0) {
408             if (ok) {
409                 *ok = false;
410             }
411             return UINT_MAX;
412         }
413         value = (value << 4) + hexit;
414     }
415     if (ok) {
416         *ok = true;
417     }
418     return value;
419 }
420
421 /* Returns the current working directory as a malloc()'d string, or a null
422  * pointer if the current working directory cannot be determined. */
423 char *
424 get_cwd(void)
425 {
426     long int path_max;
427     size_t size;
428
429     /* Get maximum path length or at least a reasonable estimate. */
430     path_max = pathconf(".", _PC_PATH_MAX);
431     size = (path_max < 0 ? 1024
432             : path_max > 10240 ? 10240
433             : path_max);
434
435     /* Get current working directory. */
436     for (;;) {
437         char *buf = xmalloc(size);
438         if (getcwd(buf, size)) {
439             return xrealloc(buf, strlen(buf) + 1);
440         } else {
441             int error = errno;
442             free(buf);
443             if (error != ERANGE) {
444                 VLOG_WARN("getcwd failed (%s)", strerror(error));
445                 return NULL;
446             }
447             size *= 2;
448         }
449     }
450 }
451
452 static char *
453 all_slashes_name(const char *s)
454 {
455     return xstrdup(s[0] == '/' && s[1] == '/' && s[2] != '/' ? "//"
456                    : s[0] == '/' ? "/"
457                    : ".");
458 }
459
460 /* Returns the directory name portion of 'file_name' as a malloc()'d string,
461  * similar to the POSIX dirname() function but thread-safe. */
462 char *
463 dir_name(const char *file_name)
464 {
465     size_t len = strlen(file_name);
466     while (len > 0 && file_name[len - 1] == '/') {
467         len--;
468     }
469     while (len > 0 && file_name[len - 1] != '/') {
470         len--;
471     }
472     while (len > 0 && file_name[len - 1] == '/') {
473         len--;
474     }
475     return len ? xmemdup0(file_name, len) : all_slashes_name(file_name);
476 }
477
478 /* Returns the file name portion of 'file_name' as a malloc()'d string,
479  * similar to the POSIX basename() function but thread-safe. */
480 char *
481 base_name(const char *file_name)
482 {
483     size_t end, start;
484
485     end = strlen(file_name);
486     while (end > 0 && file_name[end - 1] == '/') {
487         end--;
488     }
489
490     if (!end) {
491         return all_slashes_name(file_name);
492     }
493
494     start = end;
495     while (start > 0 && file_name[start - 1] != '/') {
496         start--;
497     }
498
499     return xmemdup0(file_name + start, end - start);
500 }
501
502 /* If 'file_name' starts with '/', returns a copy of 'file_name'.  Otherwise,
503  * returns an absolute path to 'file_name' considering it relative to 'dir',
504  * which itself must be absolute.  'dir' may be null or the empty string, in
505  * which case the current working directory is used.
506  *
507  * Returns a null pointer if 'dir' is null and getcwd() fails. */
508 char *
509 abs_file_name(const char *dir, const char *file_name)
510 {
511     if (file_name[0] == '/') {
512         return xstrdup(file_name);
513     } else if (dir && dir[0]) {
514         char *separator = dir[strlen(dir) - 1] == '/' ? "" : "/";
515         return xasprintf("%s%s%s", dir, separator, file_name);
516     } else {
517         char *cwd = get_cwd();
518         if (cwd) {
519             char *abs_name = xasprintf("%s/%s", cwd, file_name);
520             free(cwd);
521             return abs_name;
522         } else {
523             return NULL;
524         }
525     }
526 }
527
528
529 /* Pass a value to this function if it is marked with
530  * __attribute__((warn_unused_result)) and you genuinely want to ignore
531  * its return value.  (Note that every scalar type can be implicitly
532  * converted to bool.) */
533 void ignore(bool x OVS_UNUSED) { }