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