2 * Simple C functions to supplement the C library
4 * Copyright (c) 2006 Fabrice Bellard
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:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
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
25 #include "qemu/osdep.h"
26 #include "qemu/host-utils.h"
29 #include "qemu/ctype.h"
30 #include "qemu/cutils.h"
31 #include "qemu/error-report.h"
33 void strpadcpy(char *buf
, int buf_size
, const char *str
, char pad
)
35 int len
= qemu_strnlen(str
, buf_size
);
36 memcpy(buf
, str
, len
);
37 memset(buf
+ len
, pad
, buf_size
- len
);
40 void pstrcpy(char *buf
, int buf_size
, const char *str
)
50 if (c
== 0 || q
>= buf
+ buf_size
- 1)
57 /* strcat and truncate. */
58 char *pstrcat(char *buf
, int buf_size
, const char *s
)
63 pstrcpy(buf
+ len
, buf_size
- len
, s
);
67 int strstart(const char *str
, const char *val
, const char **ptr
)
83 int stristart(const char *str
, const char *val
, const char **ptr
)
89 if (qemu_toupper(*p
) != qemu_toupper(*q
))
99 /* XXX: use host strnlen if available ? */
100 int qemu_strnlen(const char *s
, int max_len
)
104 for(i
= 0; i
< max_len
; i
++) {
112 char *qemu_strsep(char **input
, const char *delim
)
114 char *result
= *input
;
115 if (result
!= NULL
) {
118 for (p
= result
; *p
!= '\0'; p
++) {
119 if (strchr(delim
, *p
)) {
133 time_t mktimegm(struct tm
*tm
)
136 int y
= tm
->tm_year
+ 1900, m
= tm
->tm_mon
+ 1, d
= tm
->tm_mday
;
141 t
= 86400ULL * (d
+ (153 * m
- 457) / 5 + 365 * y
+ y
/ 4 - y
/ 100 +
143 t
+= 3600 * tm
->tm_hour
+ 60 * tm
->tm_min
+ tm
->tm_sec
;
147 static int64_t suffix_mul(char suffix
, int64_t unit
)
149 switch (qemu_toupper(suffix
)) {
157 return unit
* unit
* unit
;
159 return unit
* unit
* unit
* unit
;
161 return unit
* unit
* unit
* unit
* unit
;
163 return unit
* unit
* unit
* unit
* unit
* unit
;
169 * Convert size string to bytes.
171 * The size parsing supports the following syntaxes
172 * - 12345 - decimal, scale determined by @default_suffix and @unit
173 * - 12345{bBkKmMgGtTpPeE} - decimal, scale determined by suffix and @unit
174 * - 12345.678{kKmMgGtTpPeE} - decimal, scale determined by suffix, and
175 * fractional portion is truncated to byte
176 * - 0x7fEE - hexadecimal, unit determined by @default_suffix
178 * The following cause a deprecation warning, and may be removed in the future
179 * - 0xabc{kKmMgGtTpP} - hex with scaling suffix
181 * The following are intentionally not supported
182 * - octal, such as 08
183 * - fractional hex, such as 0x1.8
184 * - floating point exponents, such as 1e3
186 * The end pointer will be returned in *end, if not NULL. If there is
187 * no fraction, the input can be decimal or hexadecimal; if there is a
188 * fraction, then the input must be decimal and there must be a suffix
189 * (possibly by @default_suffix) larger than Byte, and the fractional
190 * portion may suffer from precision loss or rounding. The input must
193 * Return -ERANGE on overflow (with *@end advanced), and -EINVAL on
194 * other error (with *@end left unchanged).
196 static int do_strtosz(const char *nptr
, const char **end
,
197 const char default_suffix
, int64_t unit
,
201 const char *endptr
, *f
;
204 uint64_t val
, valf
= 0;
207 /* Parse integral portion as decimal. */
208 retval
= qemu_strtou64(nptr
, &endptr
, 10, &val
);
212 if (memchr(nptr
, '-', endptr
- nptr
) != NULL
) {
217 if (val
== 0 && (*endptr
== 'x' || *endptr
== 'X')) {
218 /* Input looks like hex, reparse, and insist on no fraction. */
219 retval
= qemu_strtou64(nptr
, &endptr
, 16, &val
);
223 if (*endptr
== '.') {
229 } else if (*endptr
== '.') {
231 * Input looks like a fraction. Make sure even 1.k works
232 * without fractional digits. If we see an exponent, treat
233 * the entire input as invalid instead.
238 retval
= qemu_strtod_finite(f
, &endptr
, &fraction
);
241 } else if (memchr(f
, 'e', endptr
- f
) || memchr(f
, 'E', endptr
- f
)) {
246 /* Extract into a 64-bit fixed-point fraction. */
247 valf
= (uint64_t)(fraction
* 0x1p
64);
251 mul
= suffix_mul(c
, unit
);
254 warn_report("Using a multiplier suffix on hex numbers "
255 "is deprecated: %s", nptr
);
259 mul
= suffix_mul(default_suffix
, unit
);
263 /* When a fraction is present, a scale is required. */
272 /* Compute exact result: 64.64 x 64.0 -> 128.64 fixed point */
273 mulu64(&val
, &valh
, val
, mul
);
274 mulu64(&valf
, &tmp
, valf
, mul
);
278 /* Round 0.5 upward. */
283 /* Report overflow. */
295 } else if (*endptr
) {
305 int qemu_strtosz(const char *nptr
, const char **end
, uint64_t *result
)
307 return do_strtosz(nptr
, end
, 'B', 1024, result
);
310 int qemu_strtosz_MiB(const char *nptr
, const char **end
, uint64_t *result
)
312 return do_strtosz(nptr
, end
, 'M', 1024, result
);
315 int qemu_strtosz_metric(const char *nptr
, const char **end
, uint64_t *result
)
317 return do_strtosz(nptr
, end
, 'B', 1000, result
);
321 * Helper function for error checking after strtol() and the like
323 static int check_strtox_error(const char *nptr
, char *ep
,
324 const char **endptr
, bool check_zero
,
329 /* Windows has a bug in that it fails to parse 0 from "0x" in base 16 */
330 if (check_zero
&& ep
== nptr
&& libc_errno
== 0) {
334 if (strtol(nptr
, &tmp
, 10) == 0 && errno
== 0 &&
335 (*tmp
== 'x' || *tmp
== 'X')) {
344 /* Turn "no conversion" into an error */
345 if (libc_errno
== 0 && ep
== nptr
) {
349 /* Fail when we're expected to consume the string, but didn't */
350 if (!endptr
&& *ep
) {
358 * Convert string @nptr to an integer, and store it in @result.
360 * This is a wrapper around strtol() that is harder to misuse.
361 * Semantics of @nptr, @endptr, @base match strtol() with differences
364 * @nptr may be null, and no conversion is performed then.
366 * If no conversion is performed, store @nptr in *@endptr and return
369 * If @endptr is null, and the string isn't fully converted, return
370 * -EINVAL. This is the case when the pointer that would be stored in
371 * a non-null @endptr points to a character other than '\0'.
373 * If the conversion overflows @result, store INT_MAX in @result,
374 * and return -ERANGE.
376 * If the conversion underflows @result, store INT_MIN in @result,
377 * and return -ERANGE.
379 * Else store the converted value in @result, and return zero.
381 int qemu_strtoi(const char *nptr
, const char **endptr
, int base
,
387 assert((unsigned) base
<= 36 && base
!= 1);
396 lresult
= strtoll(nptr
, &ep
, base
);
397 if (lresult
< INT_MIN
) {
400 } else if (lresult
> INT_MAX
) {
406 return check_strtox_error(nptr
, ep
, endptr
, lresult
== 0, errno
);
410 * Convert string @nptr to an unsigned integer, and store it in @result.
412 * This is a wrapper around strtoul() that is harder to misuse.
413 * Semantics of @nptr, @endptr, @base match strtoul() with differences
416 * @nptr may be null, and no conversion is performed then.
418 * If no conversion is performed, store @nptr in *@endptr and return
421 * If @endptr is null, and the string isn't fully converted, return
422 * -EINVAL. This is the case when the pointer that would be stored in
423 * a non-null @endptr points to a character other than '\0'.
425 * If the conversion overflows @result, store UINT_MAX in @result,
426 * and return -ERANGE.
428 * Else store the converted value in @result, and return zero.
430 * Note that a number with a leading minus sign gets converted without
431 * the minus sign, checked for overflow (see above), then negated (in
432 * @result's type). This is exactly how strtoul() works.
434 int qemu_strtoui(const char *nptr
, const char **endptr
, int base
,
435 unsigned int *result
)
440 assert((unsigned) base
<= 36 && base
!= 1);
449 lresult
= strtoull(nptr
, &ep
, base
);
451 /* Windows returns 1 for negative out-of-range values. */
452 if (errno
== ERANGE
) {
455 if (lresult
> UINT_MAX
) {
458 } else if (lresult
< INT_MIN
) {
465 return check_strtox_error(nptr
, ep
, endptr
, lresult
== 0, errno
);
469 * Convert string @nptr to a long integer, and store it in @result.
471 * This is a wrapper around strtol() that is harder to misuse.
472 * Semantics of @nptr, @endptr, @base match strtol() with differences
475 * @nptr may be null, and no conversion is performed then.
477 * If no conversion is performed, store @nptr in *@endptr and return
480 * If @endptr is null, and the string isn't fully converted, return
481 * -EINVAL. This is the case when the pointer that would be stored in
482 * a non-null @endptr points to a character other than '\0'.
484 * If the conversion overflows @result, store LONG_MAX in @result,
485 * and return -ERANGE.
487 * If the conversion underflows @result, store LONG_MIN in @result,
488 * and return -ERANGE.
490 * Else store the converted value in @result, and return zero.
492 int qemu_strtol(const char *nptr
, const char **endptr
, int base
,
497 assert((unsigned) base
<= 36 && base
!= 1);
506 *result
= strtol(nptr
, &ep
, base
);
507 return check_strtox_error(nptr
, ep
, endptr
, *result
== 0, errno
);
511 * Convert string @nptr to an unsigned long, and store it in @result.
513 * This is a wrapper around strtoul() that is harder to misuse.
514 * Semantics of @nptr, @endptr, @base match strtoul() with differences
517 * @nptr may be null, and no conversion is performed then.
519 * If no conversion is performed, store @nptr in *@endptr and return
522 * If @endptr is null, and the string isn't fully converted, return
523 * -EINVAL. This is the case when the pointer that would be stored in
524 * a non-null @endptr points to a character other than '\0'.
526 * If the conversion overflows @result, store ULONG_MAX in @result,
527 * and return -ERANGE.
529 * Else store the converted value in @result, and return zero.
531 * Note that a number with a leading minus sign gets converted without
532 * the minus sign, checked for overflow (see above), then negated (in
533 * @result's type). This is exactly how strtoul() works.
535 int qemu_strtoul(const char *nptr
, const char **endptr
, int base
,
536 unsigned long *result
)
540 assert((unsigned) base
<= 36 && base
!= 1);
549 *result
= strtoul(nptr
, &ep
, base
);
550 /* Windows returns 1 for negative out-of-range values. */
551 if (errno
== ERANGE
) {
554 return check_strtox_error(nptr
, ep
, endptr
, *result
== 0, errno
);
558 * Convert string @nptr to an int64_t.
560 * Works like qemu_strtol(), except it stores INT64_MAX on overflow,
561 * and INT64_MIN on underflow.
563 int qemu_strtoi64(const char *nptr
, const char **endptr
, int base
,
568 assert((unsigned) base
<= 36 && base
!= 1);
576 /* This assumes int64_t is long long TODO relax */
577 QEMU_BUILD_BUG_ON(sizeof(int64_t) != sizeof(long long));
579 *result
= strtoll(nptr
, &ep
, base
);
580 return check_strtox_error(nptr
, ep
, endptr
, *result
== 0, errno
);
584 * Convert string @nptr to an uint64_t.
586 * Works like qemu_strtoul(), except it stores UINT64_MAX on overflow.
588 int qemu_strtou64(const char *nptr
, const char **endptr
, int base
,
593 assert((unsigned) base
<= 36 && base
!= 1);
601 /* This assumes uint64_t is unsigned long long TODO relax */
602 QEMU_BUILD_BUG_ON(sizeof(uint64_t) != sizeof(unsigned long long));
604 *result
= strtoull(nptr
, &ep
, base
);
605 /* Windows returns 1 for negative out-of-range values. */
606 if (errno
== ERANGE
) {
609 return check_strtox_error(nptr
, ep
, endptr
, *result
== 0, errno
);
613 * Convert string @nptr to a double.
615 * This is a wrapper around strtod() that is harder to misuse.
616 * Semantics of @nptr and @endptr match strtod() with differences
619 * @nptr may be null, and no conversion is performed then.
621 * If no conversion is performed, store @nptr in *@endptr and return
624 * If @endptr is null, and the string isn't fully converted, return
625 * -EINVAL. This is the case when the pointer that would be stored in
626 * a non-null @endptr points to a character other than '\0'.
628 * If the conversion overflows, store +/-HUGE_VAL in @result, depending
629 * on the sign, and return -ERANGE.
631 * If the conversion underflows, store +/-0.0 in @result, depending on the
632 * sign, and return -ERANGE.
634 * Else store the converted value in @result, and return zero.
636 int qemu_strtod(const char *nptr
, const char **endptr
, double *result
)
648 *result
= strtod(nptr
, &ep
);
649 return check_strtox_error(nptr
, ep
, endptr
, false, errno
);
653 * Convert string @nptr to a finite double.
655 * Works like qemu_strtod(), except that "NaN" and "inf" are rejected
656 * with -EINVAL and no conversion is performed.
658 int qemu_strtod_finite(const char *nptr
, const char **endptr
, double *result
)
663 ret
= qemu_strtod(nptr
, endptr
, &tmp
);
664 if (!ret
&& !isfinite(tmp
)) {
671 if (ret
!= -EINVAL
) {
678 * Searches for the first occurrence of 'c' in 's', and returns a pointer
679 * to the trailing null byte if none was found.
681 #ifndef HAVE_STRCHRNUL
682 const char *qemu_strchrnul(const char *s
, int c
)
684 const char *e
= strchr(s
, c
);
695 * @s: String to parse
696 * @value: Destination for parsed integer value
697 * @endptr: Destination for pointer to first character not consumed
698 * @base: integer base, between 2 and 36 inclusive, or 0
700 * Parse unsigned integer
702 * Parsed syntax is like strtoull()'s: arbitrary whitespace, a single optional
703 * '+' or '-', an optional "0x" if @base is 0 or 16, one or more digits.
705 * If @s is null, or @base is invalid, or @s doesn't start with an
706 * integer in the syntax above, set *@value to 0, *@endptr to @s, and
709 * Set *@endptr to point right beyond the parsed integer (even if the integer
710 * overflows or is negative, all digits will be parsed and *@endptr will
711 * point right beyond them).
713 * If the integer is negative, set *@value to 0, and return -ERANGE.
715 * If the integer overflows unsigned long long, set *@value to
716 * ULLONG_MAX, and return -ERANGE.
718 * Else, set *@value to the parsed integer, and return 0.
720 int parse_uint(const char *s
, unsigned long long *value
, char **endptr
,
724 char *endp
= (char *)s
;
725 unsigned long long val
= 0;
727 assert((unsigned) base
<= 36 && base
!= 1);
734 val
= strtoull(s
, &endp
, base
);
745 /* make sure we reject negative numbers: */
746 while (qemu_isspace(*s
)) {
764 * @s: String to parse
765 * @value: Destination for parsed integer value
766 * @base: integer base, between 2 and 36 inclusive, or 0
768 * Parse unsigned integer from entire string
770 * Have the same behavior of parse_uint(), but with an additional check
771 * for additional data after the parsed number. If extra characters are present
772 * after the parsed number, the function will return -EINVAL, and *@v will
775 int parse_uint_full(const char *s
, unsigned long long *value
, int base
)
780 r
= parse_uint(s
, value
, &endp
, base
);
792 int qemu_parse_fd(const char *param
)
798 fd
= strtol(param
, &endptr
, 10);
799 if (param
== endptr
/* no conversion performed */ ||
800 errno
!= 0 /* not representable as long; possibly others */ ||
801 *endptr
!= '\0' /* final string not empty */ ||
802 fd
< 0 /* invalid as file descriptor */ ||
803 fd
> INT_MAX
/* not representable as int */) {
810 * Implementation of ULEB128 (http://en.wikipedia.org/wiki/LEB128)
811 * Input is limited to 14-bit numbers
813 int uleb128_encode_small(uint8_t *out
, uint32_t n
)
815 g_assert(n
<= 0x3fff);
820 *out
++ = (n
& 0x7f) | 0x80;
826 int uleb128_decode_small(const uint8_t *in
, uint32_t *n
)
833 /* we exceed 14 bit number */
843 * helper to parse debug environment variables
845 int parse_debug_env(const char *name
, int max
, int initial
)
847 char *debug_env
= getenv(name
);
855 debug
= strtol(debug_env
, &inv
, 10);
856 if (inv
== debug_env
) {
859 if (debug
< 0 || debug
> max
|| errno
!= 0) {
860 warn_report("%s not in [0, %d]", name
, max
);
867 * Return human readable string for size @val.
868 * @val can be anything that uint64_t allows (no more than "16 EiB").
869 * Use IEC binary units like KiB, MiB, and so forth.
870 * Caller is responsible for passing it to g_free().
872 char *size_to_str(uint64_t val
)
874 static const char *suffixes
[] = { "", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei" };
879 * The exponent (returned in i) minus one gives us
880 * floor(log2(val * 1024 / 1000). The correction makes us
881 * switch to the higher power when the integer part is >= 1000.
882 * (see e41b509d68afb1f for more info)
884 frexp(val
/ (1000.0 / 1024.0), &i
);
886 div
= 1ULL << (i
* 10);
888 return g_strdup_printf("%0.3g %sB", (double)val
/ div
, suffixes
[i
]);
891 char *freq_to_str(uint64_t freq_hz
)
893 static const char *const suffixes
[] = { "", "K", "M", "G", "T", "P", "E" };
894 double freq
= freq_hz
;
897 while (freq
>= 1000.0) {
901 assert(idx
< ARRAY_SIZE(suffixes
));
903 return g_strdup_printf("%0.3g %sHz", freq
, suffixes
[idx
]);
906 int qemu_pstrcmp0(const char **str1
, const char **str2
)
908 return g_strcmp0(*str1
, *str2
);
911 static inline bool starts_with_prefix(const char *dir
)
913 size_t prefix_len
= strlen(CONFIG_PREFIX
);
914 return !memcmp(dir
, CONFIG_PREFIX
, prefix_len
) &&
915 (!dir
[prefix_len
] || G_IS_DIR_SEPARATOR(dir
[prefix_len
]));
918 /* Return the next path component in dir, and store its length in *p_len. */
919 static inline const char *next_component(const char *dir
, int *p_len
)
922 while ((*dir
&& G_IS_DIR_SEPARATOR(*dir
)) ||
923 (*dir
== '.' && (G_IS_DIR_SEPARATOR(dir
[1]) || dir
[1] == '\0'))) {
927 while (dir
[len
] && !G_IS_DIR_SEPARATOR(dir
[len
])) {
934 char *get_relocated_path(const char *dir
)
936 size_t prefix_len
= strlen(CONFIG_PREFIX
);
937 const char *bindir
= CONFIG_BINDIR
;
938 const char *exec_dir
= qemu_get_exec_dir();
940 int len_dir
, len_bindir
;
942 /* Fail if qemu_init_exec_dir was not called. */
944 if (!starts_with_prefix(dir
) || !starts_with_prefix(bindir
)) {
945 return g_strdup(dir
);
948 result
= g_string_new(exec_dir
);
950 /* Advance over common components. */
951 len_dir
= len_bindir
= prefix_len
;
954 bindir
+= len_bindir
;
955 dir
= next_component(dir
, &len_dir
);
956 bindir
= next_component(bindir
, &len_bindir
);
957 } while (len_dir
&& len_dir
== len_bindir
&& !memcmp(dir
, bindir
, len_dir
));
959 /* Ascend from bindir to the common prefix with dir. */
961 bindir
+= len_bindir
;
962 g_string_append(result
, "/..");
963 bindir
= next_component(bindir
, &len_bindir
);
967 assert(G_IS_DIR_SEPARATOR(dir
[-1]));
968 g_string_append(result
, dir
- 1);
970 return g_string_free(result
, false);