xref: /qemu/util/cutils.c (revision 1fbf2665)
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 
25 #include "qemu/osdep.h"
26 #include "qemu/host-utils.h"
27 #include <math.h>
28 
29 #include "qemu/ctype.h"
30 #include "qemu/cutils.h"
31 #include "qemu/error-report.h"
32 
33 void strpadcpy(char *buf, int buf_size, const char *str, char pad)
34 {
35     int len = qemu_strnlen(str, buf_size);
36     memcpy(buf, str, len);
37     memset(buf + len, pad, buf_size - len);
38 }
39 
40 void pstrcpy(char *buf, int buf_size, const char *str)
41 {
42     int c;
43     char *q = buf;
44 
45     if (buf_size <= 0)
46         return;
47 
48     for(;;) {
49         c = *str++;
50         if (c == 0 || q >= buf + buf_size - 1)
51             break;
52         *q++ = c;
53     }
54     *q = '\0';
55 }
56 
57 /* strcat and truncate. */
58 char *pstrcat(char *buf, int buf_size, const char *s)
59 {
60     int len;
61     len = strlen(buf);
62     if (len < buf_size)
63         pstrcpy(buf + len, buf_size - len, s);
64     return buf;
65 }
66 
67 int strstart(const char *str, const char *val, const char **ptr)
68 {
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++;
77     }
78     if (ptr)
79         *ptr = p;
80     return 1;
81 }
82 
83 int stristart(const char *str, const char *val, const char **ptr)
84 {
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++;
93     }
94     if (ptr)
95         *ptr = p;
96     return 1;
97 }
98 
99 /* XXX: use host strnlen if available ? */
100 int qemu_strnlen(const char *s, int max_len)
101 {
102     int i;
103 
104     for(i = 0; i < max_len; i++) {
105         if (s[i] == '\0') {
106             break;
107         }
108     }
109     return i;
110 }
111 
112 char *qemu_strsep(char **input, const char *delim)
113 {
114     char *result = *input;
115     if (result != NULL) {
116         char *p;
117 
118         for (p = result; *p != '\0'; p++) {
119             if (strchr(delim, *p)) {
120                 break;
121             }
122         }
123         if (*p == '\0') {
124             *input = NULL;
125         } else {
126             *p = '\0';
127             *input = p + 1;
128         }
129     }
130     return result;
131 }
132 
133 time_t mktimegm(struct tm *tm)
134 {
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--;
140     }
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;
145 }
146 
147 static int64_t suffix_mul(char suffix, int64_t unit)
148 {
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;
164     }
165     return -1;
166 }
167 
168 /*
169  * Convert size string to bytes.
170  *
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
177  *
178  * The following cause a deprecation warning, and may be removed in the future
179  * - 0xabc{kKmMgGtTpP} - hex with scaling suffix
180  *
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
185  *
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.
192  *
193  * Return -ERANGE on overflow (with *@end advanced), and -EINVAL on
194  * other error (with *@end left unchanged).
195  */
196 static int do_strtosz(const char *nptr, const char **end,
197                       const char default_suffix, int64_t unit,
198                       uint64_t *result)
199 {
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;
206 
207     /* Parse integral portion as decimal. */
208     retval = qemu_strtou64(nptr, &endptr, 10, &val);
209     if (retval) {
210         goto out;
211     }
212     if (memchr(nptr, '-', endptr - nptr) != NULL) {
213         endptr = nptr;
214         retval = -EINVAL;
215         goto out;
216     }
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;
222         }
223         if (*endptr == '.') {
224             endptr = nptr;
225             retval = -EINVAL;
226             goto out;
227         }
228         hex = true;
229     } else if (*endptr == '.') {
230         /*
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.
234          */
235         double fraction;
236 
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);
248         }
249     }
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);
256         }
257         endptr++;
258     } else {
259         mul = suffix_mul(default_suffix, unit);
260         assert(mul > 0);
261     }
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;
268         }
269     } else {
270         uint64_t valh, tmp;
271 
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;
277 
278         /* Round 0.5 upward. */
279         tmp = valf >> 63;
280         val += tmp;
281         valh += val < tmp;
282 
283         /* Report overflow. */
284         if (valh != 0) {
285             retval = -ERANGE;
286             goto out;
287         }
288     }
289 
290     retval = 0;
291 
292 out:
293     if (end) {
294         *end = endptr;
295     } else if (*endptr) {
296         retval = -EINVAL;
297     }
298     if (retval == 0) {
299         *result = val;
300     }
301 
302     return retval;
303 }
304 
305 int qemu_strtosz(const char *nptr, const char **end, uint64_t *result)
306 {
307     return do_strtosz(nptr, end, 'B', 1024, result);
308 }
309 
310 int qemu_strtosz_MiB(const char *nptr, const char **end, uint64_t *result)
311 {
312     return do_strtosz(nptr, end, 'M', 1024, result);
313 }
314 
315 int qemu_strtosz_metric(const char *nptr, const char **end, uint64_t *result)
316 {
317     return do_strtosz(nptr, end, 'B', 1000, result);
318 }
319 
320 /**
321  * Helper function for error checking after strtol() and the like
322  */
323 static int check_strtox_error(const char *nptr, char *ep,
324                               const char **endptr, bool check_zero,
325                               int libc_errno)
326 {
327     assert(ep >= nptr);
328 
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;
332 
333         errno = 0;
334         if (strtol(nptr, &tmp, 10) == 0 && errno == 0 &&
335             (*tmp == 'x' || *tmp == 'X')) {
336             ep = tmp;
337         }
338     }
339 
340     if (endptr) {
341         *endptr = ep;
342     }
343 
344     /* Turn "no conversion" into an error */
345     if (libc_errno == 0 && ep == nptr) {
346         return -EINVAL;
347     }
348 
349     /* Fail when we're expected to consume the string, but didn't */
350     if (!endptr && *ep) {
351         return -EINVAL;
352     }
353 
354     return -libc_errno;
355 }
356 
357 /**
358  * Convert string @nptr to an integer, and store it in @result.
359  *
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.
363  *
364  * @nptr may be null, and no conversion is performed then.
365  *
366  * If no conversion is performed, store @nptr in *@endptr and return
367  * -EINVAL.
368  *
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'.
372  *
373  * If the conversion overflows @result, store INT_MAX in @result,
374  * and return -ERANGE.
375  *
376  * If the conversion underflows @result, store INT_MIN in @result,
377  * and return -ERANGE.
378  *
379  * Else store the converted value in @result, and return zero.
380  */
381 int qemu_strtoi(const char *nptr, const char **endptr, int base,
382                 int *result)
383 {
384     char *ep;
385     long long lresult;
386 
387     assert((unsigned) base <= 36 && base != 1);
388     if (!nptr) {
389         if (endptr) {
390             *endptr = nptr;
391         }
392         return -EINVAL;
393     }
394 
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;
405     }
406     return check_strtox_error(nptr, ep, endptr, lresult == 0, errno);
407 }
408 
409 /**
410  * Convert string @nptr to an unsigned integer, and store it in @result.
411  *
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.
415  *
416  * @nptr may be null, and no conversion is performed then.
417  *
418  * If no conversion is performed, store @nptr in *@endptr and return
419  * -EINVAL.
420  *
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'.
424  *
425  * If the conversion overflows @result, store UINT_MAX in @result,
426  * and return -ERANGE.
427  *
428  * Else store the converted value in @result, and return zero.
429  *
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.
433  */
434 int qemu_strtoui(const char *nptr, const char **endptr, int base,
435                  unsigned int *result)
436 {
437     char *ep;
438     long long lresult;
439 
440     assert((unsigned) base <= 36 && base != 1);
441     if (!nptr) {
442         if (endptr) {
443             *endptr = nptr;
444         }
445         return -EINVAL;
446     }
447 
448     errno = 0;
449     lresult = strtoull(nptr, &ep, base);
450 
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;
463         }
464     }
465     return check_strtox_error(nptr, ep, endptr, lresult == 0, errno);
466 }
467 
468 /**
469  * Convert string @nptr to a long integer, and store it in @result.
470  *
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.
474  *
475  * @nptr may be null, and no conversion is performed then.
476  *
477  * If no conversion is performed, store @nptr in *@endptr and return
478  * -EINVAL.
479  *
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'.
483  *
484  * If the conversion overflows @result, store LONG_MAX in @result,
485  * and return -ERANGE.
486  *
487  * If the conversion underflows @result, store LONG_MIN in @result,
488  * and return -ERANGE.
489  *
490  * Else store the converted value in @result, and return zero.
491  */
492 int qemu_strtol(const char *nptr, const char **endptr, int base,
493                 long *result)
494 {
495     char *ep;
496 
497     assert((unsigned) base <= 36 && base != 1);
498     if (!nptr) {
499         if (endptr) {
500             *endptr = nptr;
501         }
502         return -EINVAL;
503     }
504 
505     errno = 0;
506     *result = strtol(nptr, &ep, base);
507     return check_strtox_error(nptr, ep, endptr, *result == 0, errno);
508 }
509 
510 /**
511  * Convert string @nptr to an unsigned long, and store it in @result.
512  *
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.
516  *
517  * @nptr may be null, and no conversion is performed then.
518  *
519  * If no conversion is performed, store @nptr in *@endptr and return
520  * -EINVAL.
521  *
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'.
525  *
526  * If the conversion overflows @result, store ULONG_MAX in @result,
527  * and return -ERANGE.
528  *
529  * Else store the converted value in @result, and return zero.
530  *
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.
534  */
535 int qemu_strtoul(const char *nptr, const char **endptr, int base,
536                  unsigned long *result)
537 {
538     char *ep;
539 
540     assert((unsigned) base <= 36 && base != 1);
541     if (!nptr) {
542         if (endptr) {
543             *endptr = nptr;
544         }
545         return -EINVAL;
546     }
547 
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;
553     }
554     return check_strtox_error(nptr, ep, endptr, *result == 0, errno);
555 }
556 
557 /**
558  * Convert string @nptr to an int64_t.
559  *
560  * Works like qemu_strtol(), except it stores INT64_MAX on overflow,
561  * and INT64_MIN on underflow.
562  */
563 int qemu_strtoi64(const char *nptr, const char **endptr, int base,
564                  int64_t *result)
565 {
566     char *ep;
567 
568     assert((unsigned) base <= 36 && base != 1);
569     if (!nptr) {
570         if (endptr) {
571             *endptr = nptr;
572         }
573         return -EINVAL;
574     }
575 
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);
581 }
582 
583 /**
584  * Convert string @nptr to an uint64_t.
585  *
586  * Works like qemu_strtoul(), except it stores UINT64_MAX on overflow.
587  */
588 int qemu_strtou64(const char *nptr, const char **endptr, int base,
589                   uint64_t *result)
590 {
591     char *ep;
592 
593     assert((unsigned) base <= 36 && base != 1);
594     if (!nptr) {
595         if (endptr) {
596             *endptr = nptr;
597         }
598         return -EINVAL;
599     }
600 
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;
608     }
609     return check_strtox_error(nptr, ep, endptr, *result == 0, errno);
610 }
611 
612 /**
613  * Convert string @nptr to a double.
614   *
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.
618  *
619  * @nptr may be null, and no conversion is performed then.
620  *
621  * If no conversion is performed, store @nptr in *@endptr and return
622  * -EINVAL.
623  *
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'.
627  *
628  * If the conversion overflows, store +/-HUGE_VAL in @result, depending
629  * on the sign, and return -ERANGE.
630  *
631  * If the conversion underflows, store +/-0.0 in @result, depending on the
632  * sign, and return -ERANGE.
633  *
634  * Else store the converted value in @result, and return zero.
635  */
636 int qemu_strtod(const char *nptr, const char **endptr, double *result)
637 {
638     char *ep;
639 
640     if (!nptr) {
641         if (endptr) {
642             *endptr = nptr;
643         }
644         return -EINVAL;
645     }
646 
647     errno = 0;
648     *result = strtod(nptr, &ep);
649     return check_strtox_error(nptr, ep, endptr, false, errno);
650 }
651 
652 /**
653  * Convert string @nptr to a finite double.
654  *
655  * Works like qemu_strtod(), except that "NaN" and "inf" are rejected
656  * with -EINVAL and no conversion is performed.
657  */
658 int qemu_strtod_finite(const char *nptr, const char **endptr, double *result)
659 {
660     double tmp;
661     int ret;
662 
663     ret = qemu_strtod(nptr, endptr, &tmp);
664     if (!ret && !isfinite(tmp)) {
665         if (endptr) {
666             *endptr = nptr;
667         }
668         ret = -EINVAL;
669     }
670 
671     if (ret != -EINVAL) {
672         *result = tmp;
673     }
674     return ret;
675 }
676 
677 /**
678  * Searches for the first occurrence of 'c' in 's', and returns a pointer
679  * to the trailing null byte if none was found.
680  */
681 #ifndef HAVE_STRCHRNUL
682 const char *qemu_strchrnul(const char *s, int c)
683 {
684     const char *e = strchr(s, c);
685     if (!e) {
686         e = s + strlen(s);
687     }
688     return e;
689 }
690 #endif
691 
692 /**
693  * parse_uint:
694  *
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
699  *
700  * Parse unsigned integer
701  *
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.
704  *
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.
708  *
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).
712  *
713  * If the integer is negative, set *@value to 0, and return -ERANGE.
714  *
715  * If the integer overflows unsigned long long, set *@value to
716  * ULLONG_MAX, and return -ERANGE.
717  *
718  * Else, set *@value to the parsed integer, and return 0.
719  */
720 int parse_uint(const char *s, unsigned long long *value, char **endptr,
721                int base)
722 {
723     int r = 0;
724     char *endp = (char *)s;
725     unsigned long long val = 0;
726 
727     assert((unsigned) base <= 36 && base != 1);
728     if (!s) {
729         r = -EINVAL;
730         goto out;
731     }
732 
733     errno = 0;
734     val = strtoull(s, &endp, base);
735     if (errno) {
736         r = -errno;
737         goto out;
738     }
739 
740     if (endp == s) {
741         r = -EINVAL;
742         goto out;
743     }
744 
745     /* make sure we reject negative numbers: */
746     while (qemu_isspace(*s)) {
747         s++;
748     }
749     if (*s == '-') {
750         val = 0;
751         r = -ERANGE;
752         goto out;
753     }
754 
755 out:
756     *value = val;
757     *endptr = endp;
758     return r;
759 }
760 
761 /**
762  * parse_uint_full:
763  *
764  * @s: String to parse
765  * @value: Destination for parsed integer value
766  * @base: integer base, between 2 and 36 inclusive, or 0
767  *
768  * Parse unsigned integer from entire string
769  *
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.
774  */
775 int parse_uint_full(const char *s, unsigned long long *value, int base)
776 {
777     char *endp;
778     int r;
779 
780     r = parse_uint(s, value, &endp, base);
781     if (r < 0) {
782         return r;
783     }
784     if (*endp) {
785         *value = 0;
786         return -EINVAL;
787     }
788 
789     return 0;
790 }
791 
792 int qemu_parse_fd(const char *param)
793 {
794     long fd;
795     char *endptr;
796 
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;
805     }
806     return fd;
807 }
808 
809 /*
810  * Implementation of  ULEB128 (http://en.wikipedia.org/wiki/LEB128)
811  * Input is limited to 14-bit numbers
812  */
813 int uleb128_encode_small(uint8_t *out, uint32_t n)
814 {
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;
823     }
824 }
825 
826 int uleb128_decode_small(const uint8_t *in, uint32_t *n)
827 {
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;
836         }
837         *n |= *in << 7;
838         return 2;
839     }
840 }
841 
842 /*
843  * helper to parse debug environment variables
844  */
845 int parse_debug_env(const char *name, int max, int initial)
846 {
847     char *debug_env = getenv(name);
848     char *inv = NULL;
849     long debug;
850 
851     if (!debug_env) {
852         return initial;
853     }
854     errno = 0;
855     debug = strtol(debug_env, &inv, 10);
856     if (inv == debug_env) {
857         return initial;
858     }
859     if (debug < 0 || debug > max || errno != 0) {
860         warn_report("%s not in [0, %d]", name, max);
861         return initial;
862     }
863     return debug;
864 }
865 
866 /*
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().
871  */
872 char *size_to_str(uint64_t val)
873 {
874     static const char *suffixes[] = { "", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei" };
875     uint64_t div;
876     int i;
877 
878     /*
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)
883      */
884     frexp(val / (1000.0 / 1024.0), &i);
885     i = (i - 1) / 10;
886     div = 1ULL << (i * 10);
887 
888     return g_strdup_printf("%0.3g %sB", (double)val / div, suffixes[i]);
889 }
890 
891 char *freq_to_str(uint64_t freq_hz)
892 {
893     static const char *const suffixes[] = { "", "K", "M", "G", "T", "P", "E" };
894     double freq = freq_hz;
895     size_t idx = 0;
896 
897     while (freq >= 1000.0) {
898         freq /= 1000.0;
899         idx++;
900     }
901     assert(idx < ARRAY_SIZE(suffixes));
902 
903     return g_strdup_printf("%0.3g %sHz", freq, suffixes[idx]);
904 }
905 
906 int qemu_pstrcmp0(const char **str1, const char **str2)
907 {
908     return g_strcmp0(*str1, *str2);
909 }
910 
911 static inline bool starts_with_prefix(const char *dir)
912 {
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]));
916 }
917 
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)
920 {
921     int len;
922     while ((*dir && G_IS_DIR_SEPARATOR(*dir)) ||
923            (*dir == '.' && (G_IS_DIR_SEPARATOR(dir[1]) || dir[1] == '\0'))) {
924         dir++;
925     }
926     len = 0;
927     while (dir[len] && !G_IS_DIR_SEPARATOR(dir[len])) {
928         len++;
929     }
930     *p_len = len;
931     return dir;
932 }
933 
934 char *get_relocated_path(const char *dir)
935 {
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;
941 
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);
946     }
947 
948     result = g_string_new(exec_dir);
949 
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));
958 
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);
964     }
965 
966     if (*dir) {
967         assert(G_IS_DIR_SEPARATOR(dir[-1]));
968         g_string_append(result, dir - 1);
969     }
970     return g_string_free(result, false);
971 }
972