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