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