1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2 #pragma once
3 
4 #include <assert.h>
5 #include <errno.h>
6 #include <inttypes.h>
7 #include <stdbool.h>
8 #include <sys/param.h>
9 #include <sys/sysmacros.h>
10 #include <sys/types.h>
11 
12 #include "macro-fundamental.h"
13 
14 #define _printf_(a, b) __attribute__((__format__(printf, a, b)))
15 #ifdef __clang__
16 #  define _alloc_(...)
17 #else
18 #  define _alloc_(...) __attribute__((__alloc_size__(__VA_ARGS__)))
19 #endif
20 #define _sentinel_ __attribute__((__sentinel__))
21 #define _destructor_ __attribute__((__destructor__))
22 #define _deprecated_ __attribute__((__deprecated__))
23 #define _malloc_ __attribute__((__malloc__))
24 #define _weak_ __attribute__((__weak__))
25 #define _public_ __attribute__((__visibility__("default")))
26 #define _hidden_ __attribute__((__visibility__("hidden")))
27 #define _weakref_(x) __attribute__((__weakref__(#x)))
28 #define _alignas_(x) __attribute__((__aligned__(__alignof__(x))))
29 #define _alignptr_ __attribute__((__aligned__(sizeof(void*))))
30 #define _warn_unused_result_ __attribute__((__warn_unused_result__))
31 
32 #if !defined(HAS_FEATURE_MEMORY_SANITIZER)
33 #  if defined(__has_feature)
34 #    if __has_feature(memory_sanitizer)
35 #      define HAS_FEATURE_MEMORY_SANITIZER 1
36 #    endif
37 #  endif
38 #  if !defined(HAS_FEATURE_MEMORY_SANITIZER)
39 #    define HAS_FEATURE_MEMORY_SANITIZER 0
40 #  endif
41 #endif
42 
43 #if !defined(HAS_FEATURE_ADDRESS_SANITIZER)
44 #  ifdef __SANITIZE_ADDRESS__
45 #      define HAS_FEATURE_ADDRESS_SANITIZER 1
46 #  elif defined(__has_feature)
47 #    if __has_feature(address_sanitizer)
48 #      define HAS_FEATURE_ADDRESS_SANITIZER 1
49 #    endif
50 #  endif
51 #  if !defined(HAS_FEATURE_ADDRESS_SANITIZER)
52 #    define HAS_FEATURE_ADDRESS_SANITIZER 0
53 #  endif
54 #endif
55 
56 /* Note: on GCC "no_sanitize_address" is a function attribute only, on llvm it may also be applied to global
57  * variables. We define a specific macro which knows this. Note that on GCC we don't need this decorator so much, since
58  * our primary usecase for this attribute is registration structures placed in named ELF sections which shall not be
59  * padded, but GCC doesn't pad those anyway if AddressSanitizer is enabled. */
60 #if HAS_FEATURE_ADDRESS_SANITIZER && defined(__clang__)
61 #define _variable_no_sanitize_address_ __attribute__((__no_sanitize_address__))
62 #else
63 #define _variable_no_sanitize_address_
64 #endif
65 
66 /* Apparently there's no has_feature() call defined to check for ubsan, hence let's define this
67  * unconditionally on llvm */
68 #if defined(__clang__)
69 #define _function_no_sanitize_float_cast_overflow_ __attribute__((no_sanitize("float-cast-overflow")))
70 #else
71 #define _function_no_sanitize_float_cast_overflow_
72 #endif
73 
74 /* Temporarily disable some warnings */
75 #define DISABLE_WARNING_DEPRECATED_DECLARATIONS                         \
76         _Pragma("GCC diagnostic push");                                 \
77         _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
78 
79 #define DISABLE_WARNING_FORMAT_NONLITERAL                               \
80         _Pragma("GCC diagnostic push");                                 \
81         _Pragma("GCC diagnostic ignored \"-Wformat-nonliteral\"")
82 
83 #define DISABLE_WARNING_MISSING_PROTOTYPES                              \
84         _Pragma("GCC diagnostic push");                                 \
85         _Pragma("GCC diagnostic ignored \"-Wmissing-prototypes\"")
86 
87 #define DISABLE_WARNING_NONNULL                                         \
88         _Pragma("GCC diagnostic push");                                 \
89         _Pragma("GCC diagnostic ignored \"-Wnonnull\"")
90 
91 #define DISABLE_WARNING_SHADOW                                          \
92         _Pragma("GCC diagnostic push");                                 \
93         _Pragma("GCC diagnostic ignored \"-Wshadow\"")
94 
95 #define DISABLE_WARNING_INCOMPATIBLE_POINTER_TYPES                      \
96         _Pragma("GCC diagnostic push");                                 \
97         _Pragma("GCC diagnostic ignored \"-Wincompatible-pointer-types\"")
98 
99 #if HAVE_WSTRINGOP_TRUNCATION
100 #  define DISABLE_WARNING_STRINGOP_TRUNCATION                           \
101         _Pragma("GCC diagnostic push");                                 \
102         _Pragma("GCC diagnostic ignored \"-Wstringop-truncation\"")
103 #else
104 #  define DISABLE_WARNING_STRINGOP_TRUNCATION                           \
105         _Pragma("GCC diagnostic push")
106 #endif
107 
108 #define DISABLE_WARNING_FLOAT_EQUAL \
109         _Pragma("GCC diagnostic push");                                 \
110         _Pragma("GCC diagnostic ignored \"-Wfloat-equal\"")
111 
112 #define DISABLE_WARNING_TYPE_LIMITS \
113         _Pragma("GCC diagnostic push");                                 \
114         _Pragma("GCC diagnostic ignored \"-Wtype-limits\"")
115 
116 #define REENABLE_WARNING                                                \
117         _Pragma("GCC diagnostic pop")
118 
119 /* automake test harness */
120 #define EXIT_TEST_SKIP 77
121 
122 /* builtins */
123 #if __SIZEOF_INT__ == 4
124 #define BUILTIN_FFS_U32(x) __builtin_ffs(x);
125 #elif __SIZEOF_LONG__ == 4
126 #define BUILTIN_FFS_U32(x) __builtin_ffsl(x);
127 #else
128 #error "neither int nor long are four bytes long?!?"
129 #endif
130 
131 /* Rounds up */
132 
133 #define ALIGN4(l) (((l) + 3) & ~3)
134 #define ALIGN8(l) (((l) + 7) & ~7)
135 
136 #if __SIZEOF_POINTER__ == 8
137 #define ALIGN(l) ALIGN8(l)
138 #elif __SIZEOF_POINTER__ == 4
139 #define ALIGN(l) ALIGN4(l)
140 #else
141 #error "Wut? Pointers are neither 4 nor 8 bytes long?"
142 #endif
143 
144 #define ALIGN_PTR(p) ((void*) ALIGN((unsigned long) (p)))
145 #define ALIGN4_PTR(p) ((void*) ALIGN4((unsigned long) (p)))
146 #define ALIGN8_PTR(p) ((void*) ALIGN8((unsigned long) (p)))
147 
148 #define ALIGN_TO_PTR(p, ali) ((void*) ALIGN_TO((unsigned long) (p), (ali)))
149 
150 /* align to next higher power-of-2 (except for: 0 => 0, overflow => 0) */
ALIGN_POWER2(unsigned long u)151 static inline unsigned long ALIGN_POWER2(unsigned long u) {
152 
153         /* Avoid subtraction overflow */
154         if (u == 0)
155                 return 0;
156 
157         /* clz(0) is undefined */
158         if (u == 1)
159                 return 1;
160 
161         /* left-shift overflow is undefined */
162         if (__builtin_clzl(u - 1UL) < 1)
163                 return 0;
164 
165         return 1UL << (sizeof(u) * 8 - __builtin_clzl(u - 1UL));
166 }
167 
GREEDY_ALLOC_ROUND_UP(size_t l)168 static inline size_t GREEDY_ALLOC_ROUND_UP(size_t l) {
169         size_t m;
170 
171         /* Round up allocation sizes a bit to some reasonable, likely larger value. This is supposed to be
172          * used for cases which are likely called in an allocation loop of some form, i.e. that repetitively
173          * grow stuff, for example strv_extend() and suchlike.
174          *
175          * Note the difference to GREEDY_REALLOC() here, as this helper operates on a single size value only,
176          * and rounds up to next multiple of 2, needing no further counter.
177          *
178          * Note the benefits of direct ALIGN_POWER2() usage: type-safety for size_t, sane handling for very
179          * small (i.e. <= 2) and safe handling for very large (i.e. > SSIZE_MAX) values. */
180 
181         if (l <= 2)
182                 return 2; /* Never allocate less than 2 of something.  */
183 
184         m = ALIGN_POWER2(l);
185         if (m == 0) /* overflow? */
186                 return l;
187 
188         return m;
189 }
190 
191 /*
192  * container_of - cast a member of a structure out to the containing structure
193  * @ptr: the pointer to the member.
194  * @type: the type of the container struct this is embedded in.
195  * @member: the name of the member within the struct.
196  */
197 #define container_of(ptr, type, member) __container_of(UNIQ, (ptr), type, member)
198 #define __container_of(uniq, ptr, type, member)                         \
199         ({                                                              \
200                 const typeof( ((type*)0)->member ) *UNIQ_T(A, uniq) = (ptr); \
201                 (type*)( (char *)UNIQ_T(A, uniq) - offsetof(type, member) ); \
202         })
203 
204 #ifdef __COVERITY__
205 
206 /* Use special definitions of assertion macros in order to prevent
207  * false positives of ASSERT_SIDE_EFFECT on Coverity static analyzer
208  * for uses of assert_se() and assert_return().
209  *
210  * These definitions make expression go through a (trivial) function
211  * call to ensure they are not discarded. Also use ! or !! to ensure
212  * the boolean expressions are seen as such.
213  *
214  * This technique has been described and recommended in:
215  * https://community.synopsys.com/s/question/0D534000046Yuzb/suppressing-assertsideeffect-for-functions-that-allow-for-sideeffects
216  */
217 
218 extern void __coverity_panic__(void);
219 
__coverity_check__(int condition)220 static inline void __coverity_check__(int condition) {
221         if (!condition)
222                 __coverity_panic__();
223 }
224 
__coverity_check_and_return__(int condition)225 static inline int __coverity_check_and_return__(int condition) {
226         return condition;
227 }
228 
229 #define assert_message_se(expr, message) __coverity_check__(!!(expr))
230 
231 #define assert_log(expr, message) __coverity_check_and_return__(!!(expr))
232 
233 #else  /* ! __COVERITY__ */
234 
235 #define assert_message_se(expr, message)                                \
236         do {                                                            \
237                 if (_unlikely_(!(expr)))                                \
238                         log_assert_failed(message, PROJECT_FILE, __LINE__, __PRETTY_FUNCTION__); \
239         } while (false)
240 
241 #define assert_log(expr, message) ((_likely_(expr))                     \
242         ? (true)                                                        \
243         : (log_assert_failed_return(message, PROJECT_FILE, __LINE__, __PRETTY_FUNCTION__), false))
244 
245 #endif  /* __COVERITY__ */
246 
247 #define assert_se(expr) assert_message_se(expr, #expr)
248 
249 /* We override the glibc assert() here. */
250 #undef assert
251 #ifdef NDEBUG
252 #define assert(expr) do {} while (false)
253 #else
254 #define assert(expr) assert_message_se(expr, #expr)
255 #endif
256 
257 #define assert_not_reached()                                            \
258         log_assert_failed_unreachable(PROJECT_FILE, __LINE__, __PRETTY_FUNCTION__)
259 
260 #define assert_return(expr, r)                                          \
261         do {                                                            \
262                 if (!assert_log(expr, #expr))                           \
263                         return (r);                                     \
264         } while (false)
265 
266 #define assert_return_errno(expr, r, err)                               \
267         do {                                                            \
268                 if (!assert_log(expr, #expr)) {                         \
269                         errno = err;                                    \
270                         return (r);                                     \
271                 }                                                       \
272         } while (false)
273 
274 #define return_with_errno(r, err)                     \
275         do {                                          \
276                 errno = abs(err);                     \
277                 return r;                             \
278         } while (false)
279 
280 #define PTR_TO_INT(p) ((int) ((intptr_t) (p)))
281 #define INT_TO_PTR(u) ((void *) ((intptr_t) (u)))
282 #define PTR_TO_UINT(p) ((unsigned) ((uintptr_t) (p)))
283 #define UINT_TO_PTR(u) ((void *) ((uintptr_t) (u)))
284 
285 #define PTR_TO_LONG(p) ((long) ((intptr_t) (p)))
286 #define LONG_TO_PTR(u) ((void *) ((intptr_t) (u)))
287 #define PTR_TO_ULONG(p) ((unsigned long) ((uintptr_t) (p)))
288 #define ULONG_TO_PTR(u) ((void *) ((uintptr_t) (u)))
289 
290 #define PTR_TO_UINT8(p) ((uint8_t) ((uintptr_t) (p)))
291 #define UINT8_TO_PTR(u) ((void *) ((uintptr_t) (u)))
292 
293 #define PTR_TO_INT32(p) ((int32_t) ((intptr_t) (p)))
294 #define INT32_TO_PTR(u) ((void *) ((intptr_t) (u)))
295 #define PTR_TO_UINT32(p) ((uint32_t) ((uintptr_t) (p)))
296 #define UINT32_TO_PTR(u) ((void *) ((uintptr_t) (u)))
297 
298 #define PTR_TO_INT64(p) ((int64_t) ((intptr_t) (p)))
299 #define INT64_TO_PTR(u) ((void *) ((intptr_t) (u)))
300 #define PTR_TO_UINT64(p) ((uint64_t) ((uintptr_t) (p)))
301 #define UINT64_TO_PTR(u) ((void *) ((uintptr_t) (u)))
302 
303 #define PTR_TO_SIZE(p) ((size_t) ((uintptr_t) (p)))
304 #define SIZE_TO_PTR(u) ((void *) ((uintptr_t) (u)))
305 
306 #define CHAR_TO_STR(x) ((char[2]) { x, 0 })
307 
308 #define char_array_0(x) x[sizeof(x)-1] = 0;
309 
310 #define sizeof_field(struct_type, member) sizeof(((struct_type *) 0)->member)
311 
312 /* Returns the number of chars needed to format variables of the specified type as a decimal string. Adds in
313  * extra space for a negative '-' prefix for signed types. Includes space for the trailing NUL. */
314 #define DECIMAL_STR_MAX(type)                                           \
315         ((size_t) IS_SIGNED_INTEGER_TYPE(type) + 1U +                   \
316             (sizeof(type) <= 1 ? 3U :                                   \
317              sizeof(type) <= 2 ? 5U :                                   \
318              sizeof(type) <= 4 ? 10U :                                  \
319              sizeof(type) <= 8 ? (IS_SIGNED_INTEGER_TYPE(type) ? 19U : 20U) : sizeof(int[-2*(sizeof(type) > 8)])))
320 
321 /* Returns the number of chars needed to format the specified integer value. It's hence more specific than
322  * DECIMAL_STR_MAX() which answers the same question for all possible values of the specified type. Does
323  * *not* include space for a trailing NUL. (If you wonder why we special case _x_ == 0 here: it's to trick
324  * out gcc's -Wtype-limits, which would complain on comparing an unsigned type with < 0, otherwise. By
325  * special-casing == 0 here first, we can use <= 0 instead of < 0 to trick out gcc.) */
326 #define DECIMAL_STR_WIDTH(x)                                      \
327         ({                                                        \
328                 typeof(x) _x_ = (x);                              \
329                 size_t ans;                                       \
330                 if (_x_ == 0)                                     \
331                         ans = 1;                                  \
332                 else {                                            \
333                         ans = _x_ <= 0 ? 2 : 1;                   \
334                         while ((_x_ /= 10) != 0)                  \
335                                 ans++;                            \
336                 }                                                 \
337                 ans;                                              \
338         })
339 
340 #define SWAP_TWO(x, y) do {                        \
341                 typeof(x) _t = (x);                \
342                 (x) = (y);                         \
343                 (y) = (_t);                        \
344         } while (false)
345 
346 #define STRV_MAKE(...) ((char**) ((const char*[]) { __VA_ARGS__, NULL }))
347 #define STRV_MAKE_EMPTY ((char*[1]) { NULL })
348 #define STRV_MAKE_CONST(...) ((const char* const*) ((const char*[]) { __VA_ARGS__, NULL }))
349 
350 /* Pointers range from NULL to POINTER_MAX */
351 #define POINTER_MAX ((void*) UINTPTR_MAX)
352 
353 /* Iterates through a specified list of pointers. Accepts NULL pointers, but uses POINTER_MAX as internal marker for EOL. */
354 #define FOREACH_POINTER(p, x, ...)                                                       \
355         for (typeof(p) *_l = (typeof(p)[]) { ({ p = x; }), ##__VA_ARGS__, POINTER_MAX }; \
356              p != (typeof(p)) POINTER_MAX;                                               \
357              p = *(++_l))
358 
359 /* Define C11 thread_local attribute even on older gcc compiler
360  * version */
361 #ifndef thread_local
362 /*
363  * Don't break on glibc < 2.16 that doesn't define __STDC_NO_THREADS__
364  * see http://gcc.gnu.org/bugzilla/show_bug.cgi?id=53769
365  */
366 #if __STDC_VERSION__ >= 201112L && !(defined(__STDC_NO_THREADS__) || (defined(__GNU_LIBRARY__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 16))
367 #define thread_local _Thread_local
368 #else
369 #define thread_local __thread
370 #endif
371 #endif
372 
373 #define DEFINE_TRIVIAL_DESTRUCTOR(name, type, func)             \
374         static inline void name(type *p) {                      \
375                 func(p);                                        \
376         }
377 
378 /* When func() returns the void value (NULL, -1, …) of the appropriate type */
379 #define DEFINE_TRIVIAL_CLEANUP_FUNC(type, func)                 \
380         static inline void func##p(type *p) {                   \
381                 if (*p)                                         \
382                         *p = func(*p);                          \
383         }
384 
385 /* When func() doesn't return the appropriate type, set variable to empty afterwards */
386 #define DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(type, func, empty)     \
387         static inline void func##p(type *p) {                   \
388                 if (*p != (empty)) {                            \
389                         func(*p);                               \
390                         *p = (empty);                           \
391                 }                                               \
392         }
393 
394 #define _DEFINE_TRIVIAL_REF_FUNC(type, name, scope)             \
395         scope type *name##_ref(type *p) {                       \
396                 if (!p)                                         \
397                         return NULL;                            \
398                                                                 \
399                 /* For type check. */                           \
400                 unsigned *q = &p->n_ref;                        \
401                 assert(*q > 0);                                 \
402                 assert_se(*q < UINT_MAX);                       \
403                                                                 \
404                 (*q)++;                                         \
405                 return p;                                       \
406         }
407 
408 #define _DEFINE_TRIVIAL_UNREF_FUNC(type, name, free_func, scope) \
409         scope type *name##_unref(type *p) {                      \
410                 if (!p)                                          \
411                         return NULL;                             \
412                                                                  \
413                 assert(p->n_ref > 0);                            \
414                 p->n_ref--;                                      \
415                 if (p->n_ref > 0)                                \
416                         return NULL;                             \
417                                                                  \
418                 return free_func(p);                             \
419         }
420 
421 #define DEFINE_TRIVIAL_REF_FUNC(type, name)     \
422         _DEFINE_TRIVIAL_REF_FUNC(type, name,)
423 #define DEFINE_PRIVATE_TRIVIAL_REF_FUNC(type, name)     \
424         _DEFINE_TRIVIAL_REF_FUNC(type, name, static)
425 #define DEFINE_PUBLIC_TRIVIAL_REF_FUNC(type, name)      \
426         _DEFINE_TRIVIAL_REF_FUNC(type, name, _public_)
427 
428 #define DEFINE_TRIVIAL_UNREF_FUNC(type, name, free_func)        \
429         _DEFINE_TRIVIAL_UNREF_FUNC(type, name, free_func,)
430 #define DEFINE_PRIVATE_TRIVIAL_UNREF_FUNC(type, name, free_func)        \
431         _DEFINE_TRIVIAL_UNREF_FUNC(type, name, free_func, static)
432 #define DEFINE_PUBLIC_TRIVIAL_UNREF_FUNC(type, name, free_func)         \
433         _DEFINE_TRIVIAL_UNREF_FUNC(type, name, free_func, _public_)
434 
435 #define DEFINE_TRIVIAL_REF_UNREF_FUNC(type, name, free_func)    \
436         DEFINE_TRIVIAL_REF_FUNC(type, name);                    \
437         DEFINE_TRIVIAL_UNREF_FUNC(type, name, free_func);
438 
439 #define DEFINE_PRIVATE_TRIVIAL_REF_UNREF_FUNC(type, name, free_func)    \
440         DEFINE_PRIVATE_TRIVIAL_REF_FUNC(type, name);                    \
441         DEFINE_PRIVATE_TRIVIAL_UNREF_FUNC(type, name, free_func);
442 
443 #define DEFINE_PUBLIC_TRIVIAL_REF_UNREF_FUNC(type, name, free_func)    \
444         DEFINE_PUBLIC_TRIVIAL_REF_FUNC(type, name);                    \
445         DEFINE_PUBLIC_TRIVIAL_UNREF_FUNC(type, name, free_func);
446 
447 /* A macro to force copying of a variable from memory. This is useful whenever we want to read something from
448  * memory and want to make sure the compiler won't optimize away the destination variable for us. It's not
449  * supposed to be a full CPU memory barrier, i.e. CPU is still allowed to reorder the reads, but it is not
450  * allowed to remove our local copies of the variables. We want this to work for unaligned memory, hence
451  * memcpy() is great for our purposes. */
452 #define READ_NOW(x)                                                     \
453         ({                                                              \
454                 typeof(x) _copy;                                        \
455                 memcpy(&_copy, &(x), sizeof(_copy));                    \
456                 asm volatile ("" : : : "memory");                       \
457                 _copy;                                                  \
458         })
459 
460 #define saturate_add(x, y, limit)                                       \
461         ({                                                              \
462                 typeof(limit) _x = (x);                                 \
463                 typeof(limit) _y = (y);                                 \
464                 _x > (limit) || _y >= (limit) - _x ? (limit) : _x + _y; \
465         })
466 
size_add(size_t x,size_t y)467 static inline size_t size_add(size_t x, size_t y) {
468         return saturate_add(x, y, SIZE_MAX);
469 }
470 
471 typedef struct {
472         int _empty[0];
473 } dummy_t;
474 
475 assert_cc(sizeof(dummy_t) == 0);
476 
477 /* A little helper for subtracting 1 off a pointer in a safe UB-free way. This is intended to be used for for
478  * loops that count down from a high pointer until some base. A naive loop would implement this like this:
479  *
480  * for (p = end-1; p >= base; p--) …
481  *
482  * But this is not safe because p before the base is UB in C. With this macro the loop becomes this instead:
483  *
484  * for (p = PTR_SUB1(end, base); p; p = PTR_SUB1(p, base)) …
485  *
486  * And is free from UB! */
487 #define PTR_SUB1(p, base)                                \
488         ({                                               \
489                 typeof(p) _q = (p);                      \
490                 _q && _q > (base) ? &_q[-1] : NULL;      \
491         })
492 
493 #include "log.h"
494