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