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