1 /* SPDX-License-Identifier: GPL-2.0 */
7 int atoi64(const char *str, int64_t *value)
12 errno = 0; /* To distinguish success/failure after call */
13 tmp = strtoll(str, &endptr, 10);
14 if (errno == ERANGE && (tmp == LLONG_MAX || tmp == LLONG_MIN))
15 return -E_ATOI_OVERFLOW;
17 * If there were no digits at all, strtoll() stores the original value
21 return -E_ATOI_NO_DIGITS;
23 * The implementation may also set errno and return 0 in case no
24 * conversion was performed.
26 if (errno != 0 && tmp == 0)
27 return -E_ATOI_NO_DIGITS;
28 if (*endptr != '\0') /* Further characters after number */
29 return -E_ATOI_JUNK_AT_END;
34 __attribute__ ((warn_unused_result))
35 void *xrealloc(void *p, size_t size)
38 * No need to check for NULL pointers: If p is NULL, the call
39 * to realloc is equivalent to malloc(size)
42 if (!(p = realloc(p, size))) {
43 EMERG_LOG("realloc failed (size = %zu), aborting\n", size);
49 __attribute__ ((warn_unused_result))
50 void *xmalloc(size_t size)
52 return xrealloc(NULL, size);
55 __attribute__ ((warn_unused_result))
56 void *xcalloc(size_t size)
58 void *p = xmalloc(size);
64 * Print a formated message to a dynamically allocated string.
66 * This function is similar to vasprintf(), a GNU extension which is not in C
67 * or POSIX. It allocates a string large enough to hold the output including
68 * the terminating null byte. The allocated string is returned via the first
69 * argument and must be freed by the caller. However, unlike vasprintf(), this
70 * function calls exit() if insufficient memory is available, while vasprintf()
71 * returns -1 in this case.
73 * It returns the number of bytes written, not including the terminating \p
76 __attribute__ ((format (printf, 2, 0)))
77 unsigned xvasprintf(char **result, const char *fmt, va_list ap)
83 *result = xmalloc(size + 1);
85 ret = vsnprintf(*result, size, fmt, aq);
88 if ((size_t)ret < size)
91 *result = xrealloc(*result, size);
93 ret = vsnprintf(*result, size, fmt, aq);
95 assert(ret >= 0 && (size_t)ret < size);
99 __attribute__ ((format (printf, 2, 3)))
100 /* Print to a dynamically allocated string, variable number of arguments. */
101 unsigned xasprintf(char **result, const char *fmt, ...)
107 ret = xvasprintf(result, fmt, ap);
113 * Compile a regular expression.
115 * This simple wrapper calls regcomp(3) and logs a message on errors.
117 int xregcomp(regex_t *preg, const char *regex, int cflags)
121 int ret = regcomp(preg, regex, cflags);
125 size = regerror(ret, preg, NULL, 0);
127 regerror(ret, preg, buf, size);
128 ERROR_LOG("%s\n", buf);
133 static int loglevel_arg_val;
135 __attribute__ ((format (printf, 2, 3)))
136 void txp_log(int ll, const char* fmt,...)
139 if (ll < loglevel_arg_val)
142 vfprintf(stderr, fmt, argp);