vhost-user: more master/slave things
[qemu.git] / util / cutils.c
blobb2777210e7daa99c4e6dcff04d0c2405c364cca0
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 #include "qemu/ctype.h"
30 #include "qemu/cutils.h"
31 #include "qemu/error-report.h"
33 void strpadcpy(char *buf, int buf_size, const char *str, char pad)
35 int len = qemu_strnlen(str, buf_size);
36 memcpy(buf, str, len);
37 memset(buf + len, pad, buf_size - len);
40 void pstrcpy(char *buf, int buf_size, const char *str)
42 int c;
43 char *q = buf;
45 if (buf_size <= 0)
46 return;
48 for(;;) {
49 c = *str++;
50 if (c == 0 || q >= buf + buf_size - 1)
51 break;
52 *q++ = c;
54 *q = '\0';
57 /* strcat and truncate. */
58 char *pstrcat(char *buf, int buf_size, const char *s)
60 int len;
61 len = strlen(buf);
62 if (len < buf_size)
63 pstrcpy(buf + len, buf_size - len, s);
64 return buf;
67 int strstart(const char *str, const char *val, const char **ptr)
69 const char *p, *q;
70 p = str;
71 q = val;
72 while (*q != '\0') {
73 if (*p != *q)
74 return 0;
75 p++;
76 q++;
78 if (ptr)
79 *ptr = p;
80 return 1;
83 int stristart(const char *str, const char *val, const char **ptr)
85 const char *p, *q;
86 p = str;
87 q = val;
88 while (*q != '\0') {
89 if (qemu_toupper(*p) != qemu_toupper(*q))
90 return 0;
91 p++;
92 q++;
94 if (ptr)
95 *ptr = p;
96 return 1;
99 /* XXX: use host strnlen if available ? */
100 int qemu_strnlen(const char *s, int max_len)
102 int i;
104 for(i = 0; i < max_len; i++) {
105 if (s[i] == '\0') {
106 break;
109 return i;
112 char *qemu_strsep(char **input, const char *delim)
114 char *result = *input;
115 if (result != NULL) {
116 char *p;
118 for (p = result; *p != '\0'; p++) {
119 if (strchr(delim, *p)) {
120 break;
123 if (*p == '\0') {
124 *input = NULL;
125 } else {
126 *p = '\0';
127 *input = p + 1;
130 return result;
133 time_t mktimegm(struct tm *tm)
135 time_t t;
136 int y = tm->tm_year + 1900, m = tm->tm_mon + 1, d = tm->tm_mday;
137 if (m < 3) {
138 m += 12;
139 y--;
141 t = 86400ULL * (d + (153 * m - 457) / 5 + 365 * y + y / 4 - y / 100 +
142 y / 400 - 719469);
143 t += 3600 * tm->tm_hour + 60 * tm->tm_min + tm->tm_sec;
144 return t;
147 static int64_t suffix_mul(char suffix, int64_t unit)
149 switch (qemu_toupper(suffix)) {
150 case 'B':
151 return 1;
152 case 'K':
153 return unit;
154 case 'M':
155 return unit * unit;
156 case 'G':
157 return unit * unit * unit;
158 case 'T':
159 return unit * unit * unit * unit;
160 case 'P':
161 return unit * unit * unit * unit * unit;
162 case 'E':
163 return unit * unit * unit * unit * unit * unit;
165 return -1;
169 * Convert size string to bytes.
171 * The size parsing supports the following syntaxes
172 * - 12345 - decimal, scale determined by @default_suffix and @unit
173 * - 12345{bBkKmMgGtTpPeE} - decimal, scale determined by suffix and @unit
174 * - 12345.678{kKmMgGtTpPeE} - decimal, scale determined by suffix, and
175 * fractional portion is truncated to byte
176 * - 0x7fEE - hexadecimal, unit determined by @default_suffix
178 * The following cause a deprecation warning, and may be removed in the future
179 * - 0xabc{kKmMgGtTpP} - hex with scaling suffix
181 * The following are intentionally not supported
182 * - octal, such as 08
183 * - fractional hex, such as 0x1.8
184 * - floating point exponents, such as 1e3
186 * The end pointer will be returned in *end, if not NULL. If there is
187 * no fraction, the input can be decimal or hexadecimal; if there is a
188 * fraction, then the input must be decimal and there must be a suffix
189 * (possibly by @default_suffix) larger than Byte, and the fractional
190 * portion may suffer from precision loss or rounding. The input must
191 * be positive.
193 * Return -ERANGE on overflow (with *@end advanced), and -EINVAL on
194 * other error (with *@end left unchanged).
196 static int do_strtosz(const char *nptr, const char **end,
197 const char default_suffix, int64_t unit,
198 uint64_t *result)
200 int retval;
201 const char *endptr, *f;
202 unsigned char c;
203 bool hex = false;
204 uint64_t val, valf = 0;
205 int64_t mul;
207 /* Parse integral portion as decimal. */
208 retval = qemu_strtou64(nptr, &endptr, 10, &val);
209 if (retval) {
210 goto out;
212 if (memchr(nptr, '-', endptr - nptr) != NULL) {
213 endptr = nptr;
214 retval = -EINVAL;
215 goto out;
217 if (val == 0 && (*endptr == 'x' || *endptr == 'X')) {
218 /* Input looks like hex, reparse, and insist on no fraction. */
219 retval = qemu_strtou64(nptr, &endptr, 16, &val);
220 if (retval) {
221 goto out;
223 if (*endptr == '.') {
224 endptr = nptr;
225 retval = -EINVAL;
226 goto out;
228 hex = true;
229 } else if (*endptr == '.') {
231 * Input looks like a fraction. Make sure even 1.k works
232 * without fractional digits. If we see an exponent, treat
233 * the entire input as invalid instead.
235 double fraction;
237 f = endptr;
238 retval = qemu_strtod_finite(f, &endptr, &fraction);
239 if (retval) {
240 endptr++;
241 } else if (memchr(f, 'e', endptr - f) || memchr(f, 'E', endptr - f)) {
242 endptr = nptr;
243 retval = -EINVAL;
244 goto out;
245 } else {
246 /* Extract into a 64-bit fixed-point fraction. */
247 valf = (uint64_t)(fraction * 0x1p64);
250 c = *endptr;
251 mul = suffix_mul(c, unit);
252 if (mul > 0) {
253 if (hex) {
254 warn_report("Using a multiplier suffix on hex numbers "
255 "is deprecated: %s", nptr);
257 endptr++;
258 } else {
259 mul = suffix_mul(default_suffix, unit);
260 assert(mul > 0);
262 if (mul == 1) {
263 /* When a fraction is present, a scale is required. */
264 if (valf != 0) {
265 endptr = nptr;
266 retval = -EINVAL;
267 goto out;
269 } else {
270 uint64_t valh, tmp;
272 /* Compute exact result: 64.64 x 64.0 -> 128.64 fixed point */
273 mulu64(&val, &valh, val, mul);
274 mulu64(&valf, &tmp, valf, mul);
275 val += tmp;
276 valh += val < tmp;
278 /* Round 0.5 upward. */
279 tmp = valf >> 63;
280 val += tmp;
281 valh += val < tmp;
283 /* Report overflow. */
284 if (valh != 0) {
285 retval = -ERANGE;
286 goto out;
290 retval = 0;
292 out:
293 if (end) {
294 *end = endptr;
295 } else if (*endptr) {
296 retval = -EINVAL;
298 if (retval == 0) {
299 *result = val;
302 return retval;
305 int qemu_strtosz(const char *nptr, const char **end, uint64_t *result)
307 return do_strtosz(nptr, end, 'B', 1024, result);
310 int qemu_strtosz_MiB(const char *nptr, const char **end, uint64_t *result)
312 return do_strtosz(nptr, end, 'M', 1024, result);
315 int qemu_strtosz_metric(const char *nptr, const char **end, uint64_t *result)
317 return do_strtosz(nptr, end, 'B', 1000, result);
321 * Helper function for error checking after strtol() and the like
323 static int check_strtox_error(const char *nptr, char *ep,
324 const char **endptr, bool check_zero,
325 int libc_errno)
327 assert(ep >= nptr);
329 /* Windows has a bug in that it fails to parse 0 from "0x" in base 16 */
330 if (check_zero && ep == nptr && libc_errno == 0) {
331 char *tmp;
333 errno = 0;
334 if (strtol(nptr, &tmp, 10) == 0 && errno == 0 &&
335 (*tmp == 'x' || *tmp == 'X')) {
336 ep = tmp;
340 if (endptr) {
341 *endptr = ep;
344 /* Turn "no conversion" into an error */
345 if (libc_errno == 0 && ep == nptr) {
346 return -EINVAL;
349 /* Fail when we're expected to consume the string, but didn't */
350 if (!endptr && *ep) {
351 return -EINVAL;
354 return -libc_errno;
358 * Convert string @nptr to an integer, and store it in @result.
360 * This is a wrapper around strtol() that is harder to misuse.
361 * Semantics of @nptr, @endptr, @base match strtol() with differences
362 * noted below.
364 * @nptr may be null, and no conversion is performed then.
366 * If no conversion is performed, store @nptr in *@endptr and return
367 * -EINVAL.
369 * If @endptr is null, and the string isn't fully converted, return
370 * -EINVAL. This is the case when the pointer that would be stored in
371 * a non-null @endptr points to a character other than '\0'.
373 * If the conversion overflows @result, store INT_MAX in @result,
374 * and return -ERANGE.
376 * If the conversion underflows @result, store INT_MIN in @result,
377 * and return -ERANGE.
379 * Else store the converted value in @result, and return zero.
381 int qemu_strtoi(const char *nptr, const char **endptr, int base,
382 int *result)
384 char *ep;
385 long long lresult;
387 assert((unsigned) base <= 36 && base != 1);
388 if (!nptr) {
389 if (endptr) {
390 *endptr = nptr;
392 return -EINVAL;
395 errno = 0;
396 lresult = strtoll(nptr, &ep, base);
397 if (lresult < INT_MIN) {
398 *result = INT_MIN;
399 errno = ERANGE;
400 } else if (lresult > INT_MAX) {
401 *result = INT_MAX;
402 errno = ERANGE;
403 } else {
404 *result = lresult;
406 return check_strtox_error(nptr, ep, endptr, lresult == 0, errno);
410 * Convert string @nptr to an unsigned integer, and store it in @result.
412 * This is a wrapper around strtoul() that is harder to misuse.
413 * Semantics of @nptr, @endptr, @base match strtoul() with differences
414 * noted below.
416 * @nptr may be null, and no conversion is performed then.
418 * If no conversion is performed, store @nptr in *@endptr and return
419 * -EINVAL.
421 * If @endptr is null, and the string isn't fully converted, return
422 * -EINVAL. This is the case when the pointer that would be stored in
423 * a non-null @endptr points to a character other than '\0'.
425 * If the conversion overflows @result, store UINT_MAX in @result,
426 * and return -ERANGE.
428 * Else store the converted value in @result, and return zero.
430 * Note that a number with a leading minus sign gets converted without
431 * the minus sign, checked for overflow (see above), then negated (in
432 * @result's type). This is exactly how strtoul() works.
434 int qemu_strtoui(const char *nptr, const char **endptr, int base,
435 unsigned int *result)
437 char *ep;
438 long long lresult;
440 assert((unsigned) base <= 36 && base != 1);
441 if (!nptr) {
442 if (endptr) {
443 *endptr = nptr;
445 return -EINVAL;
448 errno = 0;
449 lresult = strtoull(nptr, &ep, base);
451 /* Windows returns 1 for negative out-of-range values. */
452 if (errno == ERANGE) {
453 *result = -1;
454 } else {
455 if (lresult > UINT_MAX) {
456 *result = UINT_MAX;
457 errno = ERANGE;
458 } else if (lresult < INT_MIN) {
459 *result = UINT_MAX;
460 errno = ERANGE;
461 } else {
462 *result = lresult;
465 return check_strtox_error(nptr, ep, endptr, lresult == 0, errno);
469 * Convert string @nptr to a long integer, and store it in @result.
471 * This is a wrapper around strtol() that is harder to misuse.
472 * Semantics of @nptr, @endptr, @base match strtol() with differences
473 * noted below.
475 * @nptr may be null, and no conversion is performed then.
477 * If no conversion is performed, store @nptr in *@endptr and return
478 * -EINVAL.
480 * If @endptr is null, and the string isn't fully converted, return
481 * -EINVAL. This is the case when the pointer that would be stored in
482 * a non-null @endptr points to a character other than '\0'.
484 * If the conversion overflows @result, store LONG_MAX in @result,
485 * and return -ERANGE.
487 * If the conversion underflows @result, store LONG_MIN in @result,
488 * and return -ERANGE.
490 * Else store the converted value in @result, and return zero.
492 int qemu_strtol(const char *nptr, const char **endptr, int base,
493 long *result)
495 char *ep;
497 assert((unsigned) base <= 36 && base != 1);
498 if (!nptr) {
499 if (endptr) {
500 *endptr = nptr;
502 return -EINVAL;
505 errno = 0;
506 *result = strtol(nptr, &ep, base);
507 return check_strtox_error(nptr, ep, endptr, *result == 0, errno);
511 * Convert string @nptr to an unsigned long, and store it in @result.
513 * This is a wrapper around strtoul() that is harder to misuse.
514 * Semantics of @nptr, @endptr, @base match strtoul() with differences
515 * noted below.
517 * @nptr may be null, and no conversion is performed then.
519 * If no conversion is performed, store @nptr in *@endptr and return
520 * -EINVAL.
522 * If @endptr is null, and the string isn't fully converted, return
523 * -EINVAL. This is the case when the pointer that would be stored in
524 * a non-null @endptr points to a character other than '\0'.
526 * If the conversion overflows @result, store ULONG_MAX in @result,
527 * and return -ERANGE.
529 * Else store the converted value in @result, and return zero.
531 * Note that a number with a leading minus sign gets converted without
532 * the minus sign, checked for overflow (see above), then negated (in
533 * @result's type). This is exactly how strtoul() works.
535 int qemu_strtoul(const char *nptr, const char **endptr, int base,
536 unsigned long *result)
538 char *ep;
540 assert((unsigned) base <= 36 && base != 1);
541 if (!nptr) {
542 if (endptr) {
543 *endptr = nptr;
545 return -EINVAL;
548 errno = 0;
549 *result = strtoul(nptr, &ep, base);
550 /* Windows returns 1 for negative out-of-range values. */
551 if (errno == ERANGE) {
552 *result = -1;
554 return check_strtox_error(nptr, ep, endptr, *result == 0, errno);
558 * Convert string @nptr to an int64_t.
560 * Works like qemu_strtol(), except it stores INT64_MAX on overflow,
561 * and INT64_MIN on underflow.
563 int qemu_strtoi64(const char *nptr, const char **endptr, int base,
564 int64_t *result)
566 char *ep;
568 assert((unsigned) base <= 36 && base != 1);
569 if (!nptr) {
570 if (endptr) {
571 *endptr = nptr;
573 return -EINVAL;
576 /* This assumes int64_t is long long TODO relax */
577 QEMU_BUILD_BUG_ON(sizeof(int64_t) != sizeof(long long));
578 errno = 0;
579 *result = strtoll(nptr, &ep, base);
580 return check_strtox_error(nptr, ep, endptr, *result == 0, errno);
584 * Convert string @nptr to an uint64_t.
586 * Works like qemu_strtoul(), except it stores UINT64_MAX on overflow.
588 int qemu_strtou64(const char *nptr, const char **endptr, int base,
589 uint64_t *result)
591 char *ep;
593 assert((unsigned) base <= 36 && base != 1);
594 if (!nptr) {
595 if (endptr) {
596 *endptr = nptr;
598 return -EINVAL;
601 /* This assumes uint64_t is unsigned long long TODO relax */
602 QEMU_BUILD_BUG_ON(sizeof(uint64_t) != sizeof(unsigned long long));
603 errno = 0;
604 *result = strtoull(nptr, &ep, base);
605 /* Windows returns 1 for negative out-of-range values. */
606 if (errno == ERANGE) {
607 *result = -1;
609 return check_strtox_error(nptr, ep, endptr, *result == 0, errno);
613 * Convert string @nptr to a double.
615 * This is a wrapper around strtod() that is harder to misuse.
616 * Semantics of @nptr and @endptr match strtod() with differences
617 * noted below.
619 * @nptr may be null, and no conversion is performed then.
621 * If no conversion is performed, store @nptr in *@endptr and return
622 * -EINVAL.
624 * If @endptr is null, and the string isn't fully converted, return
625 * -EINVAL. This is the case when the pointer that would be stored in
626 * a non-null @endptr points to a character other than '\0'.
628 * If the conversion overflows, store +/-HUGE_VAL in @result, depending
629 * on the sign, and return -ERANGE.
631 * If the conversion underflows, store +/-0.0 in @result, depending on the
632 * sign, and return -ERANGE.
634 * Else store the converted value in @result, and return zero.
636 int qemu_strtod(const char *nptr, const char **endptr, double *result)
638 char *ep;
640 if (!nptr) {
641 if (endptr) {
642 *endptr = nptr;
644 return -EINVAL;
647 errno = 0;
648 *result = strtod(nptr, &ep);
649 return check_strtox_error(nptr, ep, endptr, false, errno);
653 * Convert string @nptr to a finite double.
655 * Works like qemu_strtod(), except that "NaN" and "inf" are rejected
656 * with -EINVAL and no conversion is performed.
658 int qemu_strtod_finite(const char *nptr, const char **endptr, double *result)
660 double tmp;
661 int ret;
663 ret = qemu_strtod(nptr, endptr, &tmp);
664 if (!ret && !isfinite(tmp)) {
665 if (endptr) {
666 *endptr = nptr;
668 ret = -EINVAL;
671 if (ret != -EINVAL) {
672 *result = tmp;
674 return ret;
678 * Searches for the first occurrence of 'c' in 's', and returns a pointer
679 * to the trailing null byte if none was found.
681 #ifndef HAVE_STRCHRNUL
682 const char *qemu_strchrnul(const char *s, int c)
684 const char *e = strchr(s, c);
685 if (!e) {
686 e = s + strlen(s);
688 return e;
690 #endif
693 * parse_uint:
695 * @s: String to parse
696 * @value: Destination for parsed integer value
697 * @endptr: Destination for pointer to first character not consumed
698 * @base: integer base, between 2 and 36 inclusive, or 0
700 * Parse unsigned integer
702 * Parsed syntax is like strtoull()'s: arbitrary whitespace, a single optional
703 * '+' or '-', an optional "0x" if @base is 0 or 16, one or more digits.
705 * If @s is null, or @base is invalid, or @s doesn't start with an
706 * integer in the syntax above, set *@value to 0, *@endptr to @s, and
707 * return -EINVAL.
709 * Set *@endptr to point right beyond the parsed integer (even if the integer
710 * overflows or is negative, all digits will be parsed and *@endptr will
711 * point right beyond them).
713 * If the integer is negative, set *@value to 0, and return -ERANGE.
715 * If the integer overflows unsigned long long, set *@value to
716 * ULLONG_MAX, and return -ERANGE.
718 * Else, set *@value to the parsed integer, and return 0.
720 int parse_uint(const char *s, unsigned long long *value, char **endptr,
721 int base)
723 int r = 0;
724 char *endp = (char *)s;
725 unsigned long long val = 0;
727 assert((unsigned) base <= 36 && base != 1);
728 if (!s) {
729 r = -EINVAL;
730 goto out;
733 errno = 0;
734 val = strtoull(s, &endp, base);
735 if (errno) {
736 r = -errno;
737 goto out;
740 if (endp == s) {
741 r = -EINVAL;
742 goto out;
745 /* make sure we reject negative numbers: */
746 while (qemu_isspace(*s)) {
747 s++;
749 if (*s == '-') {
750 val = 0;
751 r = -ERANGE;
752 goto out;
755 out:
756 *value = val;
757 *endptr = endp;
758 return r;
762 * parse_uint_full:
764 * @s: String to parse
765 * @value: Destination for parsed integer value
766 * @base: integer base, between 2 and 36 inclusive, or 0
768 * Parse unsigned integer from entire string
770 * Have the same behavior of parse_uint(), but with an additional check
771 * for additional data after the parsed number. If extra characters are present
772 * after the parsed number, the function will return -EINVAL, and *@v will
773 * be set to 0.
775 int parse_uint_full(const char *s, unsigned long long *value, int base)
777 char *endp;
778 int r;
780 r = parse_uint(s, value, &endp, base);
781 if (r < 0) {
782 return r;
784 if (*endp) {
785 *value = 0;
786 return -EINVAL;
789 return 0;
792 int qemu_parse_fd(const char *param)
794 long fd;
795 char *endptr;
797 errno = 0;
798 fd = strtol(param, &endptr, 10);
799 if (param == endptr /* no conversion performed */ ||
800 errno != 0 /* not representable as long; possibly others */ ||
801 *endptr != '\0' /* final string not empty */ ||
802 fd < 0 /* invalid as file descriptor */ ||
803 fd > INT_MAX /* not representable as int */) {
804 return -1;
806 return fd;
810 * Implementation of ULEB128 (http://en.wikipedia.org/wiki/LEB128)
811 * Input is limited to 14-bit numbers
813 int uleb128_encode_small(uint8_t *out, uint32_t n)
815 g_assert(n <= 0x3fff);
816 if (n < 0x80) {
817 *out = n;
818 return 1;
819 } else {
820 *out++ = (n & 0x7f) | 0x80;
821 *out = n >> 7;
822 return 2;
826 int uleb128_decode_small(const uint8_t *in, uint32_t *n)
828 if (!(*in & 0x80)) {
829 *n = *in;
830 return 1;
831 } else {
832 *n = *in++ & 0x7f;
833 /* we exceed 14 bit number */
834 if (*in & 0x80) {
835 return -1;
837 *n |= *in << 7;
838 return 2;
843 * helper to parse debug environment variables
845 int parse_debug_env(const char *name, int max, int initial)
847 char *debug_env = getenv(name);
848 char *inv = NULL;
849 long debug;
851 if (!debug_env) {
852 return initial;
854 errno = 0;
855 debug = strtol(debug_env, &inv, 10);
856 if (inv == debug_env) {
857 return initial;
859 if (debug < 0 || debug > max || errno != 0) {
860 warn_report("%s not in [0, %d]", name, max);
861 return initial;
863 return debug;
867 * Return human readable string for size @val.
868 * @val can be anything that uint64_t allows (no more than "16 EiB").
869 * Use IEC binary units like KiB, MiB, and so forth.
870 * Caller is responsible for passing it to g_free().
872 char *size_to_str(uint64_t val)
874 static const char *suffixes[] = { "", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei" };
875 uint64_t div;
876 int i;
879 * The exponent (returned in i) minus one gives us
880 * floor(log2(val * 1024 / 1000). The correction makes us
881 * switch to the higher power when the integer part is >= 1000.
882 * (see e41b509d68afb1f for more info)
884 frexp(val / (1000.0 / 1024.0), &i);
885 i = (i - 1) / 10;
886 div = 1ULL << (i * 10);
888 return g_strdup_printf("%0.3g %sB", (double)val / div, suffixes[i]);
891 char *freq_to_str(uint64_t freq_hz)
893 static const char *const suffixes[] = { "", "K", "M", "G", "T", "P", "E" };
894 double freq = freq_hz;
895 size_t idx = 0;
897 while (freq >= 1000.0) {
898 freq /= 1000.0;
899 idx++;
901 assert(idx < ARRAY_SIZE(suffixes));
903 return g_strdup_printf("%0.3g %sHz", freq, suffixes[idx]);
906 int qemu_pstrcmp0(const char **str1, const char **str2)
908 return g_strcmp0(*str1, *str2);
911 static inline bool starts_with_prefix(const char *dir)
913 size_t prefix_len = strlen(CONFIG_PREFIX);
914 return !memcmp(dir, CONFIG_PREFIX, prefix_len) &&
915 (!dir[prefix_len] || G_IS_DIR_SEPARATOR(dir[prefix_len]));
918 /* Return the next path component in dir, and store its length in *p_len. */
919 static inline const char *next_component(const char *dir, int *p_len)
921 int len;
922 while ((*dir && G_IS_DIR_SEPARATOR(*dir)) ||
923 (*dir == '.' && (G_IS_DIR_SEPARATOR(dir[1]) || dir[1] == '\0'))) {
924 dir++;
926 len = 0;
927 while (dir[len] && !G_IS_DIR_SEPARATOR(dir[len])) {
928 len++;
930 *p_len = len;
931 return dir;
934 char *get_relocated_path(const char *dir)
936 size_t prefix_len = strlen(CONFIG_PREFIX);
937 const char *bindir = CONFIG_BINDIR;
938 const char *exec_dir = qemu_get_exec_dir();
939 GString *result;
940 int len_dir, len_bindir;
942 /* Fail if qemu_init_exec_dir was not called. */
943 assert(exec_dir[0]);
944 if (!starts_with_prefix(dir) || !starts_with_prefix(bindir)) {
945 return g_strdup(dir);
948 result = g_string_new(exec_dir);
950 /* Advance over common components. */
951 len_dir = len_bindir = prefix_len;
952 do {
953 dir += len_dir;
954 bindir += len_bindir;
955 dir = next_component(dir, &len_dir);
956 bindir = next_component(bindir, &len_bindir);
957 } while (len_dir && len_dir == len_bindir && !memcmp(dir, bindir, len_dir));
959 /* Ascend from bindir to the common prefix with dir. */
960 while (len_bindir) {
961 bindir += len_bindir;
962 g_string_append(result, "/..");
963 bindir = next_component(bindir, &len_bindir);
966 if (*dir) {
967 assert(G_IS_DIR_SEPARATOR(dir[-1]));
968 g_string_append(result, dir - 1);
970 return g_string_free(result, false);