hw/cxl: Clean up includes
[qemu/armbru.git] / util / cutils.c
blob5887e7441405a5a4fedbf77ad084fe757ef48733
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 * - floating point exponents, such as 1e3
206 * The end pointer will be returned in *end, if not NULL. If there is
207 * no fraction, the input can be decimal or hexadecimal; if there is a
208 * fraction, then the input must be decimal and there must be a suffix
209 * (possibly by @default_suffix) larger than Byte, and the fractional
210 * portion may suffer from precision loss or rounding. The input must
211 * be positive.
213 * Return -ERANGE on overflow (with *@end advanced), and -EINVAL on
214 * other error (with *@end left unchanged).
216 static int do_strtosz(const char *nptr, const char **end,
217 const char default_suffix, int64_t unit,
218 uint64_t *result)
220 int retval;
221 const char *endptr, *f;
222 unsigned char c;
223 uint64_t val, valf = 0;
224 int64_t mul;
226 /* Parse integral portion as decimal. */
227 retval = qemu_strtou64(nptr, &endptr, 10, &val);
228 if (retval) {
229 goto out;
231 if (memchr(nptr, '-', endptr - nptr) != NULL) {
232 endptr = nptr;
233 retval = -EINVAL;
234 goto out;
236 if (val == 0 && (*endptr == 'x' || *endptr == 'X')) {
237 /* Input looks like hex; reparse, and insist on no fraction or suffix. */
238 retval = qemu_strtou64(nptr, &endptr, 16, &val);
239 if (retval) {
240 goto out;
242 if (*endptr == '.' || suffix_mul(*endptr, unit) > 0) {
243 endptr = nptr;
244 retval = -EINVAL;
245 goto out;
247 } else if (*endptr == '.') {
249 * Input looks like a fraction. Make sure even 1.k works
250 * without fractional digits. If we see an exponent, treat
251 * the entire input as invalid instead.
253 double fraction;
255 f = endptr;
256 retval = qemu_strtod_finite(f, &endptr, &fraction);
257 if (retval) {
258 endptr++;
259 } else if (memchr(f, 'e', endptr - f) || memchr(f, 'E', endptr - f)) {
260 endptr = nptr;
261 retval = -EINVAL;
262 goto out;
263 } else {
264 /* Extract into a 64-bit fixed-point fraction. */
265 valf = (uint64_t)(fraction * 0x1p64);
268 c = *endptr;
269 mul = suffix_mul(c, unit);
270 if (mul > 0) {
271 endptr++;
272 } else {
273 mul = suffix_mul(default_suffix, unit);
274 assert(mul > 0);
276 if (mul == 1) {
277 /* When a fraction is present, a scale is required. */
278 if (valf != 0) {
279 endptr = nptr;
280 retval = -EINVAL;
281 goto out;
283 } else {
284 uint64_t valh, tmp;
286 /* Compute exact result: 64.64 x 64.0 -> 128.64 fixed point */
287 mulu64(&val, &valh, val, mul);
288 mulu64(&valf, &tmp, valf, mul);
289 val += tmp;
290 valh += val < tmp;
292 /* Round 0.5 upward. */
293 tmp = valf >> 63;
294 val += tmp;
295 valh += val < tmp;
297 /* Report overflow. */
298 if (valh != 0) {
299 retval = -ERANGE;
300 goto out;
304 retval = 0;
306 out:
307 if (end) {
308 *end = endptr;
309 } else if (*endptr) {
310 retval = -EINVAL;
312 if (retval == 0) {
313 *result = val;
316 return retval;
319 int qemu_strtosz(const char *nptr, const char **end, uint64_t *result)
321 return do_strtosz(nptr, end, 'B', 1024, result);
324 int qemu_strtosz_MiB(const char *nptr, const char **end, uint64_t *result)
326 return do_strtosz(nptr, end, 'M', 1024, result);
329 int qemu_strtosz_metric(const char *nptr, const char **end, uint64_t *result)
331 return do_strtosz(nptr, end, 'B', 1000, result);
335 * Helper function for error checking after strtol() and the like
337 static int check_strtox_error(const char *nptr, char *ep,
338 const char **endptr, bool check_zero,
339 int libc_errno)
341 assert(ep >= nptr);
343 /* Windows has a bug in that it fails to parse 0 from "0x" in base 16 */
344 if (check_zero && ep == nptr && libc_errno == 0) {
345 char *tmp;
347 errno = 0;
348 if (strtol(nptr, &tmp, 10) == 0 && errno == 0 &&
349 (*tmp == 'x' || *tmp == 'X')) {
350 ep = tmp;
354 if (endptr) {
355 *endptr = ep;
358 /* Turn "no conversion" into an error */
359 if (libc_errno == 0 && ep == nptr) {
360 return -EINVAL;
363 /* Fail when we're expected to consume the string, but didn't */
364 if (!endptr && *ep) {
365 return -EINVAL;
368 return -libc_errno;
372 * Convert string @nptr to an integer, and store it in @result.
374 * This is a wrapper around strtol() that is harder to misuse.
375 * Semantics of @nptr, @endptr, @base match strtol() with differences
376 * noted below.
378 * @nptr may be null, and no conversion is performed then.
380 * If no conversion is performed, store @nptr in *@endptr and return
381 * -EINVAL.
383 * If @endptr is null, and the string isn't fully converted, return
384 * -EINVAL. This is the case when the pointer that would be stored in
385 * a non-null @endptr points to a character other than '\0'.
387 * If the conversion overflows @result, store INT_MAX in @result,
388 * and return -ERANGE.
390 * If the conversion underflows @result, store INT_MIN in @result,
391 * and return -ERANGE.
393 * Else store the converted value in @result, and return zero.
395 int qemu_strtoi(const char *nptr, const char **endptr, int base,
396 int *result)
398 char *ep;
399 long long lresult;
401 assert((unsigned) base <= 36 && base != 1);
402 if (!nptr) {
403 if (endptr) {
404 *endptr = nptr;
406 return -EINVAL;
409 errno = 0;
410 lresult = strtoll(nptr, &ep, base);
411 if (lresult < INT_MIN) {
412 *result = INT_MIN;
413 errno = ERANGE;
414 } else if (lresult > INT_MAX) {
415 *result = INT_MAX;
416 errno = ERANGE;
417 } else {
418 *result = lresult;
420 return check_strtox_error(nptr, ep, endptr, lresult == 0, errno);
424 * Convert string @nptr to an unsigned integer, and store it in @result.
426 * This is a wrapper around strtoul() that is harder to misuse.
427 * Semantics of @nptr, @endptr, @base match strtoul() with differences
428 * noted below.
430 * @nptr may be null, and no conversion is performed then.
432 * If no conversion is performed, store @nptr in *@endptr and return
433 * -EINVAL.
435 * If @endptr is null, and the string isn't fully converted, return
436 * -EINVAL. This is the case when the pointer that would be stored in
437 * a non-null @endptr points to a character other than '\0'.
439 * If the conversion overflows @result, store UINT_MAX in @result,
440 * and return -ERANGE.
442 * Else store the converted value in @result, and return zero.
444 * Note that a number with a leading minus sign gets converted without
445 * the minus sign, checked for overflow (see above), then negated (in
446 * @result's type). This is exactly how strtoul() works.
448 int qemu_strtoui(const char *nptr, const char **endptr, int base,
449 unsigned int *result)
451 char *ep;
452 long long lresult;
454 assert((unsigned) base <= 36 && base != 1);
455 if (!nptr) {
456 if (endptr) {
457 *endptr = nptr;
459 return -EINVAL;
462 errno = 0;
463 lresult = strtoull(nptr, &ep, base);
465 /* Windows returns 1 for negative out-of-range values. */
466 if (errno == ERANGE) {
467 *result = -1;
468 } else {
469 if (lresult > UINT_MAX) {
470 *result = UINT_MAX;
471 errno = ERANGE;
472 } else if (lresult < INT_MIN) {
473 *result = UINT_MAX;
474 errno = ERANGE;
475 } else {
476 *result = lresult;
479 return check_strtox_error(nptr, ep, endptr, lresult == 0, errno);
483 * Convert string @nptr to a long integer, and store it in @result.
485 * This is a wrapper around strtol() that is harder to misuse.
486 * Semantics of @nptr, @endptr, @base match strtol() with differences
487 * noted below.
489 * @nptr may be null, and no conversion is performed then.
491 * If no conversion is performed, store @nptr in *@endptr and return
492 * -EINVAL.
494 * If @endptr is null, and the string isn't fully converted, return
495 * -EINVAL. This is the case when the pointer that would be stored in
496 * a non-null @endptr points to a character other than '\0'.
498 * If the conversion overflows @result, store LONG_MAX in @result,
499 * and return -ERANGE.
501 * If the conversion underflows @result, store LONG_MIN in @result,
502 * and return -ERANGE.
504 * Else store the converted value in @result, and return zero.
506 int qemu_strtol(const char *nptr, const char **endptr, int base,
507 long *result)
509 char *ep;
511 assert((unsigned) base <= 36 && base != 1);
512 if (!nptr) {
513 if (endptr) {
514 *endptr = nptr;
516 return -EINVAL;
519 errno = 0;
520 *result = strtol(nptr, &ep, base);
521 return check_strtox_error(nptr, ep, endptr, *result == 0, errno);
525 * Convert string @nptr to an unsigned long, and store it in @result.
527 * This is a wrapper around strtoul() that is harder to misuse.
528 * Semantics of @nptr, @endptr, @base match strtoul() with differences
529 * noted below.
531 * @nptr may be null, and no conversion is performed then.
533 * If no conversion is performed, store @nptr in *@endptr and return
534 * -EINVAL.
536 * If @endptr is null, and the string isn't fully converted, return
537 * -EINVAL. This is the case when the pointer that would be stored in
538 * a non-null @endptr points to a character other than '\0'.
540 * If the conversion overflows @result, store ULONG_MAX in @result,
541 * and return -ERANGE.
543 * Else store the converted value in @result, and return zero.
545 * Note that a number with a leading minus sign gets converted without
546 * the minus sign, checked for overflow (see above), then negated (in
547 * @result's type). This is exactly how strtoul() works.
549 int qemu_strtoul(const char *nptr, const char **endptr, int base,
550 unsigned long *result)
552 char *ep;
554 assert((unsigned) base <= 36 && base != 1);
555 if (!nptr) {
556 if (endptr) {
557 *endptr = nptr;
559 return -EINVAL;
562 errno = 0;
563 *result = strtoul(nptr, &ep, base);
564 /* Windows returns 1 for negative out-of-range values. */
565 if (errno == ERANGE) {
566 *result = -1;
568 return check_strtox_error(nptr, ep, endptr, *result == 0, errno);
572 * Convert string @nptr to an int64_t.
574 * Works like qemu_strtol(), except it stores INT64_MAX on overflow,
575 * and INT64_MIN on underflow.
577 int qemu_strtoi64(const char *nptr, const char **endptr, int base,
578 int64_t *result)
580 char *ep;
582 assert((unsigned) base <= 36 && base != 1);
583 if (!nptr) {
584 if (endptr) {
585 *endptr = nptr;
587 return -EINVAL;
590 /* This assumes int64_t is long long TODO relax */
591 QEMU_BUILD_BUG_ON(sizeof(int64_t) != sizeof(long long));
592 errno = 0;
593 *result = strtoll(nptr, &ep, base);
594 return check_strtox_error(nptr, ep, endptr, *result == 0, errno);
598 * Convert string @nptr to an uint64_t.
600 * Works like qemu_strtoul(), except it stores UINT64_MAX on overflow.
602 int qemu_strtou64(const char *nptr, const char **endptr, int base,
603 uint64_t *result)
605 char *ep;
607 assert((unsigned) base <= 36 && base != 1);
608 if (!nptr) {
609 if (endptr) {
610 *endptr = nptr;
612 return -EINVAL;
615 /* This assumes uint64_t is unsigned long long TODO relax */
616 QEMU_BUILD_BUG_ON(sizeof(uint64_t) != sizeof(unsigned long long));
617 errno = 0;
618 *result = strtoull(nptr, &ep, base);
619 /* Windows returns 1 for negative out-of-range values. */
620 if (errno == ERANGE) {
621 *result = -1;
623 return check_strtox_error(nptr, ep, endptr, *result == 0, errno);
627 * Convert string @nptr to a double.
629 * This is a wrapper around strtod() that is harder to misuse.
630 * Semantics of @nptr and @endptr match strtod() with differences
631 * noted below.
633 * @nptr may be null, and no conversion is performed then.
635 * If no conversion is performed, store @nptr in *@endptr and return
636 * -EINVAL.
638 * If @endptr is null, and the string isn't fully converted, return
639 * -EINVAL. This is the case when the pointer that would be stored in
640 * a non-null @endptr points to a character other than '\0'.
642 * If the conversion overflows, store +/-HUGE_VAL in @result, depending
643 * on the sign, and return -ERANGE.
645 * If the conversion underflows, store +/-0.0 in @result, depending on the
646 * sign, and return -ERANGE.
648 * Else store the converted value in @result, and return zero.
650 int qemu_strtod(const char *nptr, const char **endptr, double *result)
652 char *ep;
654 if (!nptr) {
655 if (endptr) {
656 *endptr = nptr;
658 return -EINVAL;
661 errno = 0;
662 *result = strtod(nptr, &ep);
663 return check_strtox_error(nptr, ep, endptr, false, errno);
667 * Convert string @nptr to a finite double.
669 * Works like qemu_strtod(), except that "NaN" and "inf" are rejected
670 * with -EINVAL and no conversion is performed.
672 int qemu_strtod_finite(const char *nptr, const char **endptr, double *result)
674 double tmp;
675 int ret;
677 ret = qemu_strtod(nptr, endptr, &tmp);
678 if (!ret && !isfinite(tmp)) {
679 if (endptr) {
680 *endptr = nptr;
682 ret = -EINVAL;
685 if (ret != -EINVAL) {
686 *result = tmp;
688 return ret;
692 * Searches for the first occurrence of 'c' in 's', and returns a pointer
693 * to the trailing null byte if none was found.
695 #ifndef HAVE_STRCHRNUL
696 const char *qemu_strchrnul(const char *s, int c)
698 const char *e = strchr(s, c);
699 if (!e) {
700 e = s + strlen(s);
702 return e;
704 #endif
707 * parse_uint:
709 * @s: String to parse
710 * @value: Destination for parsed integer value
711 * @endptr: Destination for pointer to first character not consumed
712 * @base: integer base, between 2 and 36 inclusive, or 0
714 * Parse unsigned integer
716 * Parsed syntax is like strtoull()'s: arbitrary whitespace, a single optional
717 * '+' or '-', an optional "0x" if @base is 0 or 16, one or more digits.
719 * If @s is null, or @base is invalid, or @s doesn't start with an
720 * integer in the syntax above, set *@value to 0, *@endptr to @s, and
721 * return -EINVAL.
723 * Set *@endptr to point right beyond the parsed integer (even if the integer
724 * overflows or is negative, all digits will be parsed and *@endptr will
725 * point right beyond them).
727 * If the integer is negative, set *@value to 0, and return -ERANGE.
729 * If the integer overflows unsigned long long, set *@value to
730 * ULLONG_MAX, and return -ERANGE.
732 * Else, set *@value to the parsed integer, and return 0.
734 int parse_uint(const char *s, unsigned long long *value, char **endptr,
735 int base)
737 int r = 0;
738 char *endp = (char *)s;
739 unsigned long long val = 0;
741 assert((unsigned) base <= 36 && base != 1);
742 if (!s) {
743 r = -EINVAL;
744 goto out;
747 errno = 0;
748 val = strtoull(s, &endp, base);
749 if (errno) {
750 r = -errno;
751 goto out;
754 if (endp == s) {
755 r = -EINVAL;
756 goto out;
759 /* make sure we reject negative numbers: */
760 while (qemu_isspace(*s)) {
761 s++;
763 if (*s == '-') {
764 val = 0;
765 r = -ERANGE;
766 goto out;
769 out:
770 *value = val;
771 *endptr = endp;
772 return r;
776 * parse_uint_full:
778 * @s: String to parse
779 * @value: Destination for parsed integer value
780 * @base: integer base, between 2 and 36 inclusive, or 0
782 * Parse unsigned integer from entire string
784 * Have the same behavior of parse_uint(), but with an additional check
785 * for additional data after the parsed number. If extra characters are present
786 * after the parsed number, the function will return -EINVAL, and *@v will
787 * be set to 0.
789 int parse_uint_full(const char *s, unsigned long long *value, int base)
791 char *endp;
792 int r;
794 r = parse_uint(s, value, &endp, base);
795 if (r < 0) {
796 return r;
798 if (*endp) {
799 *value = 0;
800 return -EINVAL;
803 return 0;
806 int qemu_parse_fd(const char *param)
808 long fd;
809 char *endptr;
811 errno = 0;
812 fd = strtol(param, &endptr, 10);
813 if (param == endptr /* no conversion performed */ ||
814 errno != 0 /* not representable as long; possibly others */ ||
815 *endptr != '\0' /* final string not empty */ ||
816 fd < 0 /* invalid as file descriptor */ ||
817 fd > INT_MAX /* not representable as int */) {
818 return -1;
820 return fd;
824 * Implementation of ULEB128 (http://en.wikipedia.org/wiki/LEB128)
825 * Input is limited to 14-bit numbers
827 int uleb128_encode_small(uint8_t *out, uint32_t n)
829 g_assert(n <= 0x3fff);
830 if (n < 0x80) {
831 *out = n;
832 return 1;
833 } else {
834 *out++ = (n & 0x7f) | 0x80;
835 *out = n >> 7;
836 return 2;
840 int uleb128_decode_small(const uint8_t *in, uint32_t *n)
842 if (!(*in & 0x80)) {
843 *n = *in;
844 return 1;
845 } else {
846 *n = *in++ & 0x7f;
847 /* we exceed 14 bit number */
848 if (*in & 0x80) {
849 return -1;
851 *n |= *in << 7;
852 return 2;
857 * helper to parse debug environment variables
859 int parse_debug_env(const char *name, int max, int initial)
861 char *debug_env = getenv(name);
862 char *inv = NULL;
863 long debug;
865 if (!debug_env) {
866 return initial;
868 errno = 0;
869 debug = strtol(debug_env, &inv, 10);
870 if (inv == debug_env) {
871 return initial;
873 if (debug < 0 || debug > max || errno != 0) {
874 warn_report("%s not in [0, %d]", name, max);
875 return initial;
877 return debug;
880 const char *si_prefix(unsigned int exp10)
882 static const char *prefixes[] = {
883 "a", "f", "p", "n", "u", "m", "", "K", "M", "G", "T", "P", "E"
886 exp10 += 18;
887 assert(exp10 % 3 == 0 && exp10 / 3 < ARRAY_SIZE(prefixes));
888 return prefixes[exp10 / 3];
891 const char *iec_binary_prefix(unsigned int exp2)
893 static const char *prefixes[] = { "", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei" };
895 assert(exp2 % 10 == 0 && exp2 / 10 < ARRAY_SIZE(prefixes));
896 return prefixes[exp2 / 10];
900 * Return human readable string for size @val.
901 * @val can be anything that uint64_t allows (no more than "16 EiB").
902 * Use IEC binary units like KiB, MiB, and so forth.
903 * Caller is responsible for passing it to g_free().
905 char *size_to_str(uint64_t val)
907 uint64_t div;
908 int i;
911 * The exponent (returned in i) minus one gives us
912 * floor(log2(val * 1024 / 1000). The correction makes us
913 * switch to the higher power when the integer part is >= 1000.
914 * (see e41b509d68afb1f for more info)
916 frexp(val / (1000.0 / 1024.0), &i);
917 i = (i - 1) / 10 * 10;
918 div = 1ULL << i;
920 return g_strdup_printf("%0.3g %sB", (double)val / div, iec_binary_prefix(i));
923 char *freq_to_str(uint64_t freq_hz)
925 double freq = freq_hz;
926 size_t exp10 = 0;
928 while (freq >= 1000.0) {
929 freq /= 1000.0;
930 exp10 += 3;
933 return g_strdup_printf("%0.3g %sHz", freq, si_prefix(exp10));
936 int qemu_pstrcmp0(const char **str1, const char **str2)
938 return g_strcmp0(*str1, *str2);
941 static inline bool starts_with_prefix(const char *dir)
943 size_t prefix_len = strlen(CONFIG_PREFIX);
944 return !memcmp(dir, CONFIG_PREFIX, prefix_len) &&
945 (!dir[prefix_len] || G_IS_DIR_SEPARATOR(dir[prefix_len]));
948 /* Return the next path component in dir, and store its length in *p_len. */
949 static inline const char *next_component(const char *dir, int *p_len)
951 int len;
952 while ((*dir && G_IS_DIR_SEPARATOR(*dir)) ||
953 (*dir == '.' && (G_IS_DIR_SEPARATOR(dir[1]) || dir[1] == '\0'))) {
954 dir++;
956 len = 0;
957 while (dir[len] && !G_IS_DIR_SEPARATOR(dir[len])) {
958 len++;
960 *p_len = len;
961 return dir;
964 static const char *exec_dir;
966 void qemu_init_exec_dir(const char *argv0)
968 #ifdef G_OS_WIN32
969 char *p;
970 char buf[MAX_PATH];
971 DWORD len;
973 if (exec_dir) {
974 return;
977 len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
978 if (len == 0) {
979 return;
982 buf[len] = 0;
983 p = buf + len - 1;
984 while (p != buf && *p != '\\') {
985 p--;
987 *p = 0;
988 if (access(buf, R_OK) == 0) {
989 exec_dir = g_strdup(buf);
990 } else {
991 exec_dir = CONFIG_BINDIR;
993 #else
994 char *p = NULL;
995 char buf[PATH_MAX];
997 if (exec_dir) {
998 return;
1001 #if defined(__linux__)
1003 int len;
1004 len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
1005 if (len > 0) {
1006 buf[len] = 0;
1007 p = buf;
1010 #elif defined(__FreeBSD__) \
1011 || (defined(__NetBSD__) && defined(KERN_PROC_PATHNAME))
1013 #if defined(__FreeBSD__)
1014 static int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
1015 #else
1016 static int mib[4] = {CTL_KERN, KERN_PROC_ARGS, -1, KERN_PROC_PATHNAME};
1017 #endif
1018 size_t len = sizeof(buf) - 1;
1020 *buf = '\0';
1021 if (!sysctl(mib, ARRAY_SIZE(mib), buf, &len, NULL, 0) &&
1022 *buf) {
1023 buf[sizeof(buf) - 1] = '\0';
1024 p = buf;
1027 #elif defined(__APPLE__)
1029 char fpath[PATH_MAX];
1030 uint32_t len = sizeof(fpath);
1031 if (_NSGetExecutablePath(fpath, &len) == 0) {
1032 p = realpath(fpath, buf);
1033 if (!p) {
1034 return;
1038 #elif defined(__HAIKU__)
1040 image_info ii;
1041 int32_t c = 0;
1043 *buf = '\0';
1044 while (get_next_image_info(0, &c, &ii) == B_OK) {
1045 if (ii.type == B_APP_IMAGE) {
1046 strncpy(buf, ii.name, sizeof(buf));
1047 buf[sizeof(buf) - 1] = 0;
1048 p = buf;
1049 break;
1053 #endif
1054 /* If we don't have any way of figuring out the actual executable
1055 location then try argv[0]. */
1056 if (!p && argv0) {
1057 p = realpath(argv0, buf);
1059 if (p) {
1060 exec_dir = g_path_get_dirname(p);
1061 } else {
1062 exec_dir = CONFIG_BINDIR;
1064 #endif
1067 const char *qemu_get_exec_dir(void)
1069 return exec_dir;
1072 char *get_relocated_path(const char *dir)
1074 size_t prefix_len = strlen(CONFIG_PREFIX);
1075 const char *bindir = CONFIG_BINDIR;
1076 const char *exec_dir = qemu_get_exec_dir();
1077 GString *result;
1078 int len_dir, len_bindir;
1080 /* Fail if qemu_init_exec_dir was not called. */
1081 assert(exec_dir[0]);
1083 result = g_string_new(exec_dir);
1084 g_string_append(result, "/qemu-bundle");
1085 if (access(result->str, R_OK) == 0) {
1086 #ifdef G_OS_WIN32
1087 size_t size = mbsrtowcs(NULL, &dir, 0, &(mbstate_t){0}) + 1;
1088 PWSTR wdir = g_new(WCHAR, size);
1089 mbsrtowcs(wdir, &dir, size, &(mbstate_t){0});
1091 PCWSTR wdir_skipped_root;
1092 PathCchSkipRoot(wdir, &wdir_skipped_root);
1094 size = wcsrtombs(NULL, &wdir_skipped_root, 0, &(mbstate_t){0});
1095 char *cursor = result->str + result->len;
1096 g_string_set_size(result, result->len + size);
1097 wcsrtombs(cursor, &wdir_skipped_root, size + 1, &(mbstate_t){0});
1098 g_free(wdir);
1099 #else
1100 g_string_append(result, dir);
1101 #endif
1102 } else if (!starts_with_prefix(dir) || !starts_with_prefix(bindir)) {
1103 g_string_assign(result, dir);
1104 } else {
1105 g_string_assign(result, exec_dir);
1107 /* Advance over common components. */
1108 len_dir = len_bindir = prefix_len;
1109 do {
1110 dir += len_dir;
1111 bindir += len_bindir;
1112 dir = next_component(dir, &len_dir);
1113 bindir = next_component(bindir, &len_bindir);
1114 } while (len_dir && len_dir == len_bindir && !memcmp(dir, bindir, len_dir));
1116 /* Ascend from bindir to the common prefix with dir. */
1117 while (len_bindir) {
1118 bindir += len_bindir;
1119 g_string_append(result, "/..");
1120 bindir = next_component(bindir, &len_bindir);
1123 if (*dir) {
1124 assert(G_IS_DIR_SEPARATOR(dir[-1]));
1125 g_string_append(result, dir - 1);
1129 return g_string_free(result, false);