xref: /qemu/util/cutils.c (revision 7a21bee2)
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 #ifdef __FreeBSD__
30 #include <sys/sysctl.h>
31 #include <sys/user.h>
32 #endif
33 
34 #ifdef __NetBSD__
35 #include <sys/sysctl.h>
36 #endif
37 
38 #ifdef __HAIKU__
39 #include <kernel/image.h>
40 #endif
41 
42 #ifdef G_OS_WIN32
43 #include <pathcch.h>
44 #include <wchar.h>
45 #endif
46 
47 #include "qemu/ctype.h"
48 #include "qemu/cutils.h"
49 #include "qemu/error-report.h"
50 
51 void strpadcpy(char *buf, int buf_size, const char *str, char pad)
52 {
53     int len = qemu_strnlen(str, buf_size);
54     memcpy(buf, str, len);
55     memset(buf + len, pad, buf_size - len);
56 }
57 
58 void pstrcpy(char *buf, int buf_size, const char *str)
59 {
60     int c;
61     char *q = buf;
62 
63     if (buf_size <= 0)
64         return;
65 
66     for(;;) {
67         c = *str++;
68         if (c == 0 || q >= buf + buf_size - 1)
69             break;
70         *q++ = c;
71     }
72     *q = '\0';
73 }
74 
75 /* strcat and truncate. */
76 char *pstrcat(char *buf, int buf_size, const char *s)
77 {
78     int len;
79     len = strlen(buf);
80     if (len < buf_size)
81         pstrcpy(buf + len, buf_size - len, s);
82     return buf;
83 }
84 
85 int strstart(const char *str, const char *val, const char **ptr)
86 {
87     const char *p, *q;
88     p = str;
89     q = val;
90     while (*q != '\0') {
91         if (*p != *q)
92             return 0;
93         p++;
94         q++;
95     }
96     if (ptr)
97         *ptr = p;
98     return 1;
99 }
100 
101 int stristart(const char *str, const char *val, const char **ptr)
102 {
103     const char *p, *q;
104     p = str;
105     q = val;
106     while (*q != '\0') {
107         if (qemu_toupper(*p) != qemu_toupper(*q))
108             return 0;
109         p++;
110         q++;
111     }
112     if (ptr)
113         *ptr = p;
114     return 1;
115 }
116 
117 /* XXX: use host strnlen if available ? */
118 int qemu_strnlen(const char *s, int max_len)
119 {
120     int i;
121 
122     for(i = 0; i < max_len; i++) {
123         if (s[i] == '\0') {
124             break;
125         }
126     }
127     return i;
128 }
129 
130 char *qemu_strsep(char **input, const char *delim)
131 {
132     char *result = *input;
133     if (result != NULL) {
134         char *p;
135 
136         for (p = result; *p != '\0'; p++) {
137             if (strchr(delim, *p)) {
138                 break;
139             }
140         }
141         if (*p == '\0') {
142             *input = NULL;
143         } else {
144             *p = '\0';
145             *input = p + 1;
146         }
147     }
148     return result;
149 }
150 
151 time_t mktimegm(struct tm *tm)
152 {
153     time_t t;
154     int y = tm->tm_year + 1900, m = tm->tm_mon + 1, d = tm->tm_mday;
155     if (m < 3) {
156         m += 12;
157         y--;
158     }
159     t = 86400ULL * (d + (153 * m - 457) / 5 + 365 * y + y / 4 - y / 100 +
160                  y / 400 - 719469);
161     t += 3600 * tm->tm_hour + 60 * tm->tm_min + tm->tm_sec;
162     return t;
163 }
164 
165 static int64_t suffix_mul(char suffix, int64_t unit)
166 {
167     switch (qemu_toupper(suffix)) {
168     case 'B':
169         return 1;
170     case 'K':
171         return unit;
172     case 'M':
173         return unit * unit;
174     case 'G':
175         return unit * unit * unit;
176     case 'T':
177         return unit * unit * unit * unit;
178     case 'P':
179         return unit * unit * unit * unit * unit;
180     case 'E':
181         return unit * unit * unit * unit * unit * unit;
182     }
183     return -1;
184 }
185 
186 /*
187  * Convert size string to bytes.
188  *
189  * The size parsing supports the following syntaxes
190  * - 12345 - decimal, scale determined by @default_suffix and @unit
191  * - 12345{bBkKmMgGtTpPeE} - decimal, scale determined by suffix and @unit
192  * - 12345.678{kKmMgGtTpPeE} - decimal, scale determined by suffix, and
193  *   fractional portion is truncated to byte
194  * - 0x7fEE - hexadecimal, unit determined by @default_suffix
195  *
196  * The following cause a deprecation warning, and may be removed in the future
197  * - 0xabc{kKmMgGtTpP} - hex with scaling suffix
198  *
199  * The following are intentionally not supported
200  * - octal, such as 08
201  * - fractional hex, such as 0x1.8
202  * - floating point exponents, such as 1e3
203  *
204  * The end pointer will be returned in *end, if not NULL.  If there is
205  * no fraction, the input can be decimal or hexadecimal; if there is a
206  * fraction, then the input must be decimal and there must be a suffix
207  * (possibly by @default_suffix) larger than Byte, and the fractional
208  * portion may suffer from precision loss or rounding.  The input must
209  * be positive.
210  *
211  * Return -ERANGE on overflow (with *@end advanced), and -EINVAL on
212  * other error (with *@end left unchanged).
213  */
214 static int do_strtosz(const char *nptr, const char **end,
215                       const char default_suffix, int64_t unit,
216                       uint64_t *result)
217 {
218     int retval;
219     const char *endptr, *f;
220     unsigned char c;
221     bool hex = false;
222     uint64_t val, valf = 0;
223     int64_t mul;
224 
225     /* Parse integral portion as decimal. */
226     retval = qemu_strtou64(nptr, &endptr, 10, &val);
227     if (retval) {
228         goto out;
229     }
230     if (memchr(nptr, '-', endptr - nptr) != NULL) {
231         endptr = nptr;
232         retval = -EINVAL;
233         goto out;
234     }
235     if (val == 0 && (*endptr == 'x' || *endptr == 'X')) {
236         /* Input looks like hex, reparse, and insist on no fraction. */
237         retval = qemu_strtou64(nptr, &endptr, 16, &val);
238         if (retval) {
239             goto out;
240         }
241         if (*endptr == '.') {
242             endptr = nptr;
243             retval = -EINVAL;
244             goto out;
245         }
246         hex = true;
247     } else if (*endptr == '.') {
248         /*
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.
252          */
253         double fraction;
254 
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);
266         }
267     }
268     c = *endptr;
269     mul = suffix_mul(c, unit);
270     if (mul > 0) {
271         if (hex) {
272             warn_report("Using a multiplier suffix on hex numbers "
273                         "is deprecated: %s", nptr);
274         }
275         endptr++;
276     } else {
277         mul = suffix_mul(default_suffix, unit);
278         assert(mul > 0);
279     }
280     if (mul == 1) {
281         /* When a fraction is present, a scale is required. */
282         if (valf != 0) {
283             endptr = nptr;
284             retval = -EINVAL;
285             goto out;
286         }
287     } else {
288         uint64_t valh, tmp;
289 
290         /* Compute exact result: 64.64 x 64.0 -> 128.64 fixed point */
291         mulu64(&val, &valh, val, mul);
292         mulu64(&valf, &tmp, valf, mul);
293         val += tmp;
294         valh += val < tmp;
295 
296         /* Round 0.5 upward. */
297         tmp = valf >> 63;
298         val += tmp;
299         valh += val < tmp;
300 
301         /* Report overflow. */
302         if (valh != 0) {
303             retval = -ERANGE;
304             goto out;
305         }
306     }
307 
308     retval = 0;
309 
310 out:
311     if (end) {
312         *end = endptr;
313     } else if (*endptr) {
314         retval = -EINVAL;
315     }
316     if (retval == 0) {
317         *result = val;
318     }
319 
320     return retval;
321 }
322 
323 int qemu_strtosz(const char *nptr, const char **end, uint64_t *result)
324 {
325     return do_strtosz(nptr, end, 'B', 1024, result);
326 }
327 
328 int qemu_strtosz_MiB(const char *nptr, const char **end, uint64_t *result)
329 {
330     return do_strtosz(nptr, end, 'M', 1024, result);
331 }
332 
333 int qemu_strtosz_metric(const char *nptr, const char **end, uint64_t *result)
334 {
335     return do_strtosz(nptr, end, 'B', 1000, result);
336 }
337 
338 /**
339  * Helper function for error checking after strtol() and the like
340  */
341 static int check_strtox_error(const char *nptr, char *ep,
342                               const char **endptr, bool check_zero,
343                               int libc_errno)
344 {
345     assert(ep >= nptr);
346 
347     /* Windows has a bug in that it fails to parse 0 from "0x" in base 16 */
348     if (check_zero && ep == nptr && libc_errno == 0) {
349         char *tmp;
350 
351         errno = 0;
352         if (strtol(nptr, &tmp, 10) == 0 && errno == 0 &&
353             (*tmp == 'x' || *tmp == 'X')) {
354             ep = tmp;
355         }
356     }
357 
358     if (endptr) {
359         *endptr = ep;
360     }
361 
362     /* Turn "no conversion" into an error */
363     if (libc_errno == 0 && ep == nptr) {
364         return -EINVAL;
365     }
366 
367     /* Fail when we're expected to consume the string, but didn't */
368     if (!endptr && *ep) {
369         return -EINVAL;
370     }
371 
372     return -libc_errno;
373 }
374 
375 /**
376  * Convert string @nptr to an integer, and store it in @result.
377  *
378  * This is a wrapper around strtol() that is harder to misuse.
379  * Semantics of @nptr, @endptr, @base match strtol() with differences
380  * noted below.
381  *
382  * @nptr may be null, and no conversion is performed then.
383  *
384  * If no conversion is performed, store @nptr in *@endptr and return
385  * -EINVAL.
386  *
387  * If @endptr is null, and the string isn't fully converted, return
388  * -EINVAL.  This is the case when the pointer that would be stored in
389  * a non-null @endptr points to a character other than '\0'.
390  *
391  * If the conversion overflows @result, store INT_MAX in @result,
392  * and return -ERANGE.
393  *
394  * If the conversion underflows @result, store INT_MIN in @result,
395  * and return -ERANGE.
396  *
397  * Else store the converted value in @result, and return zero.
398  */
399 int qemu_strtoi(const char *nptr, const char **endptr, int base,
400                 int *result)
401 {
402     char *ep;
403     long long lresult;
404 
405     assert((unsigned) base <= 36 && base != 1);
406     if (!nptr) {
407         if (endptr) {
408             *endptr = nptr;
409         }
410         return -EINVAL;
411     }
412 
413     errno = 0;
414     lresult = strtoll(nptr, &ep, base);
415     if (lresult < INT_MIN) {
416         *result = INT_MIN;
417         errno = ERANGE;
418     } else if (lresult > INT_MAX) {
419         *result = INT_MAX;
420         errno = ERANGE;
421     } else {
422         *result = lresult;
423     }
424     return check_strtox_error(nptr, ep, endptr, lresult == 0, errno);
425 }
426 
427 /**
428  * Convert string @nptr to an unsigned integer, and store it in @result.
429  *
430  * This is a wrapper around strtoul() that is harder to misuse.
431  * Semantics of @nptr, @endptr, @base match strtoul() with differences
432  * noted below.
433  *
434  * @nptr may be null, and no conversion is performed then.
435  *
436  * If no conversion is performed, store @nptr in *@endptr and return
437  * -EINVAL.
438  *
439  * If @endptr is null, and the string isn't fully converted, return
440  * -EINVAL.  This is the case when the pointer that would be stored in
441  * a non-null @endptr points to a character other than '\0'.
442  *
443  * If the conversion overflows @result, store UINT_MAX in @result,
444  * and return -ERANGE.
445  *
446  * Else store the converted value in @result, and return zero.
447  *
448  * Note that a number with a leading minus sign gets converted without
449  * the minus sign, checked for overflow (see above), then negated (in
450  * @result's type).  This is exactly how strtoul() works.
451  */
452 int qemu_strtoui(const char *nptr, const char **endptr, int base,
453                  unsigned int *result)
454 {
455     char *ep;
456     long long lresult;
457 
458     assert((unsigned) base <= 36 && base != 1);
459     if (!nptr) {
460         if (endptr) {
461             *endptr = nptr;
462         }
463         return -EINVAL;
464     }
465 
466     errno = 0;
467     lresult = strtoull(nptr, &ep, base);
468 
469     /* Windows returns 1 for negative out-of-range values.  */
470     if (errno == ERANGE) {
471         *result = -1;
472     } else {
473         if (lresult > UINT_MAX) {
474             *result = UINT_MAX;
475             errno = ERANGE;
476         } else if (lresult < INT_MIN) {
477             *result = UINT_MAX;
478             errno = ERANGE;
479         } else {
480             *result = lresult;
481         }
482     }
483     return check_strtox_error(nptr, ep, endptr, lresult == 0, errno);
484 }
485 
486 /**
487  * Convert string @nptr to a long integer, and store it in @result.
488  *
489  * This is a wrapper around strtol() that is harder to misuse.
490  * Semantics of @nptr, @endptr, @base match strtol() with differences
491  * noted below.
492  *
493  * @nptr may be null, and no conversion is performed then.
494  *
495  * If no conversion is performed, store @nptr in *@endptr and return
496  * -EINVAL.
497  *
498  * If @endptr is null, and the string isn't fully converted, return
499  * -EINVAL.  This is the case when the pointer that would be stored in
500  * a non-null @endptr points to a character other than '\0'.
501  *
502  * If the conversion overflows @result, store LONG_MAX in @result,
503  * and return -ERANGE.
504  *
505  * If the conversion underflows @result, store LONG_MIN in @result,
506  * and return -ERANGE.
507  *
508  * Else store the converted value in @result, and return zero.
509  */
510 int qemu_strtol(const char *nptr, const char **endptr, int base,
511                 long *result)
512 {
513     char *ep;
514 
515     assert((unsigned) base <= 36 && base != 1);
516     if (!nptr) {
517         if (endptr) {
518             *endptr = nptr;
519         }
520         return -EINVAL;
521     }
522 
523     errno = 0;
524     *result = strtol(nptr, &ep, base);
525     return check_strtox_error(nptr, ep, endptr, *result == 0, errno);
526 }
527 
528 /**
529  * Convert string @nptr to an unsigned long, and store it in @result.
530  *
531  * This is a wrapper around strtoul() that is harder to misuse.
532  * Semantics of @nptr, @endptr, @base match strtoul() with differences
533  * noted below.
534  *
535  * @nptr may be null, and no conversion is performed then.
536  *
537  * If no conversion is performed, store @nptr in *@endptr and return
538  * -EINVAL.
539  *
540  * If @endptr is null, and the string isn't fully converted, return
541  * -EINVAL.  This is the case when the pointer that would be stored in
542  * a non-null @endptr points to a character other than '\0'.
543  *
544  * If the conversion overflows @result, store ULONG_MAX in @result,
545  * and return -ERANGE.
546  *
547  * Else store the converted value in @result, and return zero.
548  *
549  * Note that a number with a leading minus sign gets converted without
550  * the minus sign, checked for overflow (see above), then negated (in
551  * @result's type).  This is exactly how strtoul() works.
552  */
553 int qemu_strtoul(const char *nptr, const char **endptr, int base,
554                  unsigned long *result)
555 {
556     char *ep;
557 
558     assert((unsigned) base <= 36 && base != 1);
559     if (!nptr) {
560         if (endptr) {
561             *endptr = nptr;
562         }
563         return -EINVAL;
564     }
565 
566     errno = 0;
567     *result = strtoul(nptr, &ep, base);
568     /* Windows returns 1 for negative out-of-range values.  */
569     if (errno == ERANGE) {
570         *result = -1;
571     }
572     return check_strtox_error(nptr, ep, endptr, *result == 0, errno);
573 }
574 
575 /**
576  * Convert string @nptr to an int64_t.
577  *
578  * Works like qemu_strtol(), except it stores INT64_MAX on overflow,
579  * and INT64_MIN on underflow.
580  */
581 int qemu_strtoi64(const char *nptr, const char **endptr, int base,
582                  int64_t *result)
583 {
584     char *ep;
585 
586     assert((unsigned) base <= 36 && base != 1);
587     if (!nptr) {
588         if (endptr) {
589             *endptr = nptr;
590         }
591         return -EINVAL;
592     }
593 
594     /* This assumes int64_t is long long TODO relax */
595     QEMU_BUILD_BUG_ON(sizeof(int64_t) != sizeof(long long));
596     errno = 0;
597     *result = strtoll(nptr, &ep, base);
598     return check_strtox_error(nptr, ep, endptr, *result == 0, errno);
599 }
600 
601 /**
602  * Convert string @nptr to an uint64_t.
603  *
604  * Works like qemu_strtoul(), except it stores UINT64_MAX on overflow.
605  */
606 int qemu_strtou64(const char *nptr, const char **endptr, int base,
607                   uint64_t *result)
608 {
609     char *ep;
610 
611     assert((unsigned) base <= 36 && base != 1);
612     if (!nptr) {
613         if (endptr) {
614             *endptr = nptr;
615         }
616         return -EINVAL;
617     }
618 
619     /* This assumes uint64_t is unsigned long long TODO relax */
620     QEMU_BUILD_BUG_ON(sizeof(uint64_t) != sizeof(unsigned long long));
621     errno = 0;
622     *result = strtoull(nptr, &ep, base);
623     /* Windows returns 1 for negative out-of-range values.  */
624     if (errno == ERANGE) {
625         *result = -1;
626     }
627     return check_strtox_error(nptr, ep, endptr, *result == 0, errno);
628 }
629 
630 /**
631  * Convert string @nptr to a double.
632   *
633  * This is a wrapper around strtod() that is harder to misuse.
634  * Semantics of @nptr and @endptr match strtod() with differences
635  * noted below.
636  *
637  * @nptr may be null, and no conversion is performed then.
638  *
639  * If no conversion is performed, store @nptr in *@endptr and return
640  * -EINVAL.
641  *
642  * If @endptr is null, and the string isn't fully converted, return
643  * -EINVAL. This is the case when the pointer that would be stored in
644  * a non-null @endptr points to a character other than '\0'.
645  *
646  * If the conversion overflows, store +/-HUGE_VAL in @result, depending
647  * on the sign, and return -ERANGE.
648  *
649  * If the conversion underflows, store +/-0.0 in @result, depending on the
650  * sign, and return -ERANGE.
651  *
652  * Else store the converted value in @result, and return zero.
653  */
654 int qemu_strtod(const char *nptr, const char **endptr, double *result)
655 {
656     char *ep;
657 
658     if (!nptr) {
659         if (endptr) {
660             *endptr = nptr;
661         }
662         return -EINVAL;
663     }
664 
665     errno = 0;
666     *result = strtod(nptr, &ep);
667     return check_strtox_error(nptr, ep, endptr, false, errno);
668 }
669 
670 /**
671  * Convert string @nptr to a finite double.
672  *
673  * Works like qemu_strtod(), except that "NaN" and "inf" are rejected
674  * with -EINVAL and no conversion is performed.
675  */
676 int qemu_strtod_finite(const char *nptr, const char **endptr, double *result)
677 {
678     double tmp;
679     int ret;
680 
681     ret = qemu_strtod(nptr, endptr, &tmp);
682     if (!ret && !isfinite(tmp)) {
683         if (endptr) {
684             *endptr = nptr;
685         }
686         ret = -EINVAL;
687     }
688 
689     if (ret != -EINVAL) {
690         *result = tmp;
691     }
692     return ret;
693 }
694 
695 /**
696  * Searches for the first occurrence of 'c' in 's', and returns a pointer
697  * to the trailing null byte if none was found.
698  */
699 #ifndef HAVE_STRCHRNUL
700 const char *qemu_strchrnul(const char *s, int c)
701 {
702     const char *e = strchr(s, c);
703     if (!e) {
704         e = s + strlen(s);
705     }
706     return e;
707 }
708 #endif
709 
710 /**
711  * parse_uint:
712  *
713  * @s: String to parse
714  * @value: Destination for parsed integer value
715  * @endptr: Destination for pointer to first character not consumed
716  * @base: integer base, between 2 and 36 inclusive, or 0
717  *
718  * Parse unsigned integer
719  *
720  * Parsed syntax is like strtoull()'s: arbitrary whitespace, a single optional
721  * '+' or '-', an optional "0x" if @base is 0 or 16, one or more digits.
722  *
723  * If @s is null, or @base is invalid, or @s doesn't start with an
724  * integer in the syntax above, set *@value to 0, *@endptr to @s, and
725  * return -EINVAL.
726  *
727  * Set *@endptr to point right beyond the parsed integer (even if the integer
728  * overflows or is negative, all digits will be parsed and *@endptr will
729  * point right beyond them).
730  *
731  * If the integer is negative, set *@value to 0, and return -ERANGE.
732  *
733  * If the integer overflows unsigned long long, set *@value to
734  * ULLONG_MAX, and return -ERANGE.
735  *
736  * Else, set *@value to the parsed integer, and return 0.
737  */
738 int parse_uint(const char *s, unsigned long long *value, char **endptr,
739                int base)
740 {
741     int r = 0;
742     char *endp = (char *)s;
743     unsigned long long val = 0;
744 
745     assert((unsigned) base <= 36 && base != 1);
746     if (!s) {
747         r = -EINVAL;
748         goto out;
749     }
750 
751     errno = 0;
752     val = strtoull(s, &endp, base);
753     if (errno) {
754         r = -errno;
755         goto out;
756     }
757 
758     if (endp == s) {
759         r = -EINVAL;
760         goto out;
761     }
762 
763     /* make sure we reject negative numbers: */
764     while (qemu_isspace(*s)) {
765         s++;
766     }
767     if (*s == '-') {
768         val = 0;
769         r = -ERANGE;
770         goto out;
771     }
772 
773 out:
774     *value = val;
775     *endptr = endp;
776     return r;
777 }
778 
779 /**
780  * parse_uint_full:
781  *
782  * @s: String to parse
783  * @value: Destination for parsed integer value
784  * @base: integer base, between 2 and 36 inclusive, or 0
785  *
786  * Parse unsigned integer from entire string
787  *
788  * Have the same behavior of parse_uint(), but with an additional check
789  * for additional data after the parsed number. If extra characters are present
790  * after the parsed number, the function will return -EINVAL, and *@v will
791  * be set to 0.
792  */
793 int parse_uint_full(const char *s, unsigned long long *value, int base)
794 {
795     char *endp;
796     int r;
797 
798     r = parse_uint(s, value, &endp, base);
799     if (r < 0) {
800         return r;
801     }
802     if (*endp) {
803         *value = 0;
804         return -EINVAL;
805     }
806 
807     return 0;
808 }
809 
810 int qemu_parse_fd(const char *param)
811 {
812     long fd;
813     char *endptr;
814 
815     errno = 0;
816     fd = strtol(param, &endptr, 10);
817     if (param == endptr /* no conversion performed */                    ||
818         errno != 0      /* not representable as long; possibly others */ ||
819         *endptr != '\0' /* final string not empty */                     ||
820         fd < 0          /* invalid as file descriptor */                 ||
821         fd > INT_MAX    /* not representable as int */) {
822         return -1;
823     }
824     return fd;
825 }
826 
827 /*
828  * Implementation of  ULEB128 (http://en.wikipedia.org/wiki/LEB128)
829  * Input is limited to 14-bit numbers
830  */
831 int uleb128_encode_small(uint8_t *out, uint32_t n)
832 {
833     g_assert(n <= 0x3fff);
834     if (n < 0x80) {
835         *out = n;
836         return 1;
837     } else {
838         *out++ = (n & 0x7f) | 0x80;
839         *out = n >> 7;
840         return 2;
841     }
842 }
843 
844 int uleb128_decode_small(const uint8_t *in, uint32_t *n)
845 {
846     if (!(*in & 0x80)) {
847         *n = *in;
848         return 1;
849     } else {
850         *n = *in++ & 0x7f;
851         /* we exceed 14 bit number */
852         if (*in & 0x80) {
853             return -1;
854         }
855         *n |= *in << 7;
856         return 2;
857     }
858 }
859 
860 /*
861  * helper to parse debug environment variables
862  */
863 int parse_debug_env(const char *name, int max, int initial)
864 {
865     char *debug_env = getenv(name);
866     char *inv = NULL;
867     long debug;
868 
869     if (!debug_env) {
870         return initial;
871     }
872     errno = 0;
873     debug = strtol(debug_env, &inv, 10);
874     if (inv == debug_env) {
875         return initial;
876     }
877     if (debug < 0 || debug > max || errno != 0) {
878         warn_report("%s not in [0, %d]", name, max);
879         return initial;
880     }
881     return debug;
882 }
883 
884 const char *si_prefix(unsigned int exp10)
885 {
886     static const char *prefixes[] = {
887         "a", "f", "p", "n", "u", "m", "", "K", "M", "G", "T", "P", "E"
888     };
889 
890     exp10 += 18;
891     assert(exp10 % 3 == 0 && exp10 / 3 < ARRAY_SIZE(prefixes));
892     return prefixes[exp10 / 3];
893 }
894 
895 const char *iec_binary_prefix(unsigned int exp2)
896 {
897     static const char *prefixes[] = { "", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei" };
898 
899     assert(exp2 % 10 == 0 && exp2 / 10 < ARRAY_SIZE(prefixes));
900     return prefixes[exp2 / 10];
901 }
902 
903 /*
904  * Return human readable string for size @val.
905  * @val can be anything that uint64_t allows (no more than "16 EiB").
906  * Use IEC binary units like KiB, MiB, and so forth.
907  * Caller is responsible for passing it to g_free().
908  */
909 char *size_to_str(uint64_t val)
910 {
911     uint64_t div;
912     int i;
913 
914     /*
915      * The exponent (returned in i) minus one gives us
916      * floor(log2(val * 1024 / 1000).  The correction makes us
917      * switch to the higher power when the integer part is >= 1000.
918      * (see e41b509d68afb1f for more info)
919      */
920     frexp(val / (1000.0 / 1024.0), &i);
921     i = (i - 1) / 10 * 10;
922     div = 1ULL << i;
923 
924     return g_strdup_printf("%0.3g %sB", (double)val / div, iec_binary_prefix(i));
925 }
926 
927 char *freq_to_str(uint64_t freq_hz)
928 {
929     double freq = freq_hz;
930     size_t exp10 = 0;
931 
932     while (freq >= 1000.0) {
933         freq /= 1000.0;
934         exp10 += 3;
935     }
936 
937     return g_strdup_printf("%0.3g %sHz", freq, si_prefix(exp10));
938 }
939 
940 int qemu_pstrcmp0(const char **str1, const char **str2)
941 {
942     return g_strcmp0(*str1, *str2);
943 }
944 
945 static inline bool starts_with_prefix(const char *dir)
946 {
947     size_t prefix_len = strlen(CONFIG_PREFIX);
948     return !memcmp(dir, CONFIG_PREFIX, prefix_len) &&
949         (!dir[prefix_len] || G_IS_DIR_SEPARATOR(dir[prefix_len]));
950 }
951 
952 /* Return the next path component in dir, and store its length in *p_len.  */
953 static inline const char *next_component(const char *dir, int *p_len)
954 {
955     int len;
956     while ((*dir && G_IS_DIR_SEPARATOR(*dir)) ||
957            (*dir == '.' && (G_IS_DIR_SEPARATOR(dir[1]) || dir[1] == '\0'))) {
958         dir++;
959     }
960     len = 0;
961     while (dir[len] && !G_IS_DIR_SEPARATOR(dir[len])) {
962         len++;
963     }
964     *p_len = len;
965     return dir;
966 }
967 
968 static const char *exec_dir;
969 
970 void qemu_init_exec_dir(const char *argv0)
971 {
972 #ifdef G_OS_WIN32
973     char *p;
974     char buf[MAX_PATH];
975     DWORD len;
976 
977     if (exec_dir) {
978         return;
979     }
980 
981     len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
982     if (len == 0) {
983         return;
984     }
985 
986     buf[len] = 0;
987     p = buf + len - 1;
988     while (p != buf && *p != '\\') {
989         p--;
990     }
991     *p = 0;
992     if (access(buf, R_OK) == 0) {
993         exec_dir = g_strdup(buf);
994     } else {
995         exec_dir = CONFIG_BINDIR;
996     }
997 #else
998     char *p = NULL;
999     char buf[PATH_MAX];
1000 
1001     if (exec_dir) {
1002         return;
1003     }
1004 
1005 #if defined(__linux__)
1006     {
1007         int len;
1008         len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
1009         if (len > 0) {
1010             buf[len] = 0;
1011             p = buf;
1012         }
1013     }
1014 #elif defined(__FreeBSD__) \
1015       || (defined(__NetBSD__) && defined(KERN_PROC_PATHNAME))
1016     {
1017 #if defined(__FreeBSD__)
1018         static int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
1019 #else
1020         static int mib[4] = {CTL_KERN, KERN_PROC_ARGS, -1, KERN_PROC_PATHNAME};
1021 #endif
1022         size_t len = sizeof(buf) - 1;
1023 
1024         *buf = '\0';
1025         if (!sysctl(mib, ARRAY_SIZE(mib), buf, &len, NULL, 0) &&
1026             *buf) {
1027             buf[sizeof(buf) - 1] = '\0';
1028             p = buf;
1029         }
1030     }
1031 #elif defined(__APPLE__)
1032     {
1033         char fpath[PATH_MAX];
1034         uint32_t len = sizeof(fpath);
1035         if (_NSGetExecutablePath(fpath, &len) == 0) {
1036             p = realpath(fpath, buf);
1037             if (!p) {
1038                 return;
1039             }
1040         }
1041     }
1042 #elif defined(__HAIKU__)
1043     {
1044         image_info ii;
1045         int32_t c = 0;
1046 
1047         *buf = '\0';
1048         while (get_next_image_info(0, &c, &ii) == B_OK) {
1049             if (ii.type == B_APP_IMAGE) {
1050                 strncpy(buf, ii.name, sizeof(buf));
1051                 buf[sizeof(buf) - 1] = 0;
1052                 p = buf;
1053                 break;
1054             }
1055         }
1056     }
1057 #endif
1058     /* If we don't have any way of figuring out the actual executable
1059        location then try argv[0].  */
1060     if (!p && argv0) {
1061         p = realpath(argv0, buf);
1062     }
1063     if (p) {
1064         exec_dir = g_path_get_dirname(p);
1065     } else {
1066         exec_dir = CONFIG_BINDIR;
1067     }
1068 #endif
1069 }
1070 
1071 const char *qemu_get_exec_dir(void)
1072 {
1073     return exec_dir;
1074 }
1075 
1076 char *get_relocated_path(const char *dir)
1077 {
1078     size_t prefix_len = strlen(CONFIG_PREFIX);
1079     const char *bindir = CONFIG_BINDIR;
1080     const char *exec_dir = qemu_get_exec_dir();
1081     GString *result;
1082     int len_dir, len_bindir;
1083 
1084     /* Fail if qemu_init_exec_dir was not called.  */
1085     assert(exec_dir[0]);
1086 
1087     result = g_string_new(exec_dir);
1088     g_string_append(result, "/qemu-bundle");
1089     if (access(result->str, R_OK) == 0) {
1090 #ifdef G_OS_WIN32
1091         size_t size = mbsrtowcs(NULL, &dir, 0, &(mbstate_t){0}) + 1;
1092         PWSTR wdir = g_new(WCHAR, size);
1093         mbsrtowcs(wdir, &dir, size, &(mbstate_t){0});
1094 
1095         PCWSTR wdir_skipped_root;
1096         PathCchSkipRoot(wdir, &wdir_skipped_root);
1097 
1098         size = wcsrtombs(NULL, &wdir_skipped_root, 0, &(mbstate_t){0});
1099         char *cursor = result->str + result->len;
1100         g_string_set_size(result, result->len + size);
1101         wcsrtombs(cursor, &wdir_skipped_root, size + 1, &(mbstate_t){0});
1102         g_free(wdir);
1103 #else
1104         g_string_append(result, dir);
1105 #endif
1106     } else if (!starts_with_prefix(dir) || !starts_with_prefix(bindir)) {
1107         g_string_assign(result, dir);
1108     } else {
1109         g_string_assign(result, exec_dir);
1110 
1111         /* Advance over common components.  */
1112         len_dir = len_bindir = prefix_len;
1113         do {
1114             dir += len_dir;
1115             bindir += len_bindir;
1116             dir = next_component(dir, &len_dir);
1117             bindir = next_component(bindir, &len_bindir);
1118         } while (len_dir && len_dir == len_bindir && !memcmp(dir, bindir, len_dir));
1119 
1120         /* Ascend from bindir to the common prefix with dir.  */
1121         while (len_bindir) {
1122             bindir += len_bindir;
1123             g_string_append(result, "/..");
1124             bindir = next_component(bindir, &len_bindir);
1125         }
1126 
1127         if (*dir) {
1128             assert(G_IS_DIR_SEPARATOR(dir[-1]));
1129             g_string_append(result, dir - 1);
1130         }
1131     }
1132 
1133     return g_string_free(result, false);
1134 }
1135