]> git.proxmox.com Git - mirror_qemu.git/blob - util/cutils.c
util/cutils: New qemu_strtosz()
[mirror_qemu.git] / util / cutils.c
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/osdep.h"
25 #include "qemu-common.h"
26 #include "qemu/host-utils.h"
27 #include <math.h>
28
29 #include "qemu/sockets.h"
30 #include "qemu/iov.h"
31 #include "net/net.h"
32 #include "qemu/cutils.h"
33
34 void strpadcpy(char *buf, int buf_size, const char *str, char pad)
35 {
36 int len = qemu_strnlen(str, buf_size);
37 memcpy(buf, str, len);
38 memset(buf + len, pad, buf_size - len);
39 }
40
41 void pstrcpy(char *buf, int buf_size, const char *str)
42 {
43 int c;
44 char *q = buf;
45
46 if (buf_size <= 0)
47 return;
48
49 for(;;) {
50 c = *str++;
51 if (c == 0 || q >= buf + buf_size - 1)
52 break;
53 *q++ = c;
54 }
55 *q = '\0';
56 }
57
58 /* strcat and truncate. */
59 char *pstrcat(char *buf, int buf_size, const char *s)
60 {
61 int len;
62 len = strlen(buf);
63 if (len < buf_size)
64 pstrcpy(buf + len, buf_size - len, s);
65 return buf;
66 }
67
68 int strstart(const char *str, const char *val, const char **ptr)
69 {
70 const char *p, *q;
71 p = str;
72 q = val;
73 while (*q != '\0') {
74 if (*p != *q)
75 return 0;
76 p++;
77 q++;
78 }
79 if (ptr)
80 *ptr = p;
81 return 1;
82 }
83
84 int stristart(const char *str, const char *val, const char **ptr)
85 {
86 const char *p, *q;
87 p = str;
88 q = val;
89 while (*q != '\0') {
90 if (qemu_toupper(*p) != qemu_toupper(*q))
91 return 0;
92 p++;
93 q++;
94 }
95 if (ptr)
96 *ptr = p;
97 return 1;
98 }
99
100 /* XXX: use host strnlen if available ? */
101 int qemu_strnlen(const char *s, int max_len)
102 {
103 int i;
104
105 for(i = 0; i < max_len; i++) {
106 if (s[i] == '\0') {
107 break;
108 }
109 }
110 return i;
111 }
112
113 char *qemu_strsep(char **input, const char *delim)
114 {
115 char *result = *input;
116 if (result != NULL) {
117 char *p;
118
119 for (p = result; *p != '\0'; p++) {
120 if (strchr(delim, *p)) {
121 break;
122 }
123 }
124 if (*p == '\0') {
125 *input = NULL;
126 } else {
127 *p = '\0';
128 *input = p + 1;
129 }
130 }
131 return result;
132 }
133
134 time_t mktimegm(struct tm *tm)
135 {
136 time_t t;
137 int y = tm->tm_year + 1900, m = tm->tm_mon + 1, d = tm->tm_mday;
138 if (m < 3) {
139 m += 12;
140 y--;
141 }
142 t = 86400ULL * (d + (153 * m - 457) / 5 + 365 * y + y / 4 - y / 100 +
143 y / 400 - 719469);
144 t += 3600 * tm->tm_hour + 60 * tm->tm_min + tm->tm_sec;
145 return t;
146 }
147
148 /*
149 * Make sure data goes on disk, but if possible do not bother to
150 * write out the inode just for timestamp updates.
151 *
152 * Unfortunately even in 2009 many operating systems do not support
153 * fdatasync and have to fall back to fsync.
154 */
155 int qemu_fdatasync(int fd)
156 {
157 #ifdef CONFIG_FDATASYNC
158 return fdatasync(fd);
159 #else
160 return fsync(fd);
161 #endif
162 }
163
164 #ifndef _WIN32
165 /* Sets a specific flag */
166 int fcntl_setfl(int fd, int flag)
167 {
168 int flags;
169
170 flags = fcntl(fd, F_GETFL);
171 if (flags == -1)
172 return -errno;
173
174 if (fcntl(fd, F_SETFL, flags | flag) == -1)
175 return -errno;
176
177 return 0;
178 }
179 #endif
180
181 #define QEMU_STRTOSZ_DEFSUFFIX_EB 'E'
182 #define QEMU_STRTOSZ_DEFSUFFIX_PB 'P'
183 #define QEMU_STRTOSZ_DEFSUFFIX_TB 'T'
184 #define QEMU_STRTOSZ_DEFSUFFIX_GB 'G'
185 #define QEMU_STRTOSZ_DEFSUFFIX_MB 'M'
186 #define QEMU_STRTOSZ_DEFSUFFIX_KB 'K'
187 #define QEMU_STRTOSZ_DEFSUFFIX_B 'B'
188
189 static int64_t suffix_mul(char suffix, int64_t unit)
190 {
191 switch (qemu_toupper(suffix)) {
192 case QEMU_STRTOSZ_DEFSUFFIX_B:
193 return 1;
194 case QEMU_STRTOSZ_DEFSUFFIX_KB:
195 return unit;
196 case QEMU_STRTOSZ_DEFSUFFIX_MB:
197 return unit * unit;
198 case QEMU_STRTOSZ_DEFSUFFIX_GB:
199 return unit * unit * unit;
200 case QEMU_STRTOSZ_DEFSUFFIX_TB:
201 return unit * unit * unit * unit;
202 case QEMU_STRTOSZ_DEFSUFFIX_PB:
203 return unit * unit * unit * unit * unit;
204 case QEMU_STRTOSZ_DEFSUFFIX_EB:
205 return unit * unit * unit * unit * unit * unit;
206 }
207 return -1;
208 }
209
210 /*
211 * Convert string to bytes, allowing either B/b for bytes, K/k for KB,
212 * M/m for MB, G/g for GB or T/t for TB. End pointer will be returned
213 * in *end, if not NULL. Return -ERANGE on overflow, Return -EINVAL on
214 * other error.
215 */
216 static int64_t do_strtosz(const char *nptr, char **end,
217 const char default_suffix, int64_t unit)
218 {
219 int64_t retval = -EINVAL;
220 char *endptr;
221 unsigned char c;
222 int mul_required = 0;
223 double val, mul, integral, fraction;
224
225 errno = 0;
226 val = strtod(nptr, &endptr);
227 if (isnan(val) || endptr == nptr || errno != 0) {
228 goto fail;
229 }
230 fraction = modf(val, &integral);
231 if (fraction != 0) {
232 mul_required = 1;
233 }
234 c = *endptr;
235 mul = suffix_mul(c, unit);
236 if (mul >= 0) {
237 endptr++;
238 } else {
239 mul = suffix_mul(default_suffix, unit);
240 assert(mul >= 0);
241 }
242 if (mul == 1 && mul_required) {
243 goto fail;
244 }
245 if ((val * mul >= INT64_MAX) || val < 0) {
246 retval = -ERANGE;
247 goto fail;
248 }
249 retval = val * mul;
250
251 fail:
252 if (end) {
253 *end = endptr;
254 }
255
256 return retval;
257 }
258
259 int64_t qemu_strtosz(const char *nptr, char **end)
260 {
261 return do_strtosz(nptr, end, QEMU_STRTOSZ_DEFSUFFIX_B, 1024);
262 }
263
264 int64_t qemu_strtosz_MiB(const char *nptr, char **end)
265 {
266 return do_strtosz(nptr, end, QEMU_STRTOSZ_DEFSUFFIX_MB, 1024);
267 }
268
269 int64_t qemu_strtosz_metric(const char *nptr, char **end)
270 {
271 return do_strtosz(nptr, end, QEMU_STRTOSZ_DEFSUFFIX_B, 1000);
272 }
273
274 /**
275 * Helper function for error checking after strtol() and the like
276 */
277 static int check_strtox_error(const char *nptr, char *ep,
278 const char **endptr, int libc_errno)
279 {
280 if (endptr) {
281 *endptr = ep;
282 }
283
284 /* Turn "no conversion" into an error */
285 if (libc_errno == 0 && ep == nptr) {
286 return -EINVAL;
287 }
288
289 /* Fail when we're expected to consume the string, but didn't */
290 if (!endptr && *ep) {
291 return -EINVAL;
292 }
293
294 return -libc_errno;
295 }
296
297 /**
298 * Convert string @nptr to a long integer, and store it in @result.
299 *
300 * This is a wrapper around strtol() that is harder to misuse.
301 * Semantics of @nptr, @endptr, @base match strtol() with differences
302 * noted below.
303 *
304 * @nptr may be null, and no conversion is performed then.
305 *
306 * If no conversion is performed, store @nptr in *@endptr and return
307 * -EINVAL.
308 *
309 * If @endptr is null, and the string isn't fully converted, return
310 * -EINVAL. This is the case when the pointer that would be stored in
311 * a non-null @endptr points to a character other than '\0'.
312 *
313 * If the conversion overflows @result, store LONG_MAX in @result,
314 * and return -ERANGE.
315 *
316 * If the conversion underflows @result, store LONG_MIN in @result,
317 * and return -ERANGE.
318 *
319 * Else store the converted value in @result, and return zero.
320 */
321 int qemu_strtol(const char *nptr, const char **endptr, int base,
322 long *result)
323 {
324 char *ep;
325
326 if (!nptr) {
327 if (endptr) {
328 *endptr = nptr;
329 }
330 return -EINVAL;
331 }
332
333 errno = 0;
334 *result = strtol(nptr, &ep, base);
335 return check_strtox_error(nptr, ep, endptr, errno);
336 }
337
338 /**
339 * Convert string @nptr to an unsigned long, and store it in @result.
340 *
341 * This is a wrapper around strtoul() that is harder to misuse.
342 * Semantics of @nptr, @endptr, @base match strtoul() with differences
343 * noted below.
344 *
345 * @nptr may be null, and no conversion is performed then.
346 *
347 * If no conversion is performed, store @nptr in *@endptr and return
348 * -EINVAL.
349 *
350 * If @endptr is null, and the string isn't fully converted, return
351 * -EINVAL. This is the case when the pointer that would be stored in
352 * a non-null @endptr points to a character other than '\0'.
353 *
354 * If the conversion overflows @result, store ULONG_MAX in @result,
355 * and return -ERANGE.
356 *
357 * Else store the converted value in @result, and return zero.
358 *
359 * Note that a number with a leading minus sign gets converted without
360 * the minus sign, checked for overflow (see above), then negated (in
361 * @result's type). This is exactly how strtoul() works.
362 */
363 int qemu_strtoul(const char *nptr, const char **endptr, int base,
364 unsigned long *result)
365 {
366 char *ep;
367
368 if (!nptr) {
369 if (endptr) {
370 *endptr = nptr;
371 }
372 return -EINVAL;
373 }
374
375 errno = 0;
376 *result = strtoul(nptr, &ep, base);
377 /* Windows returns 1 for negative out-of-range values. */
378 if (errno == ERANGE) {
379 *result = -1;
380 }
381 return check_strtox_error(nptr, ep, endptr, errno);
382 }
383
384 /**
385 * Convert string @nptr to an int64_t.
386 *
387 * Works like qemu_strtol(), except it stores INT64_MAX on overflow,
388 * and INT_MIN on underflow.
389 */
390 int qemu_strtoi64(const char *nptr, const char **endptr, int base,
391 int64_t *result)
392 {
393 char *ep;
394
395 if (!nptr) {
396 if (endptr) {
397 *endptr = nptr;
398 }
399 return -EINVAL;
400 }
401
402 errno = 0;
403 /* FIXME This assumes int64_t is long long */
404 *result = strtoll(nptr, &ep, base);
405 return check_strtox_error(nptr, ep, endptr, errno);
406 }
407
408 /**
409 * Convert string @nptr to an uint64_t.
410 *
411 * Works like qemu_strtoul(), except it stores UINT64_MAX on overflow.
412 */
413 int qemu_strtou64(const char *nptr, const char **endptr, int base,
414 uint64_t *result)
415 {
416 char *ep;
417
418 if (!nptr) {
419 if (endptr) {
420 *endptr = nptr;
421 }
422 return -EINVAL;
423 }
424
425 errno = 0;
426 /* FIXME This assumes uint64_t is unsigned long long */
427 *result = strtoull(nptr, &ep, base);
428 /* Windows returns 1 for negative out-of-range values. */
429 if (errno == ERANGE) {
430 *result = -1;
431 }
432 return check_strtox_error(nptr, ep, endptr, errno);
433 }
434
435 /**
436 * parse_uint:
437 *
438 * @s: String to parse
439 * @value: Destination for parsed integer value
440 * @endptr: Destination for pointer to first character not consumed
441 * @base: integer base, between 2 and 36 inclusive, or 0
442 *
443 * Parse unsigned integer
444 *
445 * Parsed syntax is like strtoull()'s: arbitrary whitespace, a single optional
446 * '+' or '-', an optional "0x" if @base is 0 or 16, one or more digits.
447 *
448 * If @s is null, or @base is invalid, or @s doesn't start with an
449 * integer in the syntax above, set *@value to 0, *@endptr to @s, and
450 * return -EINVAL.
451 *
452 * Set *@endptr to point right beyond the parsed integer (even if the integer
453 * overflows or is negative, all digits will be parsed and *@endptr will
454 * point right beyond them).
455 *
456 * If the integer is negative, set *@value to 0, and return -ERANGE.
457 *
458 * If the integer overflows unsigned long long, set *@value to
459 * ULLONG_MAX, and return -ERANGE.
460 *
461 * Else, set *@value to the parsed integer, and return 0.
462 */
463 int parse_uint(const char *s, unsigned long long *value, char **endptr,
464 int base)
465 {
466 int r = 0;
467 char *endp = (char *)s;
468 unsigned long long val = 0;
469
470 if (!s) {
471 r = -EINVAL;
472 goto out;
473 }
474
475 errno = 0;
476 val = strtoull(s, &endp, base);
477 if (errno) {
478 r = -errno;
479 goto out;
480 }
481
482 if (endp == s) {
483 r = -EINVAL;
484 goto out;
485 }
486
487 /* make sure we reject negative numbers: */
488 while (isspace((unsigned char)*s)) {
489 s++;
490 }
491 if (*s == '-') {
492 val = 0;
493 r = -ERANGE;
494 goto out;
495 }
496
497 out:
498 *value = val;
499 *endptr = endp;
500 return r;
501 }
502
503 /**
504 * parse_uint_full:
505 *
506 * @s: String to parse
507 * @value: Destination for parsed integer value
508 * @base: integer base, between 2 and 36 inclusive, or 0
509 *
510 * Parse unsigned integer from entire string
511 *
512 * Have the same behavior of parse_uint(), but with an additional check
513 * for additional data after the parsed number. If extra characters are present
514 * after the parsed number, the function will return -EINVAL, and *@v will
515 * be set to 0.
516 */
517 int parse_uint_full(const char *s, unsigned long long *value, int base)
518 {
519 char *endp;
520 int r;
521
522 r = parse_uint(s, value, &endp, base);
523 if (r < 0) {
524 return r;
525 }
526 if (*endp) {
527 *value = 0;
528 return -EINVAL;
529 }
530
531 return 0;
532 }
533
534 int qemu_parse_fd(const char *param)
535 {
536 long fd;
537 char *endptr;
538
539 errno = 0;
540 fd = strtol(param, &endptr, 10);
541 if (param == endptr /* no conversion performed */ ||
542 errno != 0 /* not representable as long; possibly others */ ||
543 *endptr != '\0' /* final string not empty */ ||
544 fd < 0 /* invalid as file descriptor */ ||
545 fd > INT_MAX /* not representable as int */) {
546 return -1;
547 }
548 return fd;
549 }
550
551 /*
552 * Implementation of ULEB128 (http://en.wikipedia.org/wiki/LEB128)
553 * Input is limited to 14-bit numbers
554 */
555 int uleb128_encode_small(uint8_t *out, uint32_t n)
556 {
557 g_assert(n <= 0x3fff);
558 if (n < 0x80) {
559 *out++ = n;
560 return 1;
561 } else {
562 *out++ = (n & 0x7f) | 0x80;
563 *out++ = n >> 7;
564 return 2;
565 }
566 }
567
568 int uleb128_decode_small(const uint8_t *in, uint32_t *n)
569 {
570 if (!(*in & 0x80)) {
571 *n = *in++;
572 return 1;
573 } else {
574 *n = *in++ & 0x7f;
575 /* we exceed 14 bit number */
576 if (*in & 0x80) {
577 return -1;
578 }
579 *n |= *in++ << 7;
580 return 2;
581 }
582 }
583
584 /*
585 * helper to parse debug environment variables
586 */
587 int parse_debug_env(const char *name, int max, int initial)
588 {
589 char *debug_env = getenv(name);
590 char *inv = NULL;
591 long debug;
592
593 if (!debug_env) {
594 return initial;
595 }
596 errno = 0;
597 debug = strtol(debug_env, &inv, 10);
598 if (inv == debug_env) {
599 return initial;
600 }
601 if (debug < 0 || debug > max || errno != 0) {
602 fprintf(stderr, "warning: %s not in [0, %d]", name, max);
603 return initial;
604 }
605 return debug;
606 }
607
608 /*
609 * Helper to print ethernet mac address
610 */
611 const char *qemu_ether_ntoa(const MACAddr *mac)
612 {
613 static char ret[18];
614
615 snprintf(ret, sizeof(ret), "%02x:%02x:%02x:%02x:%02x:%02x",
616 mac->a[0], mac->a[1], mac->a[2], mac->a[3], mac->a[4], mac->a[5]);
617
618 return ret;
619 }