1 /*
2  * Copyright © 2012 Ran Benita <ran234@gmail.com>
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  */
23 
24 #ifndef UTILS_H
25 #define UTILS_H 1
26 
27 #include <errno.h>
28 #include <inttypes.h>
29 #include <stdarg.h>
30 #include <stdbool.h>
31 #include <stdio.h>
32 #include <string.h>
33 #if HAVE_UNISTD_H
34 #include <unistd.h>
35 #else
36 /* Required on Windows where unistd.h doesn't exist */
37 #define R_OK    4               /* Test for read permission.  */
38 #define W_OK    2               /* Test for write permission.  */
39 #define X_OK    1               /* Test for execute permission.  */
40 #define F_OK    0               /* Test for existence.  */
41 #endif
42 
43 #include "darray.h"
44 
45 #define STATIC_ASSERT(expr, message) do { \
46     switch (0) { case 0: case (expr): ; } \
47 } while (0)
48 
49 #define ARRAY_SIZE(arr) ((sizeof(arr) / sizeof(*(arr))))
50 
51 #define MIN(a, b) ((a) < (b) ? (a) : (b))
52 #define MAX(a, b) ((a) > (b) ? (a) : (b))
53 
54 /* Round up @a so it's divisible by @b. */
55 #define ROUNDUP(a, b) (((a) + (b) - 1) / (b) * (b))
56 
57 char
58 to_lower(char c);
59 
60 int
61 istrcmp(const char *a, const char *b);
62 
63 int
64 istrncmp(const char *a, const char *b, size_t n);
65 
66 static inline bool
streq(const char * s1,const char * s2)67 streq(const char *s1, const char *s2)
68 {
69     assert(s1 && s2);
70     return strcmp(s1, s2) == 0;
71 }
72 
73 static inline bool
streq_null(const char * s1,const char * s2)74 streq_null(const char *s1, const char *s2)
75 {
76     if (s1 == NULL || s2 == NULL)
77         return s1 == s2;
78     return streq(s1, s2);
79 }
80 
81 static inline bool
streq_not_null(const char * s1,const char * s2)82 streq_not_null(const char *s1, const char *s2)
83 {
84     if (!s1 || !s2)
85         return false;
86     return streq(s1, s2);
87 }
88 
89 static inline bool
istreq(const char * s1,const char * s2)90 istreq(const char *s1, const char *s2)
91 {
92     return istrcmp(s1, s2) == 0;
93 }
94 
95 static inline bool
istreq_prefix(const char * s1,const char * s2)96 istreq_prefix(const char *s1, const char *s2)
97 {
98     return istrncmp(s1, s2, strlen(s1)) == 0;
99 }
100 
101 static inline char *
strdup_safe(const char * s)102 strdup_safe(const char *s)
103 {
104     return s ? strdup(s) : NULL;
105 }
106 
107 static inline size_t
strlen_safe(const char * s)108 strlen_safe(const char *s)
109 {
110     return s ? strlen(s) : 0;
111 }
112 
113 static inline bool
isempty(const char * s)114 isempty(const char *s)
115 {
116     return s == NULL || s[0] == '\0';
117 }
118 
119 static inline const char *
strnull(const char * s)120 strnull(const char *s)
121 {
122     return s ? s : "(null)";
123 }
124 
125 static inline const char *
strempty(const char * s)126 strempty(const char *s)
127 {
128     return s ? s : "";
129 }
130 
131 static inline void *
memdup(const void * mem,size_t nmemb,size_t size)132 memdup(const void *mem, size_t nmemb, size_t size)
133 {
134     void *p = calloc(nmemb, size);
135     if (p)
136         memcpy(p, mem, nmemb * size);
137     return p;
138 }
139 
140 #if !(defined(HAVE_STRNDUP) && HAVE_STRNDUP)
141 static inline char *
strndup(const char * s,size_t n)142 strndup(const char *s, size_t n)
143 {
144     size_t slen = strlen(s);
145     size_t len = MIN(slen, n);
146     char *p = malloc(len + 1);
147     if (!p)
148         return NULL;
149     memcpy(p, s, len);
150     p[len] = '\0';
151     return p;
152 }
153 #endif
154 
155 /* ctype.h is locale-dependent and has other oddities. */
156 static inline bool
is_space(char ch)157 is_space(char ch)
158 {
159     return ch == ' ' || (ch >= '\t' && ch <= '\r');
160 }
161 
162 static inline bool
is_alpha(char ch)163 is_alpha(char ch)
164 {
165     return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');
166 }
167 
168 static inline bool
is_digit(char ch)169 is_digit(char ch)
170 {
171     return ch >= '0' && ch <= '9';
172 }
173 
174 static inline bool
is_alnum(char ch)175 is_alnum(char ch)
176 {
177     return is_alpha(ch) || is_digit(ch);
178 }
179 
180 static inline bool
is_xdigit(char ch)181 is_xdigit(char ch)
182 {
183     return
184         (ch >= '0' && ch <= '9') ||
185         (ch >= 'a' && ch <= 'f') ||
186         (ch >= 'A' && ch <= 'F');
187 }
188 
189 static inline bool
is_graph(char ch)190 is_graph(char ch)
191 {
192     /* See table in ascii(7). */
193     return ch >= '!' && ch <= '~';
194 }
195 
196 /*
197  * Return the bit position of the most significant bit.
198  * Note: this is 1-based! It's more useful this way, and returns 0 when
199  * mask is all 0s.
200  */
201 static inline unsigned
msb_pos(uint32_t mask)202 msb_pos(uint32_t mask)
203 {
204     unsigned pos = 0;
205     while (mask) {
206         pos++;
207         mask >>= 1u;
208     }
209     return pos;
210 }
211 
212 static inline int
one_bit_set(uint32_t x)213 one_bit_set(uint32_t x)
214 {
215     return x && (x & (x - 1)) == 0;
216 }
217 
218 bool
219 map_file(FILE *file, char **string_out, size_t *size_out);
220 
221 void
222 unmap_file(char *string, size_t size);
223 
224 static inline bool
check_eaccess(const char * path,int mode)225 check_eaccess(const char *path, int mode)
226 {
227 #if defined(HAVE_EACCESS)
228     if (eaccess(path, mode) != 0)
229         return false;
230 #elif defined(HAVE_EUIDACCESS)
231     if (euidaccess(path, mode) != 0)
232         return false;
233 #endif
234 
235     return true;
236 }
237 
238 #if defined(HAVE_SECURE_GETENV)
239 # define secure_getenv secure_getenv
240 #elif defined(HAVE___SECURE_GETENV)
241 # define secure_getenv __secure_getenv
242 #else
243 # define secure_getenv getenv
244 #endif
245 
246 #if defined(HAVE___BUILTIN_EXPECT)
247 # define likely(x)   __builtin_expect(!!(x), 1)
248 # define unlikely(x) __builtin_expect(!!(x), 0)
249 #else
250 # define likely(x)   (x)
251 # define unlikely(x) (x)
252 #endif
253 
254 /* Compiler Attributes */
255 
256 #if defined(__GNUC__) && (__GNUC__ >= 4) && !defined(__CYGWIN__)
257 # define XKB_EXPORT      __attribute__((visibility("default")))
258 #elif defined(__SUNPRO_C) && (__SUNPRO_C >= 0x550)
259 # define XKB_EXPORT      __global
260 #else /* not gcc >= 4 and not Sun Studio >= 8 */
261 # define XKB_EXPORT
262 #endif
263 
264 #if defined(__GNUC__) && ((__GNUC__ * 100 + __GNUC_MINOR__) >= 203)
265 # define ATTR_PRINTF(x,y) __attribute__((__format__(__printf__, x, y)))
266 #else /* not gcc >= 2.3 */
267 # define ATTR_PRINTF(x,y)
268 #endif
269 
270 #if (defined(__GNUC__) && ((__GNUC__ * 100 + __GNUC_MINOR__) >= 205)) \
271     || (defined(__SUNPRO_C) && (__SUNPRO_C >= 0x590))
272 # define ATTR_NORETURN __attribute__((__noreturn__))
273 #else
274 # define ATTR_NORETURN
275 #endif /* GNUC  */
276 
277 #if (defined(__GNUC__) && (__GNUC__ * 100 + __GNUC_MINOR__) >= 296)
278 #define ATTR_MALLOC  __attribute__((__malloc__))
279 #else
280 #define ATTR_MALLOC
281 #endif
282 
283 #if defined(__GNUC__) && (__GNUC__ >= 4)
284 # define ATTR_NULL_SENTINEL __attribute__((__sentinel__))
285 #else
286 # define ATTR_NULL_SENTINEL
287 #endif /* GNUC >= 4 */
288 
289 #if (defined(__GNUC__) && (__GNUC__ * 100 + __GNUC_MINOR__) >= 295)
290 #define ATTR_PACKED  __attribute__((__packed__))
291 #else
292 #define ATTR_PACKED
293 #endif
294 
295 #if !(defined(HAVE_ASPRINTF) && HAVE_ASPRINTF)
296 int asprintf(char **strp, const char *fmt, ...) ATTR_PRINTF(2, 3);
297 # if !(defined(HAVE_VASPRINTF) && HAVE_VASPRINTF)
298 #  include <stdarg.h>
299 int vasprintf(char **strp, const char *fmt, va_list ap);
300 # endif /* !HAVE_VASPRINTF */
301 #endif /* !HAVE_ASPRINTF */
302 
303 static inline bool
304 ATTR_PRINTF(3, 4)
snprintf_safe(char * buf,size_t sz,const char * format,...)305 snprintf_safe(char *buf, size_t sz, const char *format, ...)
306 {
307     va_list ap;
308     int rc;
309 
310     va_start(ap, format);
311     rc = vsnprintf(buf, sz, format, ap);
312     va_end(ap);
313 
314     return rc >= 0 && (size_t)rc < sz;
315 }
316 
317 static inline char *
318 ATTR_PRINTF(1, 0)
vasprintf_safe(const char * fmt,va_list args)319 vasprintf_safe(const char *fmt, va_list args)
320 {
321     char *str;
322     int len;
323 
324     len = vasprintf(&str, fmt, args);
325 
326     if (len == -1)
327         return NULL;
328 
329     return str;
330 }
331 
332 /**
333  * A version of asprintf that returns the allocated string or NULL on error.
334  */
335 static inline char *
336 ATTR_PRINTF(1, 2)
asprintf_safe(const char * fmt,...)337 asprintf_safe(const char *fmt, ...)
338 {
339     va_list args;
340     char *str;
341 
342     va_start(args, fmt);
343     str = vasprintf_safe(fmt, args);
344     va_end(args);
345 
346     return str;
347 }
348 
349 #endif /* UTILS_H */
350