cutils: Use parse_uint in qemu_strtosz for negative rejection
[qemu/kevin.git] / util / cutils.c
blobe3a49209a94ffd8fe0fabad31b54c2ba70f16591
1 /*
2 * Simple C functions to supplement the C library
4 * Copyright (c) 2006 Fabrice Bellard
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:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
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.
25 #include "qemu/osdep.h"
26 #include "qemu/host-utils.h"
27 #include <math.h>
29 #ifdef __FreeBSD__
30 #include <sys/sysctl.h>
31 #include <sys/user.h>
32 #endif
34 #ifdef __NetBSD__
35 #include <sys/sysctl.h>
36 #endif
38 #ifdef __HAIKU__
39 #include <kernel/image.h>
40 #endif
42 #ifdef __APPLE__
43 #include <mach-o/dyld.h>
44 #endif
46 #ifdef G_OS_WIN32
47 #include <pathcch.h>
48 #include <wchar.h>
49 #endif
51 #include "qemu/ctype.h"
52 #include "qemu/cutils.h"
53 #include "qemu/error-report.h"
55 void strpadcpy(char *buf, int buf_size, const char *str, char pad)
57 int len = qemu_strnlen(str, buf_size);
58 memcpy(buf, str, len);
59 memset(buf + len, pad, buf_size - len);
62 void pstrcpy(char *buf, int buf_size, const char *str)
64 int c;
65 char *q = buf;
67 if (buf_size <= 0)
68 return;
70 for(;;) {
71 c = *str++;
72 if (c == 0 || q >= buf + buf_size - 1)
73 break;
74 *q++ = c;
76 *q = '\0';
79 /* strcat and truncate. */
80 char *pstrcat(char *buf, int buf_size, const char *s)
82 int len;
83 len = strlen(buf);
84 if (len < buf_size)
85 pstrcpy(buf + len, buf_size - len, s);
86 return buf;
89 int strstart(const char *str, const char *val, const char **ptr)
91 const char *p, *q;
92 p = str;
93 q = val;
94 while (*q != '\0') {
95 if (*p != *q)
96 return 0;
97 p++;
98 q++;
100 if (ptr)
101 *ptr = p;
102 return 1;
105 int stristart(const char *str, const char *val, const char **ptr)
107 const char *p, *q;
108 p = str;
109 q = val;
110 while (*q != '\0') {
111 if (qemu_toupper(*p) != qemu_toupper(*q))
112 return 0;
113 p++;
114 q++;
116 if (ptr)
117 *ptr = p;
118 return 1;
121 /* XXX: use host strnlen if available ? */
122 int qemu_strnlen(const char *s, int max_len)
124 int i;
126 for(i = 0; i < max_len; i++) {
127 if (s[i] == '\0') {
128 break;
131 return i;
134 char *qemu_strsep(char **input, const char *delim)
136 char *result = *input;
137 if (result != NULL) {
138 char *p;
140 for (p = result; *p != '\0'; p++) {
141 if (strchr(delim, *p)) {
142 break;
145 if (*p == '\0') {
146 *input = NULL;
147 } else {
148 *p = '\0';
149 *input = p + 1;
152 return result;
155 time_t mktimegm(struct tm *tm)
157 time_t t;
158 int y = tm->tm_year + 1900, m = tm->tm_mon + 1, d = tm->tm_mday;
159 if (m < 3) {
160 m += 12;
161 y--;
163 t = 86400ULL * (d + (153 * m - 457) / 5 + 365 * y + y / 4 - y / 100 +
164 y / 400 - 719469);
165 t += 3600 * tm->tm_hour + 60 * tm->tm_min + tm->tm_sec;
166 return t;
169 static int64_t suffix_mul(char suffix, int64_t unit)
171 switch (qemu_toupper(suffix)) {
172 case 'B':
173 return 1;
174 case 'K':
175 return unit;
176 case 'M':
177 return unit * unit;
178 case 'G':
179 return unit * unit * unit;
180 case 'T':
181 return unit * unit * unit * unit;
182 case 'P':
183 return unit * unit * unit * unit * unit;
184 case 'E':
185 return unit * unit * unit * unit * unit * unit;
187 return -1;
191 * Convert size string to bytes.
193 * The size parsing supports the following syntaxes
194 * - 12345 - decimal, scale determined by @default_suffix and @unit
195 * - 12345{bBkKmMgGtTpPeE} - decimal, scale determined by suffix and @unit
196 * - 12345.678{kKmMgGtTpPeE} - decimal, scale determined by suffix, and
197 * fractional portion is truncated to byte
198 * - 0x7fEE - hexadecimal, unit determined by @default_suffix
200 * The following are intentionally not supported
201 * - hex with scaling suffix, such as 0x20M
202 * - octal, such as 08
203 * - fractional hex, such as 0x1.8
204 * - negative values, including -0
205 * - floating point exponents, such as 1e3
207 * The end pointer will be returned in *end, if not NULL. If there is
208 * no fraction, the input can be decimal or hexadecimal; if there is a
209 * non-zero fraction, then the input must be decimal and there must be
210 * a suffix (possibly by @default_suffix) larger than Byte, and the
211 * fractional portion may suffer from precision loss or rounding. The
212 * input must be positive.
214 * Return -ERANGE on overflow (with *@end advanced), and -EINVAL on
215 * other error (with *@end at @nptr). Unlike strtoull, *@result is
216 * set to 0 on all errors, as returning UINT64_MAX on overflow is less
217 * likely to be usable as a size.
219 static int do_strtosz(const char *nptr, const char **end,
220 const char default_suffix, int64_t unit,
221 uint64_t *result)
223 int retval;
224 const char *endptr, *f;
225 unsigned char c;
226 uint64_t val, valf = 0;
227 int64_t mul;
229 /* Parse integral portion as decimal. */
230 retval = parse_uint(nptr, &endptr, 10, &val);
231 if (retval) {
232 goto out;
234 if (val == 0 && (*endptr == 'x' || *endptr == 'X')) {
235 /* Input looks like hex; reparse, and insist on no fraction or suffix. */
236 retval = qemu_strtou64(nptr, &endptr, 16, &val);
237 if (retval) {
238 goto out;
240 if (*endptr == '.' || suffix_mul(*endptr, unit) > 0) {
241 endptr = nptr;
242 retval = -EINVAL;
243 goto out;
245 } else if (*endptr == '.') {
247 * Input looks like a fraction. Make sure even 1.k works
248 * without fractional digits. If we see an exponent, treat
249 * the entire input as invalid instead.
251 double fraction;
253 f = endptr;
254 retval = qemu_strtod_finite(f, &endptr, &fraction);
255 if (retval) {
256 endptr++;
257 } else if (memchr(f, 'e', endptr - f) || memchr(f, 'E', endptr - f)) {
258 endptr = nptr;
259 retval = -EINVAL;
260 goto out;
261 } else {
262 /* Extract into a 64-bit fixed-point fraction. */
263 valf = (uint64_t)(fraction * 0x1p64);
266 c = *endptr;
267 mul = suffix_mul(c, unit);
268 if (mul > 0) {
269 endptr++;
270 } else {
271 mul = suffix_mul(default_suffix, unit);
272 assert(mul > 0);
274 if (mul == 1) {
275 /* When a fraction is present, a scale is required. */
276 if (valf != 0) {
277 endptr = nptr;
278 retval = -EINVAL;
279 goto out;
281 } else {
282 uint64_t valh, tmp;
284 /* Compute exact result: 64.64 x 64.0 -> 128.64 fixed point */
285 mulu64(&val, &valh, val, mul);
286 mulu64(&valf, &tmp, valf, mul);
287 val += tmp;
288 valh += val < tmp;
290 /* Round 0.5 upward. */
291 tmp = valf >> 63;
292 val += tmp;
293 valh += val < tmp;
295 /* Report overflow. */
296 if (valh != 0) {
297 retval = -ERANGE;
298 goto out;
302 retval = 0;
304 out:
305 if (end) {
306 *end = endptr;
307 } else if (nptr && *endptr) {
308 retval = -EINVAL;
310 if (retval == 0) {
311 *result = val;
312 } else {
313 *result = 0;
314 if (end && retval == -EINVAL) {
315 *end = nptr;
319 return retval;
322 int qemu_strtosz(const char *nptr, const char **end, uint64_t *result)
324 return do_strtosz(nptr, end, 'B', 1024, result);
327 int qemu_strtosz_MiB(const char *nptr, const char **end, uint64_t *result)
329 return do_strtosz(nptr, end, 'M', 1024, result);
332 int qemu_strtosz_metric(const char *nptr, const char **end, uint64_t *result)
334 return do_strtosz(nptr, end, 'B', 1000, result);
338 * Helper function for error checking after strtol() and the like
340 static int check_strtox_error(const char *nptr, char *ep,
341 const char **endptr, bool check_zero,
342 int libc_errno)
344 assert(ep >= nptr);
346 /* Windows has a bug in that it fails to parse 0 from "0x" in base 16 */
347 if (check_zero && ep == nptr && libc_errno == 0) {
348 char *tmp;
350 errno = 0;
351 if (strtol(nptr, &tmp, 10) == 0 && errno == 0 &&
352 (*tmp == 'x' || *tmp == 'X')) {
353 ep = tmp;
357 if (endptr) {
358 *endptr = ep;
361 /* Turn "no conversion" into an error */
362 if (libc_errno == 0 && ep == nptr) {
363 return -EINVAL;
366 /* Fail when we're expected to consume the string, but didn't */
367 if (!endptr && *ep) {
368 return -EINVAL;
371 return -libc_errno;
375 * Convert string @nptr to an integer, and store it in @result.
377 * This is a wrapper around strtol() that is harder to misuse.
378 * Semantics of @nptr, @endptr, @base match strtol() with differences
379 * noted below.
381 * @nptr may be null, and no conversion is performed then.
383 * If no conversion is performed, store @nptr in *@endptr, 0 in
384 * @result, and return -EINVAL.
386 * If @endptr is null, and the string isn't fully converted, return
387 * -EINVAL with @result set to the parsed value. This is the case
388 * when the pointer that would be stored in a non-null @endptr points
389 * to a character other than '\0'.
391 * If the conversion overflows @result, store INT_MAX in @result,
392 * and return -ERANGE.
394 * If the conversion underflows @result, store INT_MIN in @result,
395 * and return -ERANGE.
397 * Else store the converted value in @result, and return zero.
399 * This matches the behavior of strtol() on 32-bit platforms, even on
400 * platforms where long is 64-bits.
402 int qemu_strtoi(const char *nptr, const char **endptr, int base,
403 int *result)
405 char *ep;
406 long long lresult;
408 assert((unsigned) base <= 36 && base != 1);
409 if (!nptr) {
410 *result = 0;
411 if (endptr) {
412 *endptr = nptr;
414 return -EINVAL;
417 errno = 0;
418 lresult = strtoll(nptr, &ep, base);
419 if (lresult < INT_MIN) {
420 *result = INT_MIN;
421 errno = ERANGE;
422 } else if (lresult > INT_MAX) {
423 *result = INT_MAX;
424 errno = ERANGE;
425 } else {
426 *result = lresult;
428 return check_strtox_error(nptr, ep, endptr, lresult == 0, errno);
432 * Convert string @nptr to an unsigned integer, and store it in @result.
434 * This is a wrapper around strtoul() that is harder to misuse.
435 * Semantics of @nptr, @endptr, @base match strtoul() with differences
436 * noted below.
438 * @nptr may be null, and no conversion is performed then.
440 * If no conversion is performed, store @nptr in *@endptr, 0 in
441 * @result, and return -EINVAL.
443 * If @endptr is null, and the string isn't fully converted, return
444 * -EINVAL with @result set to the parsed value. This is the case
445 * when the pointer that would be stored in a non-null @endptr points
446 * to a character other than '\0'.
448 * If the conversion overflows @result, store UINT_MAX in @result,
449 * and return -ERANGE.
451 * Else store the converted value in @result, and return zero.
453 * Note that a number with a leading minus sign gets converted without
454 * the minus sign, checked for overflow (see above), then negated (in
455 * @result's type). This matches the behavior of strtoul() on 32-bit
456 * platforms, even on platforms where long is 64-bits.
458 int qemu_strtoui(const char *nptr, const char **endptr, int base,
459 unsigned int *result)
461 char *ep;
462 unsigned long long lresult;
463 bool neg;
465 assert((unsigned) base <= 36 && base != 1);
466 if (!nptr) {
467 *result = 0;
468 if (endptr) {
469 *endptr = nptr;
471 return -EINVAL;
474 errno = 0;
475 lresult = strtoull(nptr, &ep, base);
477 /* Windows returns 1 for negative out-of-range values. */
478 if (errno == ERANGE) {
479 *result = -1;
480 } else {
482 * Note that platforms with 32-bit strtoul only accept input
483 * in the range [-4294967295, 4294967295]; but we used 64-bit
484 * strtoull which wraps -18446744073709551615 to 1 instead of
485 * declaring overflow. So we must check if '-' was parsed,
486 * and if so, undo the negation before doing our bounds check.
488 neg = memchr(nptr, '-', ep - nptr) != NULL;
489 if (neg) {
490 lresult = -lresult;
492 if (lresult > UINT_MAX) {
493 *result = UINT_MAX;
494 errno = ERANGE;
495 } else {
496 *result = neg ? -lresult : lresult;
499 return check_strtox_error(nptr, ep, endptr, lresult == 0, errno);
503 * Convert string @nptr to a long integer, and store it in @result.
505 * This is a wrapper around strtol() that is harder to misuse.
506 * Semantics of @nptr, @endptr, @base match strtol() with differences
507 * noted below.
509 * @nptr may be null, and no conversion is performed then.
511 * If no conversion is performed, store @nptr in *@endptr, 0 in
512 * @result, and return -EINVAL.
514 * If @endptr is null, and the string isn't fully converted, return
515 * -EINVAL with @result set to the parsed value. This is the case
516 * when the pointer that would be stored in a non-null @endptr points
517 * to a character other than '\0'.
519 * If the conversion overflows @result, store LONG_MAX in @result,
520 * and return -ERANGE.
522 * If the conversion underflows @result, store LONG_MIN in @result,
523 * and return -ERANGE.
525 * Else store the converted value in @result, and return zero.
527 int qemu_strtol(const char *nptr, const char **endptr, int base,
528 long *result)
530 char *ep;
532 assert((unsigned) base <= 36 && base != 1);
533 if (!nptr) {
534 *result = 0;
535 if (endptr) {
536 *endptr = nptr;
538 return -EINVAL;
541 errno = 0;
542 *result = strtol(nptr, &ep, base);
543 return check_strtox_error(nptr, ep, endptr, *result == 0, errno);
547 * Convert string @nptr to an unsigned long, and store it in @result.
549 * This is a wrapper around strtoul() that is harder to misuse.
550 * Semantics of @nptr, @endptr, @base match strtoul() with differences
551 * noted below.
553 * @nptr may be null, and no conversion is performed then.
555 * If no conversion is performed, store @nptr in *@endptr, 0 in
556 * @result, and return -EINVAL.
558 * If @endptr is null, and the string isn't fully converted, return
559 * -EINVAL with @result set to the parsed value. This is the case
560 * when the pointer that would be stored in a non-null @endptr points
561 * to a character other than '\0'.
563 * If the conversion overflows @result, store ULONG_MAX in @result,
564 * and return -ERANGE.
566 * Else store the converted value in @result, and return zero.
568 * Note that a number with a leading minus sign gets converted without
569 * the minus sign, checked for overflow (see above), then negated (in
570 * @result's type). This is exactly how strtoul() works.
572 int qemu_strtoul(const char *nptr, const char **endptr, int base,
573 unsigned long *result)
575 char *ep;
577 assert((unsigned) base <= 36 && base != 1);
578 if (!nptr) {
579 *result = 0;
580 if (endptr) {
581 *endptr = nptr;
583 return -EINVAL;
586 errno = 0;
587 *result = strtoul(nptr, &ep, base);
588 /* Windows returns 1 for negative out-of-range values. */
589 if (errno == ERANGE) {
590 *result = -1;
592 return check_strtox_error(nptr, ep, endptr, *result == 0, errno);
596 * Convert string @nptr to an int64_t.
598 * Works like qemu_strtol(), except it stores INT64_MAX on overflow,
599 * and INT64_MIN on underflow.
601 int qemu_strtoi64(const char *nptr, const char **endptr, int base,
602 int64_t *result)
604 char *ep;
606 assert((unsigned) base <= 36 && base != 1);
607 if (!nptr) {
608 *result = 0;
609 if (endptr) {
610 *endptr = nptr;
612 return -EINVAL;
615 /* This assumes int64_t is long long TODO relax */
616 QEMU_BUILD_BUG_ON(sizeof(int64_t) != sizeof(long long));
617 errno = 0;
618 *result = strtoll(nptr, &ep, base);
619 return check_strtox_error(nptr, ep, endptr, *result == 0, errno);
623 * Convert string @nptr to an uint64_t.
625 * Works like qemu_strtoul(), except it stores UINT64_MAX on overflow.
626 * (If you want to prohibit negative numbers that wrap around to
627 * positive, use parse_uint()).
629 int qemu_strtou64(const char *nptr, const char **endptr, int base,
630 uint64_t *result)
632 char *ep;
634 assert((unsigned) base <= 36 && base != 1);
635 if (!nptr) {
636 *result = 0;
637 if (endptr) {
638 *endptr = nptr;
640 return -EINVAL;
643 /* This assumes uint64_t is unsigned long long TODO relax */
644 QEMU_BUILD_BUG_ON(sizeof(uint64_t) != sizeof(unsigned long long));
645 errno = 0;
646 *result = strtoull(nptr, &ep, base);
647 /* Windows returns 1 for negative out-of-range values. */
648 if (errno == ERANGE) {
649 *result = -1;
651 return check_strtox_error(nptr, ep, endptr, *result == 0, errno);
655 * Convert string @nptr to a double.
657 * This is a wrapper around strtod() that is harder to misuse.
658 * Semantics of @nptr and @endptr match strtod() with differences
659 * noted below.
661 * @nptr may be null, and no conversion is performed then.
663 * If no conversion is performed, store @nptr in *@endptr and return
664 * -EINVAL.
666 * If @endptr is null, and the string isn't fully converted, return
667 * -EINVAL. This is the case when the pointer that would be stored in
668 * a non-null @endptr points to a character other than '\0'.
670 * If the conversion overflows, store +/-HUGE_VAL in @result, depending
671 * on the sign, and return -ERANGE.
673 * If the conversion underflows, store +/-0.0 in @result, depending on the
674 * sign, and return -ERANGE.
676 * Else store the converted value in @result, and return zero.
678 int qemu_strtod(const char *nptr, const char **endptr, double *result)
680 char *ep;
682 if (!nptr) {
683 if (endptr) {
684 *endptr = nptr;
686 return -EINVAL;
689 errno = 0;
690 *result = strtod(nptr, &ep);
691 return check_strtox_error(nptr, ep, endptr, false, errno);
695 * Convert string @nptr to a finite double.
697 * Works like qemu_strtod(), except that "NaN" and "inf" are rejected
698 * with -EINVAL and no conversion is performed.
700 int qemu_strtod_finite(const char *nptr, const char **endptr, double *result)
702 double tmp;
703 int ret;
705 ret = qemu_strtod(nptr, endptr, &tmp);
706 if (!ret && !isfinite(tmp)) {
707 if (endptr) {
708 *endptr = nptr;
710 ret = -EINVAL;
713 if (ret != -EINVAL) {
714 *result = tmp;
716 return ret;
720 * Searches for the first occurrence of 'c' in 's', and returns a pointer
721 * to the trailing null byte if none was found.
723 #ifndef HAVE_STRCHRNUL
724 const char *qemu_strchrnul(const char *s, int c)
726 const char *e = strchr(s, c);
727 if (!e) {
728 e = s + strlen(s);
730 return e;
732 #endif
735 * parse_uint:
737 * @s: String to parse
738 * @endptr: Destination for pointer to first character not consumed
739 * @base: integer base, between 2 and 36 inclusive, or 0
740 * @value: Destination for parsed integer value
742 * Parse unsigned integer
744 * Parsed syntax is like strtoull()'s: arbitrary whitespace, a single optional
745 * '+' or '-', an optional "0x" if @base is 0 or 16, one or more digits.
747 * If @s is null, or @s doesn't start with an integer in the syntax
748 * above, set *@value to 0, *@endptr to @s, and return -EINVAL.
750 * Set *@endptr to point right beyond the parsed integer (even if the integer
751 * overflows or is negative, all digits will be parsed and *@endptr will
752 * point right beyond them). If @endptr is %NULL, any trailing character
753 * instead causes a result of -EINVAL with *@value of 0.
755 * If the integer is negative, set *@value to 0, and return -ERANGE.
756 * (If you want to allow negative numbers that wrap around within
757 * bounds, use qemu_strtou64()).
759 * If the integer overflows unsigned long long, set *@value to
760 * ULLONG_MAX, and return -ERANGE.
762 * Else, set *@value to the parsed integer, and return 0.
764 int parse_uint(const char *s, const char **endptr, int base, uint64_t *value)
766 int r = 0;
767 char *endp = (char *)s;
768 unsigned long long val = 0;
770 assert((unsigned) base <= 36 && base != 1);
771 if (!s) {
772 r = -EINVAL;
773 goto out;
776 errno = 0;
777 val = strtoull(s, &endp, base);
778 if (errno) {
779 r = -errno;
780 goto out;
783 if (endp == s) {
784 r = -EINVAL;
785 goto out;
788 /* make sure we reject negative numbers: */
789 while (qemu_isspace(*s)) {
790 s++;
792 if (*s == '-') {
793 val = 0;
794 r = -ERANGE;
795 goto out;
798 out:
799 *value = val;
800 if (endptr) {
801 *endptr = endp;
802 } else if (s && *endp) {
803 r = -EINVAL;
804 *value = 0;
806 return r;
810 * parse_uint_full:
812 * @s: String to parse
813 * @base: integer base, between 2 and 36 inclusive, or 0
814 * @value: Destination for parsed integer value
816 * Parse unsigned integer from entire string, rejecting any trailing slop.
818 * Shorthand for parse_uint(s, NULL, base, value).
820 int parse_uint_full(const char *s, int base, uint64_t *value)
822 return parse_uint(s, NULL, base, value);
825 int qemu_parse_fd(const char *param)
827 long fd;
828 char *endptr;
830 errno = 0;
831 fd = strtol(param, &endptr, 10);
832 if (param == endptr /* no conversion performed */ ||
833 errno != 0 /* not representable as long; possibly others */ ||
834 *endptr != '\0' /* final string not empty */ ||
835 fd < 0 /* invalid as file descriptor */ ||
836 fd > INT_MAX /* not representable as int */) {
837 return -1;
839 return fd;
843 * Implementation of ULEB128 (http://en.wikipedia.org/wiki/LEB128)
844 * Input is limited to 14-bit numbers
846 int uleb128_encode_small(uint8_t *out, uint32_t n)
848 g_assert(n <= 0x3fff);
849 if (n < 0x80) {
850 *out = n;
851 return 1;
852 } else {
853 *out++ = (n & 0x7f) | 0x80;
854 *out = n >> 7;
855 return 2;
859 int uleb128_decode_small(const uint8_t *in, uint32_t *n)
861 if (!(*in & 0x80)) {
862 *n = *in;
863 return 1;
864 } else {
865 *n = *in++ & 0x7f;
866 /* we exceed 14 bit number */
867 if (*in & 0x80) {
868 return -1;
870 *n |= *in << 7;
871 return 2;
876 * helper to parse debug environment variables
878 int parse_debug_env(const char *name, int max, int initial)
880 char *debug_env = getenv(name);
881 char *inv = NULL;
882 long debug;
884 if (!debug_env) {
885 return initial;
887 errno = 0;
888 debug = strtol(debug_env, &inv, 10);
889 if (inv == debug_env) {
890 return initial;
892 if (debug < 0 || debug > max || errno != 0) {
893 warn_report("%s not in [0, %d]", name, max);
894 return initial;
896 return debug;
899 const char *si_prefix(unsigned int exp10)
901 static const char *prefixes[] = {
902 "a", "f", "p", "n", "u", "m", "", "K", "M", "G", "T", "P", "E"
905 exp10 += 18;
906 assert(exp10 % 3 == 0 && exp10 / 3 < ARRAY_SIZE(prefixes));
907 return prefixes[exp10 / 3];
910 const char *iec_binary_prefix(unsigned int exp2)
912 static const char *prefixes[] = { "", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei" };
914 assert(exp2 % 10 == 0 && exp2 / 10 < ARRAY_SIZE(prefixes));
915 return prefixes[exp2 / 10];
919 * Return human readable string for size @val.
920 * @val can be anything that uint64_t allows (no more than "16 EiB").
921 * Use IEC binary units like KiB, MiB, and so forth.
922 * Caller is responsible for passing it to g_free().
924 char *size_to_str(uint64_t val)
926 uint64_t div;
927 int i;
930 * The exponent (returned in i) minus one gives us
931 * floor(log2(val * 1024 / 1000). The correction makes us
932 * switch to the higher power when the integer part is >= 1000.
933 * (see e41b509d68afb1f for more info)
935 frexp(val / (1000.0 / 1024.0), &i);
936 i = (i - 1) / 10 * 10;
937 div = 1ULL << i;
939 return g_strdup_printf("%0.3g %sB", (double)val / div, iec_binary_prefix(i));
942 char *freq_to_str(uint64_t freq_hz)
944 double freq = freq_hz;
945 size_t exp10 = 0;
947 while (freq >= 1000.0) {
948 freq /= 1000.0;
949 exp10 += 3;
952 return g_strdup_printf("%0.3g %sHz", freq, si_prefix(exp10));
955 int qemu_pstrcmp0(const char **str1, const char **str2)
957 return g_strcmp0(*str1, *str2);
960 static inline bool starts_with_prefix(const char *dir)
962 size_t prefix_len = strlen(CONFIG_PREFIX);
963 return !memcmp(dir, CONFIG_PREFIX, prefix_len) &&
964 (!dir[prefix_len] || G_IS_DIR_SEPARATOR(dir[prefix_len]));
967 /* Return the next path component in dir, and store its length in *p_len. */
968 static inline const char *next_component(const char *dir, int *p_len)
970 int len;
971 while ((*dir && G_IS_DIR_SEPARATOR(*dir)) ||
972 (*dir == '.' && (G_IS_DIR_SEPARATOR(dir[1]) || dir[1] == '\0'))) {
973 dir++;
975 len = 0;
976 while (dir[len] && !G_IS_DIR_SEPARATOR(dir[len])) {
977 len++;
979 *p_len = len;
980 return dir;
983 static const char *exec_dir;
985 void qemu_init_exec_dir(const char *argv0)
987 #ifdef G_OS_WIN32
988 char *p;
989 char buf[MAX_PATH];
990 DWORD len;
992 if (exec_dir) {
993 return;
996 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
997 if (len == 0) {
998 return;
1001 buf[len] = 0;
1002 p = buf + len - 1;
1003 while (p != buf && *p != '\\') {
1004 p--;
1006 *p = 0;
1007 if (access(buf, R_OK) == 0) {
1008 exec_dir = g_strdup(buf);
1009 } else {
1010 exec_dir = CONFIG_BINDIR;
1012 #else
1013 char *p = NULL;
1014 char buf[PATH_MAX];
1016 if (exec_dir) {
1017 return;
1020 #if defined(__linux__)
1022 int len;
1023 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
1024 if (len > 0) {
1025 buf[len] = 0;
1026 p = buf;
1029 #elif defined(__FreeBSD__) \
1030 || (defined(__NetBSD__) && defined(KERN_PROC_PATHNAME))
1032 #if defined(__FreeBSD__)
1033 static int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
1034 #else
1035 static int mib[4] = {CTL_KERN, KERN_PROC_ARGS, -1, KERN_PROC_PATHNAME};
1036 #endif
1037 size_t len = sizeof(buf) - 1;
1039 *buf = '\0';
1040 if (!sysctl(mib, ARRAY_SIZE(mib), buf, &len, NULL, 0) &&
1041 *buf) {
1042 buf[sizeof(buf) - 1] = '\0';
1043 p = buf;
1046 #elif defined(__APPLE__)
1048 char fpath[PATH_MAX];
1049 uint32_t len = sizeof(fpath);
1050 if (_NSGetExecutablePath(fpath, &len) == 0) {
1051 p = realpath(fpath, buf);
1052 if (!p) {
1053 return;
1057 #elif defined(__HAIKU__)
1059 image_info ii;
1060 int32_t c = 0;
1062 *buf = '\0';
1063 while (get_next_image_info(0, &c, &ii) == B_OK) {
1064 if (ii.type == B_APP_IMAGE) {
1065 strncpy(buf, ii.name, sizeof(buf));
1066 buf[sizeof(buf) - 1] = 0;
1067 p = buf;
1068 break;
1072 #endif
1073 /* If we don't have any way of figuring out the actual executable
1074 location then try argv[0]. */
1075 if (!p && argv0) {
1076 p = realpath(argv0, buf);
1078 if (p) {
1079 exec_dir = g_path_get_dirname(p);
1080 } else {
1081 exec_dir = CONFIG_BINDIR;
1083 #endif
1086 const char *qemu_get_exec_dir(void)
1088 return exec_dir;
1091 char *get_relocated_path(const char *dir)
1093 size_t prefix_len = strlen(CONFIG_PREFIX);
1094 const char *bindir = CONFIG_BINDIR;
1095 const char *exec_dir = qemu_get_exec_dir();
1096 GString *result;
1097 int len_dir, len_bindir;
1099 /* Fail if qemu_init_exec_dir was not called. */
1100 assert(exec_dir[0]);
1102 result = g_string_new(exec_dir);
1103 g_string_append(result, "/qemu-bundle");
1104 if (access(result->str, R_OK) == 0) {
1105 #ifdef G_OS_WIN32
1106 size_t size = mbsrtowcs(NULL, &dir, 0, &(mbstate_t){0}) + 1;
1107 PWSTR wdir = g_new(WCHAR, size);
1108 mbsrtowcs(wdir, &dir, size, &(mbstate_t){0});
1110 PCWSTR wdir_skipped_root;
1111 PathCchSkipRoot(wdir, &wdir_skipped_root);
1113 size = wcsrtombs(NULL, &wdir_skipped_root, 0, &(mbstate_t){0});
1114 char *cursor = result->str + result->len;
1115 g_string_set_size(result, result->len + size);
1116 wcsrtombs(cursor, &wdir_skipped_root, size + 1, &(mbstate_t){0});
1117 g_free(wdir);
1118 #else
1119 g_string_append(result, dir);
1120 #endif
1121 } else if (!starts_with_prefix(dir) || !starts_with_prefix(bindir)) {
1122 g_string_assign(result, dir);
1123 } else {
1124 g_string_assign(result, exec_dir);
1126 /* Advance over common components. */
1127 len_dir = len_bindir = prefix_len;
1128 do {
1129 dir += len_dir;
1130 bindir += len_bindir;
1131 dir = next_component(dir, &len_dir);
1132 bindir = next_component(bindir, &len_bindir);
1133 } while (len_dir && len_dir == len_bindir && !memcmp(dir, bindir, len_dir));
1135 /* Ascend from bindir to the common prefix with dir. */
1136 while (len_bindir) {
1137 bindir += len_bindir;
1138 g_string_append(result, "/..");
1139 bindir = next_component(bindir, &len_bindir);
1142 if (*dir) {
1143 assert(G_IS_DIR_SEPARATOR(dir[-1]));
1144 g_string_append(result, dir - 1);
1148 return g_string_free(result, false);