xref: /openbmc/qemu/util/cutils.c (revision 4a66d3bf)
1 /*
2  * Simple C functions to supplement the C library
3  *
4  * Copyright (c) 2006 Fabrice Bellard
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  */
24 #include "qemu-common.h"
25 #include "qemu/host-utils.h"
26 #include <math.h>
27 
28 #include "qemu/sockets.h"
29 #include "qemu/iov.h"
30 #include "net/net.h"
31 
32 void strpadcpy(char *buf, int buf_size, const char *str, char pad)
33 {
34     int len = qemu_strnlen(str, buf_size);
35     memcpy(buf, str, len);
36     memset(buf + len, pad, buf_size - len);
37 }
38 
39 void pstrcpy(char *buf, int buf_size, const char *str)
40 {
41     int c;
42     char *q = buf;
43 
44     if (buf_size <= 0)
45         return;
46 
47     for(;;) {
48         c = *str++;
49         if (c == 0 || q >= buf + buf_size - 1)
50             break;
51         *q++ = c;
52     }
53     *q = '\0';
54 }
55 
56 /* strcat and truncate. */
57 char *pstrcat(char *buf, int buf_size, const char *s)
58 {
59     int len;
60     len = strlen(buf);
61     if (len < buf_size)
62         pstrcpy(buf + len, buf_size - len, s);
63     return buf;
64 }
65 
66 int strstart(const char *str, const char *val, const char **ptr)
67 {
68     const char *p, *q;
69     p = str;
70     q = val;
71     while (*q != '\0') {
72         if (*p != *q)
73             return 0;
74         p++;
75         q++;
76     }
77     if (ptr)
78         *ptr = p;
79     return 1;
80 }
81 
82 int stristart(const char *str, const char *val, const char **ptr)
83 {
84     const char *p, *q;
85     p = str;
86     q = val;
87     while (*q != '\0') {
88         if (qemu_toupper(*p) != qemu_toupper(*q))
89             return 0;
90         p++;
91         q++;
92     }
93     if (ptr)
94         *ptr = p;
95     return 1;
96 }
97 
98 /* XXX: use host strnlen if available ? */
99 int qemu_strnlen(const char *s, int max_len)
100 {
101     int i;
102 
103     for(i = 0; i < max_len; i++) {
104         if (s[i] == '\0') {
105             break;
106         }
107     }
108     return i;
109 }
110 
111 char *qemu_strsep(char **input, const char *delim)
112 {
113     char *result = *input;
114     if (result != NULL) {
115         char *p;
116 
117         for (p = result; *p != '\0'; p++) {
118             if (strchr(delim, *p)) {
119                 break;
120             }
121         }
122         if (*p == '\0') {
123             *input = NULL;
124         } else {
125             *p = '\0';
126             *input = p + 1;
127         }
128     }
129     return result;
130 }
131 
132 time_t mktimegm(struct tm *tm)
133 {
134     time_t t;
135     int y = tm->tm_year + 1900, m = tm->tm_mon + 1, d = tm->tm_mday;
136     if (m < 3) {
137         m += 12;
138         y--;
139     }
140     t = 86400ULL * (d + (153 * m - 457) / 5 + 365 * y + y / 4 - y / 100 +
141                  y / 400 - 719469);
142     t += 3600 * tm->tm_hour + 60 * tm->tm_min + tm->tm_sec;
143     return t;
144 }
145 
146 int qemu_fls(int i)
147 {
148     return 32 - clz32(i);
149 }
150 
151 /*
152  * Make sure data goes on disk, but if possible do not bother to
153  * write out the inode just for timestamp updates.
154  *
155  * Unfortunately even in 2009 many operating systems do not support
156  * fdatasync and have to fall back to fsync.
157  */
158 int qemu_fdatasync(int fd)
159 {
160 #ifdef CONFIG_FDATASYNC
161     return fdatasync(fd);
162 #else
163     return fsync(fd);
164 #endif
165 }
166 
167 /*
168  * Searches for an area with non-zero content in a buffer
169  *
170  * Attention! The len must be a multiple of
171  * BUFFER_FIND_NONZERO_OFFSET_UNROLL_FACTOR * sizeof(VECTYPE)
172  * and addr must be a multiple of sizeof(VECTYPE) due to
173  * restriction of optimizations in this function.
174  *
175  * can_use_buffer_find_nonzero_offset() can be used to check
176  * these requirements.
177  *
178  * The return value is the offset of the non-zero area rounded
179  * down to a multiple of sizeof(VECTYPE) for the first
180  * BUFFER_FIND_NONZERO_OFFSET_UNROLL_FACTOR chunks and down to
181  * BUFFER_FIND_NONZERO_OFFSET_UNROLL_FACTOR * sizeof(VECTYPE)
182  * afterwards.
183  *
184  * If the buffer is all zero the return value is equal to len.
185  */
186 
187 size_t buffer_find_nonzero_offset(const void *buf, size_t len)
188 {
189     const VECTYPE *p = buf;
190     const VECTYPE zero = (VECTYPE){0};
191     size_t i;
192 
193     assert(can_use_buffer_find_nonzero_offset(buf, len));
194 
195     if (!len) {
196         return 0;
197     }
198 
199     for (i = 0; i < BUFFER_FIND_NONZERO_OFFSET_UNROLL_FACTOR; i++) {
200         if (!ALL_EQ(p[i], zero)) {
201             return i * sizeof(VECTYPE);
202         }
203     }
204 
205     for (i = BUFFER_FIND_NONZERO_OFFSET_UNROLL_FACTOR;
206          i < len / sizeof(VECTYPE);
207          i += BUFFER_FIND_NONZERO_OFFSET_UNROLL_FACTOR) {
208         VECTYPE tmp0 = p[i + 0] | p[i + 1];
209         VECTYPE tmp1 = p[i + 2] | p[i + 3];
210         VECTYPE tmp2 = p[i + 4] | p[i + 5];
211         VECTYPE tmp3 = p[i + 6] | p[i + 7];
212         VECTYPE tmp01 = tmp0 | tmp1;
213         VECTYPE tmp23 = tmp2 | tmp3;
214         if (!ALL_EQ(tmp01 | tmp23, zero)) {
215             break;
216         }
217     }
218 
219     return i * sizeof(VECTYPE);
220 }
221 
222 /*
223  * Checks if a buffer is all zeroes
224  *
225  * Attention! The len must be a multiple of 4 * sizeof(long) due to
226  * restriction of optimizations in this function.
227  */
228 bool buffer_is_zero(const void *buf, size_t len)
229 {
230     /*
231      * Use long as the biggest available internal data type that fits into the
232      * CPU register and unroll the loop to smooth out the effect of memory
233      * latency.
234      */
235 
236     size_t i;
237     long d0, d1, d2, d3;
238     const long * const data = buf;
239 
240     /* use vector optimized zero check if possible */
241     if (can_use_buffer_find_nonzero_offset(buf, len)) {
242         return buffer_find_nonzero_offset(buf, len) == len;
243     }
244 
245     assert(len % (4 * sizeof(long)) == 0);
246     len /= sizeof(long);
247 
248     for (i = 0; i < len; i += 4) {
249         d0 = data[i + 0];
250         d1 = data[i + 1];
251         d2 = data[i + 2];
252         d3 = data[i + 3];
253 
254         if (d0 || d1 || d2 || d3) {
255             return false;
256         }
257     }
258 
259     return true;
260 }
261 
262 #ifndef _WIN32
263 /* Sets a specific flag */
264 int fcntl_setfl(int fd, int flag)
265 {
266     int flags;
267 
268     flags = fcntl(fd, F_GETFL);
269     if (flags == -1)
270         return -errno;
271 
272     if (fcntl(fd, F_SETFL, flags | flag) == -1)
273         return -errno;
274 
275     return 0;
276 }
277 #endif
278 
279 static int64_t suffix_mul(char suffix, int64_t unit)
280 {
281     switch (qemu_toupper(suffix)) {
282     case STRTOSZ_DEFSUFFIX_B:
283         return 1;
284     case STRTOSZ_DEFSUFFIX_KB:
285         return unit;
286     case STRTOSZ_DEFSUFFIX_MB:
287         return unit * unit;
288     case STRTOSZ_DEFSUFFIX_GB:
289         return unit * unit * unit;
290     case STRTOSZ_DEFSUFFIX_TB:
291         return unit * unit * unit * unit;
292     case STRTOSZ_DEFSUFFIX_PB:
293         return unit * unit * unit * unit * unit;
294     case STRTOSZ_DEFSUFFIX_EB:
295         return unit * unit * unit * unit * unit * unit;
296     }
297     return -1;
298 }
299 
300 /*
301  * Convert string to bytes, allowing either B/b for bytes, K/k for KB,
302  * M/m for MB, G/g for GB or T/t for TB. End pointer will be returned
303  * in *end, if not NULL. Return -ERANGE on overflow, Return -EINVAL on
304  * other error.
305  */
306 int64_t strtosz_suffix_unit(const char *nptr, char **end,
307                             const char default_suffix, int64_t unit)
308 {
309     int64_t retval = -EINVAL;
310     char *endptr;
311     unsigned char c;
312     int mul_required = 0;
313     double val, mul, integral, fraction;
314 
315     errno = 0;
316     val = strtod(nptr, &endptr);
317     if (isnan(val) || endptr == nptr || errno != 0) {
318         goto fail;
319     }
320     fraction = modf(val, &integral);
321     if (fraction != 0) {
322         mul_required = 1;
323     }
324     c = *endptr;
325     mul = suffix_mul(c, unit);
326     if (mul >= 0) {
327         endptr++;
328     } else {
329         mul = suffix_mul(default_suffix, unit);
330         assert(mul >= 0);
331     }
332     if (mul == 1 && mul_required) {
333         goto fail;
334     }
335     if ((val * mul >= INT64_MAX) || val < 0) {
336         retval = -ERANGE;
337         goto fail;
338     }
339     retval = val * mul;
340 
341 fail:
342     if (end) {
343         *end = endptr;
344     }
345 
346     return retval;
347 }
348 
349 int64_t strtosz_suffix(const char *nptr, char **end, const char default_suffix)
350 {
351     return strtosz_suffix_unit(nptr, end, default_suffix, 1024);
352 }
353 
354 int64_t strtosz(const char *nptr, char **end)
355 {
356     return strtosz_suffix(nptr, end, STRTOSZ_DEFSUFFIX_MB);
357 }
358 
359 /**
360  * parse_uint:
361  *
362  * @s: String to parse
363  * @value: Destination for parsed integer value
364  * @endptr: Destination for pointer to first character not consumed
365  * @base: integer base, between 2 and 36 inclusive, or 0
366  *
367  * Parse unsigned integer
368  *
369  * Parsed syntax is like strtoull()'s: arbitrary whitespace, a single optional
370  * '+' or '-', an optional "0x" if @base is 0 or 16, one or more digits.
371  *
372  * If @s is null, or @base is invalid, or @s doesn't start with an
373  * integer in the syntax above, set *@value to 0, *@endptr to @s, and
374  * return -EINVAL.
375  *
376  * Set *@endptr to point right beyond the parsed integer (even if the integer
377  * overflows or is negative, all digits will be parsed and *@endptr will
378  * point right beyond them).
379  *
380  * If the integer is negative, set *@value to 0, and return -ERANGE.
381  *
382  * If the integer overflows unsigned long long, set *@value to
383  * ULLONG_MAX, and return -ERANGE.
384  *
385  * Else, set *@value to the parsed integer, and return 0.
386  */
387 int parse_uint(const char *s, unsigned long long *value, char **endptr,
388                int base)
389 {
390     int r = 0;
391     char *endp = (char *)s;
392     unsigned long long val = 0;
393 
394     if (!s) {
395         r = -EINVAL;
396         goto out;
397     }
398 
399     errno = 0;
400     val = strtoull(s, &endp, base);
401     if (errno) {
402         r = -errno;
403         goto out;
404     }
405 
406     if (endp == s) {
407         r = -EINVAL;
408         goto out;
409     }
410 
411     /* make sure we reject negative numbers: */
412     while (isspace((unsigned char)*s)) {
413         s++;
414     }
415     if (*s == '-') {
416         val = 0;
417         r = -ERANGE;
418         goto out;
419     }
420 
421 out:
422     *value = val;
423     *endptr = endp;
424     return r;
425 }
426 
427 /**
428  * parse_uint_full:
429  *
430  * @s: String to parse
431  * @value: Destination for parsed integer value
432  * @base: integer base, between 2 and 36 inclusive, or 0
433  *
434  * Parse unsigned integer from entire string
435  *
436  * Have the same behavior of parse_uint(), but with an additional check
437  * for additional data after the parsed number. If extra characters are present
438  * after the parsed number, the function will return -EINVAL, and *@v will
439  * be set to 0.
440  */
441 int parse_uint_full(const char *s, unsigned long long *value, int base)
442 {
443     char *endp;
444     int r;
445 
446     r = parse_uint(s, value, &endp, base);
447     if (r < 0) {
448         return r;
449     }
450     if (*endp) {
451         *value = 0;
452         return -EINVAL;
453     }
454 
455     return 0;
456 }
457 
458 int qemu_parse_fd(const char *param)
459 {
460     int fd;
461     char *endptr = NULL;
462 
463     fd = strtol(param, &endptr, 10);
464     if (*endptr || (fd == 0 && param == endptr)) {
465         return -1;
466     }
467     return fd;
468 }
469 
470 /* round down to the nearest power of 2*/
471 int64_t pow2floor(int64_t value)
472 {
473     if (!is_power_of_2(value)) {
474         value = 0x8000000000000000ULL >> clz64(value);
475     }
476     return value;
477 }
478 
479 /*
480  * Implementation of  ULEB128 (http://en.wikipedia.org/wiki/LEB128)
481  * Input is limited to 14-bit numbers
482  */
483 int uleb128_encode_small(uint8_t *out, uint32_t n)
484 {
485     g_assert(n <= 0x3fff);
486     if (n < 0x80) {
487         *out++ = n;
488         return 1;
489     } else {
490         *out++ = (n & 0x7f) | 0x80;
491         *out++ = n >> 7;
492         return 2;
493     }
494 }
495 
496 int uleb128_decode_small(const uint8_t *in, uint32_t *n)
497 {
498     if (!(*in & 0x80)) {
499         *n = *in++;
500         return 1;
501     } else {
502         *n = *in++ & 0x7f;
503         /* we exceed 14 bit number */
504         if (*in & 0x80) {
505             return -1;
506         }
507         *n |= *in++ << 7;
508         return 2;
509     }
510 }
511 
512 /*
513  * helper to parse debug environment variables
514  */
515 int parse_debug_env(const char *name, int max, int initial)
516 {
517     char *debug_env = getenv(name);
518     char *inv = NULL;
519     int debug;
520 
521     if (!debug_env) {
522         return initial;
523     }
524     debug = strtol(debug_env, &inv, 10);
525     if (inv == debug_env) {
526         return initial;
527     }
528     if (debug < 0 || debug > max) {
529         fprintf(stderr, "warning: %s not in [0, %d]", name, max);
530         return initial;
531     }
532     return debug;
533 }
534 
535 /*
536  * Helper to print ethernet mac address
537  */
538 const char *qemu_ether_ntoa(const MACAddr *mac)
539 {
540     static char ret[18];
541 
542     snprintf(ret, sizeof(ret), "%02x:%02x:%02x:%02x:%02x:%02x",
543              mac->a[0], mac->a[1], mac->a[2], mac->a[3], mac->a[4], mac->a[5]);
544 
545     return ret;
546 }
547