util: New function ovs_strzcpy().
[sliver-openvswitch.git] / lib / util.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011 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 /* Similar to strlcpy() from OpenBSD, but it never reads more than 'size - 1'
141  * bytes from 'src' and doesn't return anything. */
142 void
143 ovs_strlcpy(char *dst, const char *src, size_t size)
144 {
145     if (size > 0) {
146         size_t len = strnlen(src, size - 1);
147         memcpy(dst, src, len);
148         dst[len] = '\0';
149     }
150 }
151
152 /* Copies 'src' to 'dst'.  Reads no more than 'size - 1' bytes from 'src'.
153  * Always null-terminates 'dst' (if 'size' is nonzero), and writes a zero byte
154  * to every otherwise unused byte in 'dst'.
155  *
156  * Except for performance, the following call:
157  *     ovs_strzcpy(dst, src, size);
158  * is equivalent to these two calls:
159  *     memset(dst, '\0', size);
160  *     ovs_strlcpy(dst, src, size);
161  *
162  * (Thus, ovs_strzcpy() is similar to strncpy() without some of the pitfalls.)
163  */
164 void
165 ovs_strzcpy(char *dst, const char *src, size_t size)
166 {
167     if (size > 0) {
168         size_t len = strnlen(src, size - 1);
169         memcpy(dst, src, len);
170         memset(dst + len, '\0', size - len);
171     }
172 }
173
174 void
175 ovs_fatal(int err_no, const char *format, ...)
176 {
177     va_list args;
178
179     fprintf(stderr, "%s: ", program_name);
180     va_start(args, format);
181     vfprintf(stderr, format, args);
182     va_end(args);
183     if (err_no != 0)
184         fprintf(stderr, " (%s)", ovs_retval_to_string(err_no));
185     putc('\n', stderr);
186
187     exit(EXIT_FAILURE);
188 }
189
190 void
191 ovs_error(int err_no, const char *format, ...)
192 {
193     int save_errno = errno;
194     va_list args;
195
196     fprintf(stderr, "%s: ", program_name);
197     va_start(args, format);
198     vfprintf(stderr, format, args);
199     va_end(args);
200     if (err_no != 0) {
201         fprintf(stderr, " (%s)", ovs_retval_to_string(err_no));
202     }
203     putc('\n', stderr);
204
205     errno = save_errno;
206 }
207
208 /* Many OVS functions return an int which is one of:
209  * - 0: no error yet
210  * - >0: errno value
211  * - EOF: end of file (not necessarily an error; depends on the function called)
212  *
213  * Returns the appropriate human-readable string. The caller must copy the
214  * string if it wants to hold onto it, as the storage may be overwritten on
215  * subsequent function calls.
216  */
217 const char *
218 ovs_retval_to_string(int retval)
219 {
220     static char unknown[48];
221
222     if (!retval) {
223         return "";
224     }
225     if (retval > 0) {
226         return strerror(retval);
227     }
228     if (retval == EOF) {
229         return "End of file";
230     }
231     snprintf(unknown, sizeof unknown, "***unknown return value: %d***", retval);
232     return unknown;
233 }
234
235 /* Sets program_name based on 'argv0'.  Should be called at the beginning of
236  * main(), as "set_program_name(argv[0]);".  */
237 void set_program_name(const char *argv0)
238 {
239     const char *slash = strrchr(argv0, '/');
240     program_name = slash ? slash + 1 : argv0;
241 }
242
243 /* Print the version information for the program.  */
244 void
245 ovs_print_version(char *date, char *time,
246                   uint8_t min_ofp, uint8_t max_ofp)
247 {
248     printf("%s (Open vSwitch) "VERSION BUILDNR"\n", program_name);
249     printf("Compiled %s %s\n", date, time);
250     if (min_ofp || max_ofp) {
251         printf("OpenFlow versions %#x:%#x\n", min_ofp, max_ofp);
252     }
253 }
254
255 /* Writes the 'size' bytes in 'buf' to 'stream' as hex bytes arranged 16 per
256  * line.  Numeric offsets are also included, starting at 'ofs' for the first
257  * byte in 'buf'.  If 'ascii' is true then the corresponding ASCII characters
258  * are also rendered alongside. */
259 void
260 ovs_hex_dump(FILE *stream, const void *buf_, size_t size,
261              uintptr_t ofs, bool ascii)
262 {
263   const uint8_t *buf = buf_;
264   const size_t per_line = 16; /* Maximum bytes per line. */
265
266   while (size > 0)
267     {
268       size_t start, end, n;
269       size_t i;
270
271       /* Number of bytes on this line. */
272       start = ofs % per_line;
273       end = per_line;
274       if (end - start > size)
275         end = start + size;
276       n = end - start;
277
278       /* Print line. */
279       fprintf(stream, "%08jx  ", (uintmax_t) ROUND_DOWN(ofs, per_line));
280       for (i = 0; i < start; i++)
281         fprintf(stream, "   ");
282       for (; i < end; i++)
283         fprintf(stream, "%02hhx%c",
284                 buf[i - start], i == per_line / 2 - 1? '-' : ' ');
285       if (ascii)
286         {
287           for (; i < per_line; i++)
288             fprintf(stream, "   ");
289           fprintf(stream, "|");
290           for (i = 0; i < start; i++)
291             fprintf(stream, " ");
292           for (; i < end; i++) {
293               int c = buf[i - start];
294               putc(c >= 32 && c < 127 ? c : '.', stream);
295           }
296           for (; i < per_line; i++)
297             fprintf(stream, " ");
298           fprintf(stream, "|");
299         }
300       fprintf(stream, "\n");
301
302       ofs += n;
303       buf += n;
304       size -= n;
305     }
306 }
307
308 bool
309 str_to_int(const char *s, int base, int *i)
310 {
311     long long ll;
312     bool ok = str_to_llong(s, base, &ll);
313     *i = ll;
314     return ok;
315 }
316
317 bool
318 str_to_long(const char *s, int base, long *li)
319 {
320     long long ll;
321     bool ok = str_to_llong(s, base, &ll);
322     *li = ll;
323     return ok;
324 }
325
326 bool
327 str_to_llong(const char *s, int base, long long *x)
328 {
329     int save_errno = errno;
330     char *tail;
331     errno = 0;
332     *x = strtoll(s, &tail, base);
333     if (errno == EINVAL || errno == ERANGE || tail == s || *tail != '\0') {
334         errno = save_errno;
335         *x = 0;
336         return false;
337     } else {
338         errno = save_errno;
339         return true;
340     }
341 }
342
343 bool
344 str_to_uint(const char *s, int base, unsigned int *u)
345 {
346     return str_to_int(s, base, (int *) u);
347 }
348
349 bool
350 str_to_ulong(const char *s, int base, unsigned long *ul)
351 {
352     return str_to_long(s, base, (long *) ul);
353 }
354
355 bool
356 str_to_ullong(const char *s, int base, unsigned long long *ull)
357 {
358     return str_to_llong(s, base, (long long *) ull);
359 }
360
361 /* Converts floating-point string 's' into a double.  If successful, stores
362  * the double in '*d' and returns true; on failure, stores 0 in '*d' and
363  * returns false.
364  *
365  * Underflow (e.g. "1e-9999") is not considered an error, but overflow
366  * (e.g. "1e9999)" is. */
367 bool
368 str_to_double(const char *s, double *d)
369 {
370     int save_errno = errno;
371     char *tail;
372     errno = 0;
373     *d = strtod(s, &tail);
374     if (errno == EINVAL || (errno == ERANGE && *d != 0)
375         || tail == s || *tail != '\0') {
376         errno = save_errno;
377         *d = 0;
378         return false;
379     } else {
380         errno = save_errno;
381         return true;
382     }
383 }
384
385 /* Returns the value of 'c' as a hexadecimal digit. */
386 int
387 hexit_value(int c)
388 {
389     switch (c) {
390     case '0': case '1': case '2': case '3': case '4':
391     case '5': case '6': case '7': case '8': case '9':
392         return c - '0';
393
394     case 'a': case 'A':
395         return 0xa;
396
397     case 'b': case 'B':
398         return 0xb;
399
400     case 'c': case 'C':
401         return 0xc;
402
403     case 'd': case 'D':
404         return 0xd;
405
406     case 'e': case 'E':
407         return 0xe;
408
409     case 'f': case 'F':
410         return 0xf;
411
412     default:
413         return -1;
414     }
415 }
416
417 /* Returns the integer value of the 'n' hexadecimal digits starting at 's', or
418  * UINT_MAX if one of those "digits" is not really a hex digit.  If 'ok' is
419  * nonnull, '*ok' is set to true if the conversion succeeds or to false if a
420  * non-hex digit is detected. */
421 unsigned int
422 hexits_value(const char *s, size_t n, bool *ok)
423 {
424     unsigned int value;
425     size_t i;
426
427     value = 0;
428     for (i = 0; i < n; i++) {
429         int hexit = hexit_value(s[i]);
430         if (hexit < 0) {
431             if (ok) {
432                 *ok = false;
433             }
434             return UINT_MAX;
435         }
436         value = (value << 4) + hexit;
437     }
438     if (ok) {
439         *ok = true;
440     }
441     return value;
442 }
443
444 /* Returns the current working directory as a malloc()'d string, or a null
445  * pointer if the current working directory cannot be determined. */
446 char *
447 get_cwd(void)
448 {
449     long int path_max;
450     size_t size;
451
452     /* Get maximum path length or at least a reasonable estimate. */
453     path_max = pathconf(".", _PC_PATH_MAX);
454     size = (path_max < 0 ? 1024
455             : path_max > 10240 ? 10240
456             : path_max);
457
458     /* Get current working directory. */
459     for (;;) {
460         char *buf = xmalloc(size);
461         if (getcwd(buf, size)) {
462             return xrealloc(buf, strlen(buf) + 1);
463         } else {
464             int error = errno;
465             free(buf);
466             if (error != ERANGE) {
467                 VLOG_WARN("getcwd failed (%s)", strerror(error));
468                 return NULL;
469             }
470             size *= 2;
471         }
472     }
473 }
474
475 static char *
476 all_slashes_name(const char *s)
477 {
478     return xstrdup(s[0] == '/' && s[1] == '/' && s[2] != '/' ? "//"
479                    : s[0] == '/' ? "/"
480                    : ".");
481 }
482
483 /* Returns the directory name portion of 'file_name' as a malloc()'d string,
484  * similar to the POSIX dirname() function but thread-safe. */
485 char *
486 dir_name(const char *file_name)
487 {
488     size_t len = strlen(file_name);
489     while (len > 0 && file_name[len - 1] == '/') {
490         len--;
491     }
492     while (len > 0 && file_name[len - 1] != '/') {
493         len--;
494     }
495     while (len > 0 && file_name[len - 1] == '/') {
496         len--;
497     }
498     return len ? xmemdup0(file_name, len) : all_slashes_name(file_name);
499 }
500
501 /* Returns the file name portion of 'file_name' as a malloc()'d string,
502  * similar to the POSIX basename() function but thread-safe. */
503 char *
504 base_name(const char *file_name)
505 {
506     size_t end, start;
507
508     end = strlen(file_name);
509     while (end > 0 && file_name[end - 1] == '/') {
510         end--;
511     }
512
513     if (!end) {
514         return all_slashes_name(file_name);
515     }
516
517     start = end;
518     while (start > 0 && file_name[start - 1] != '/') {
519         start--;
520     }
521
522     return xmemdup0(file_name + start, end - start);
523 }
524
525 /* If 'file_name' starts with '/', returns a copy of 'file_name'.  Otherwise,
526  * returns an absolute path to 'file_name' considering it relative to 'dir',
527  * which itself must be absolute.  'dir' may be null or the empty string, in
528  * which case the current working directory is used.
529  *
530  * Returns a null pointer if 'dir' is null and getcwd() fails. */
531 char *
532 abs_file_name(const char *dir, const char *file_name)
533 {
534     if (file_name[0] == '/') {
535         return xstrdup(file_name);
536     } else if (dir && dir[0]) {
537         char *separator = dir[strlen(dir) - 1] == '/' ? "" : "/";
538         return xasprintf("%s%s%s", dir, separator, file_name);
539     } else {
540         char *cwd = get_cwd();
541         if (cwd) {
542             char *abs_name = xasprintf("%s/%s", cwd, file_name);
543             free(cwd);
544             return abs_name;
545         } else {
546             return NULL;
547         }
548     }
549 }
550
551
552 /* Pass a value to this function if it is marked with
553  * __attribute__((warn_unused_result)) and you genuinely want to ignore
554  * its return value.  (Note that every scalar type can be implicitly
555  * converted to bool.) */
556 void ignore(bool x OVS_UNUSED) { }