Back to home page

OSCL-LXR

 
 

    


0001 /* SPDX-License-Identifier: GPL-2.0 */
0002 #ifndef __SUBCMD_UTIL_H
0003 #define __SUBCMD_UTIL_H
0004 
0005 #include <stdarg.h>
0006 #include <stdlib.h>
0007 #include <stdio.h>
0008 
0009 #define NORETURN __attribute__((__noreturn__))
0010 
0011 static inline void report(const char *prefix, const char *err, va_list params)
0012 {
0013     char msg[1024];
0014     vsnprintf(msg, sizeof(msg), err, params);
0015     fprintf(stderr, " %s%s\n", prefix, msg);
0016 }
0017 
0018 static NORETURN inline void die(const char *err, ...)
0019 {
0020     va_list params;
0021 
0022     va_start(params, err);
0023     report(" Fatal: ", err, params);
0024     exit(128);
0025     va_end(params);
0026 }
0027 
0028 #define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
0029 
0030 #define alloc_nr(x) (((x)+16)*3/2)
0031 
0032 /*
0033  * Realloc the buffer pointed at by variable 'x' so that it can hold
0034  * at least 'nr' entries; the number of entries currently allocated
0035  * is 'alloc', using the standard growing factor alloc_nr() macro.
0036  *
0037  * DO NOT USE any expression with side-effect for 'x' or 'alloc'.
0038  */
0039 #define ALLOC_GROW(x, nr, alloc) \
0040     do { \
0041         if ((nr) > alloc) { \
0042             if (alloc_nr(alloc) < (nr)) \
0043                 alloc = (nr); \
0044             else \
0045                 alloc = alloc_nr(alloc); \
0046             x = xrealloc((x), alloc * sizeof(*(x))); \
0047         } \
0048     } while(0)
0049 
0050 static inline void *xrealloc(void *ptr, size_t size)
0051 {
0052     void *ret = realloc(ptr, size);
0053     if (!ret)
0054         die("Out of memory, realloc failed");
0055     return ret;
0056 }
0057 
0058 #define astrcatf(out, fmt, ...)                     \
0059 ({                                  \
0060     char *tmp = *(out);                     \
0061     if (asprintf((out), "%s" fmt, tmp ?: "", ## __VA_ARGS__) == -1) \
0062         die("asprintf failed");                 \
0063     free(tmp);                          \
0064 })
0065 
0066 static inline void astrcat(char **out, const char *add)
0067 {
0068     char *tmp = *out;
0069 
0070     if (asprintf(out, "%s%s", tmp ?: "", add) == -1)
0071         die("asprintf failed");
0072 
0073     free(tmp);
0074 }
0075 
0076 #endif /* __SUBCMD_UTIL_H */