cpu: Avoid QOM casts for CPU()
[qemu/ar7.git] / util / cutils.c
blobb3372932390564e5f665e39c6ea09dc0a3dfbef8
1 /*
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
22 * THE SOFTWARE.
24 #include "qemu-common.h"
25 #include "qemu/host-utils.h"
26 #include <math.h>
28 #include "qemu/sockets.h"
29 #include "qemu/iov.h"
30 #include "net/net.h"
32 void strpadcpy(char *buf, int buf_size, const char *str, char pad)
34 int len = qemu_strnlen(str, buf_size);
35 memcpy(buf, str, len);
36 memset(buf + len, pad, buf_size - len);
39 void pstrcpy(char *buf, int buf_size, const char *str)
41 int c;
42 char *q = buf;
44 if (buf_size <= 0)
45 return;
47 for(;;) {
48 c = *str++;
49 if (c == 0 || q >= buf + buf_size - 1)
50 break;
51 *q++ = c;
53 *q = '\0';
56 /* strcat and truncate. */
57 char *pstrcat(char *buf, int buf_size, const char *s)
59 int len;
60 len = strlen(buf);
61 if (len < buf_size)
62 pstrcpy(buf + len, buf_size - len, s);
63 return buf;
66 int strstart(const char *str, const char *val, const char **ptr)
68 const char *p, *q;
69 p = str;
70 q = val;
71 while (*q != '\0') {
72 if (*p != *q)
73 return 0;
74 p++;
75 q++;
77 if (ptr)
78 *ptr = p;
79 return 1;
82 int stristart(const char *str, const char *val, const char **ptr)
84 const char *p, *q;
85 p = str;
86 q = val;
87 while (*q != '\0') {
88 if (qemu_toupper(*p) != qemu_toupper(*q))
89 return 0;
90 p++;
91 q++;
93 if (ptr)
94 *ptr = p;
95 return 1;
98 /* XXX: use host strnlen if available ? */
99 int qemu_strnlen(const char *s, int max_len)
101 int i;
103 for(i = 0; i < max_len; i++) {
104 if (s[i] == '\0') {
105 break;
108 return i;
111 char *qemu_strsep(char **input, const char *delim)
113 char *result = *input;
114 if (result != NULL) {
115 char *p;
117 for (p = result; *p != '\0'; p++) {
118 if (strchr(delim, *p)) {
119 break;
122 if (*p == '\0') {
123 *input = NULL;
124 } else {
125 *p = '\0';
126 *input = p + 1;
129 return result;
132 time_t mktimegm(struct tm *tm)
134 time_t t;
135 int y = tm->tm_year + 1900, m = tm->tm_mon + 1, d = tm->tm_mday;
136 if (m < 3) {
137 m += 12;
138 y--;
140 t = 86400ULL * (d + (153 * m - 457) / 5 + 365 * y + y / 4 - y / 100 +
141 y / 400 - 719469);
142 t += 3600 * tm->tm_hour + 60 * tm->tm_min + tm->tm_sec;
143 return t;
146 int qemu_fls(int i)
148 return 32 - clz32(i);
152 * Make sure data goes on disk, but if possible do not bother to
153 * write out the inode just for timestamp updates.
155 * Unfortunately even in 2009 many operating systems do not support
156 * fdatasync and have to fall back to fsync.
158 int qemu_fdatasync(int fd)
160 #ifdef CONFIG_FDATASYNC
161 return fdatasync(fd);
162 #else
163 return fsync(fd);
164 #endif
168 * Searches for an area with non-zero content in a buffer
170 * Attention! The len must be a multiple of
171 * BUFFER_FIND_NONZERO_OFFSET_UNROLL_FACTOR * sizeof(VECTYPE)
172 * and addr must be a multiple of sizeof(VECTYPE) due to
173 * restriction of optimizations in this function.
175 * can_use_buffer_find_nonzero_offset() can be used to check
176 * these requirements.
178 * The return value is the offset of the non-zero area rounded
179 * down to a multiple of sizeof(VECTYPE) for the first
180 * BUFFER_FIND_NONZERO_OFFSET_UNROLL_FACTOR chunks and down to
181 * BUFFER_FIND_NONZERO_OFFSET_UNROLL_FACTOR * sizeof(VECTYPE)
182 * afterwards.
184 * If the buffer is all zero the return value is equal to len.
187 size_t buffer_find_nonzero_offset(const void *buf, size_t len)
189 const VECTYPE *p = buf;
190 const VECTYPE zero = (VECTYPE){0};
191 size_t i;
193 assert(can_use_buffer_find_nonzero_offset(buf, len));
195 if (!len) {
196 return 0;
199 for (i = 0; i < BUFFER_FIND_NONZERO_OFFSET_UNROLL_FACTOR; i++) {
200 if (!ALL_EQ(p[i], zero)) {
201 return i * sizeof(VECTYPE);
205 for (i = BUFFER_FIND_NONZERO_OFFSET_UNROLL_FACTOR;
206 i < len / sizeof(VECTYPE);
207 i += BUFFER_FIND_NONZERO_OFFSET_UNROLL_FACTOR) {
208 VECTYPE tmp0 = p[i + 0] | p[i + 1];
209 VECTYPE tmp1 = p[i + 2] | p[i + 3];
210 VECTYPE tmp2 = p[i + 4] | p[i + 5];
211 VECTYPE tmp3 = p[i + 6] | p[i + 7];
212 VECTYPE tmp01 = tmp0 | tmp1;
213 VECTYPE tmp23 = tmp2 | tmp3;
214 if (!ALL_EQ(tmp01 | tmp23, zero)) {
215 break;
219 return i * sizeof(VECTYPE);
223 * Checks if a buffer is all zeroes
225 * Attention! The len must be a multiple of 4 * sizeof(long) due to
226 * restriction of optimizations in this function.
228 bool buffer_is_zero(const void *buf, size_t len)
231 * Use long as the biggest available internal data type that fits into the
232 * CPU register and unroll the loop to smooth out the effect of memory
233 * latency.
236 size_t i;
237 long d0, d1, d2, d3;
238 const long * const data = buf;
240 /* use vector optimized zero check if possible */
241 if (can_use_buffer_find_nonzero_offset(buf, len)) {
242 return buffer_find_nonzero_offset(buf, len) == len;
245 assert(len % (4 * sizeof(long)) == 0);
246 len /= sizeof(long);
248 for (i = 0; i < len; i += 4) {
249 d0 = data[i + 0];
250 d1 = data[i + 1];
251 d2 = data[i + 2];
252 d3 = data[i + 3];
254 if (d0 || d1 || d2 || d3) {
255 return false;
259 return true;
262 #ifndef _WIN32
263 /* Sets a specific flag */
264 int fcntl_setfl(int fd, int flag)
266 int flags;
268 flags = fcntl(fd, F_GETFL);
269 if (flags == -1)
270 return -errno;
272 if (fcntl(fd, F_SETFL, flags | flag) == -1)
273 return -errno;
275 return 0;
277 #endif
279 static int64_t suffix_mul(char suffix, int64_t unit)
281 switch (qemu_toupper(suffix)) {
282 case STRTOSZ_DEFSUFFIX_B:
283 return 1;
284 case STRTOSZ_DEFSUFFIX_KB:
285 return unit;
286 case STRTOSZ_DEFSUFFIX_MB:
287 return unit * unit;
288 case STRTOSZ_DEFSUFFIX_GB:
289 return unit * unit * unit;
290 case STRTOSZ_DEFSUFFIX_TB:
291 return unit * unit * unit * unit;
292 case STRTOSZ_DEFSUFFIX_PB:
293 return unit * unit * unit * unit * unit;
294 case STRTOSZ_DEFSUFFIX_EB:
295 return unit * unit * unit * unit * unit * unit;
297 return -1;
301 * Convert string to bytes, allowing either B/b for bytes, K/k for KB,
302 * M/m for MB, G/g for GB or T/t for TB. End pointer will be returned
303 * in *end, if not NULL. Return -ERANGE on overflow, Return -EINVAL on
304 * other error.
306 int64_t strtosz_suffix_unit(const char *nptr, char **end,
307 const char default_suffix, int64_t unit)
309 int64_t retval = -EINVAL;
310 char *endptr;
311 unsigned char c;
312 int mul_required = 0;
313 double val, mul, integral, fraction;
315 errno = 0;
316 val = strtod(nptr, &endptr);
317 if (isnan(val) || endptr == nptr || errno != 0) {
318 goto fail;
320 fraction = modf(val, &integral);
321 if (fraction != 0) {
322 mul_required = 1;
324 c = *endptr;
325 mul = suffix_mul(c, unit);
326 if (mul >= 0) {
327 endptr++;
328 } else {
329 mul = suffix_mul(default_suffix, unit);
330 assert(mul >= 0);
332 if (mul == 1 && mul_required) {
333 goto fail;
335 if ((val * mul >= INT64_MAX) || val < 0) {
336 retval = -ERANGE;
337 goto fail;
339 retval = val * mul;
341 fail:
342 if (end) {
343 *end = endptr;
346 return retval;
349 int64_t strtosz_suffix(const char *nptr, char **end, const char default_suffix)
351 return strtosz_suffix_unit(nptr, end, default_suffix, 1024);
354 int64_t strtosz(const char *nptr, char **end)
356 return strtosz_suffix(nptr, end, STRTOSZ_DEFSUFFIX_MB);
360 * parse_uint:
362 * @s: String to parse
363 * @value: Destination for parsed integer value
364 * @endptr: Destination for pointer to first character not consumed
365 * @base: integer base, between 2 and 36 inclusive, or 0
367 * Parse unsigned integer
369 * Parsed syntax is like strtoull()'s: arbitrary whitespace, a single optional
370 * '+' or '-', an optional "0x" if @base is 0 or 16, one or more digits.
372 * If @s is null, or @base is invalid, or @s doesn't start with an
373 * integer in the syntax above, set *@value to 0, *@endptr to @s, and
374 * return -EINVAL.
376 * Set *@endptr to point right beyond the parsed integer (even if the integer
377 * overflows or is negative, all digits will be parsed and *@endptr will
378 * point right beyond them).
380 * If the integer is negative, set *@value to 0, and return -ERANGE.
382 * If the integer overflows unsigned long long, set *@value to
383 * ULLONG_MAX, and return -ERANGE.
385 * Else, set *@value to the parsed integer, and return 0.
387 int parse_uint(const char *s, unsigned long long *value, char **endptr,
388 int base)
390 int r = 0;
391 char *endp = (char *)s;
392 unsigned long long val = 0;
394 if (!s) {
395 r = -EINVAL;
396 goto out;
399 errno = 0;
400 val = strtoull(s, &endp, base);
401 if (errno) {
402 r = -errno;
403 goto out;
406 if (endp == s) {
407 r = -EINVAL;
408 goto out;
411 /* make sure we reject negative numbers: */
412 while (isspace((unsigned char)*s)) {
413 s++;
415 if (*s == '-') {
416 val = 0;
417 r = -ERANGE;
418 goto out;
421 out:
422 *value = val;
423 *endptr = endp;
424 return r;
428 * parse_uint_full:
430 * @s: String to parse
431 * @value: Destination for parsed integer value
432 * @base: integer base, between 2 and 36 inclusive, or 0
434 * Parse unsigned integer from entire string
436 * Have the same behavior of parse_uint(), but with an additional check
437 * for additional data after the parsed number. If extra characters are present
438 * after the parsed number, the function will return -EINVAL, and *@v will
439 * be set to 0.
441 int parse_uint_full(const char *s, unsigned long long *value, int base)
443 char *endp;
444 int r;
446 r = parse_uint(s, value, &endp, base);
447 if (r < 0) {
448 return r;
450 if (*endp) {
451 *value = 0;
452 return -EINVAL;
455 return 0;
458 int qemu_parse_fd(const char *param)
460 int fd;
461 char *endptr = NULL;
463 fd = strtol(param, &endptr, 10);
464 if (*endptr || (fd == 0 && param == endptr)) {
465 return -1;
467 return fd;
470 /* round down to the nearest power of 2*/
471 int64_t pow2floor(int64_t value)
473 if (!is_power_of_2(value)) {
474 value = 0x8000000000000000ULL >> clz64(value);
476 return value;
480 * Implementation of ULEB128 (http://en.wikipedia.org/wiki/LEB128)
481 * Input is limited to 14-bit numbers
483 int uleb128_encode_small(uint8_t *out, uint32_t n)
485 g_assert(n <= 0x3fff);
486 if (n < 0x80) {
487 *out++ = n;
488 return 1;
489 } else {
490 *out++ = (n & 0x7f) | 0x80;
491 *out++ = n >> 7;
492 return 2;
496 int uleb128_decode_small(const uint8_t *in, uint32_t *n)
498 if (!(*in & 0x80)) {
499 *n = *in++;
500 return 1;
501 } else {
502 *n = *in++ & 0x7f;
503 /* we exceed 14 bit number */
504 if (*in & 0x80) {
505 return -1;
507 *n |= *in++ << 7;
508 return 2;
513 * helper to parse debug environment variables
515 int parse_debug_env(const char *name, int max, int initial)
517 char *debug_env = getenv(name);
518 char *inv = NULL;
519 int debug;
521 if (!debug_env) {
522 return initial;
524 debug = strtol(debug_env, &inv, 10);
525 if (inv == debug_env) {
526 return initial;
528 if (debug < 0 || debug > max) {
529 fprintf(stderr, "warning: %s not in [0, %d]", name, max);
530 return initial;
532 return debug;
536 * Helper to print ethernet mac address
538 const char *qemu_ether_ntoa(const MACAddr *mac)
540 static char ret[18];
542 snprintf(ret, sizeof(ret), "%02x:%02x:%02x:%02x:%02x:%02x",
543 mac->a[0], mac->a[1], mac->a[2], mac->a[3], mac->a[4], mac->a[5]);
545 return ret;