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