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