]>
git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/macro.h
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
9 #include <sys/sysmacros.h>
10 #include <sys/types.h>
12 #include "constants.h"
13 #include "macro-fundamental.h"
15 /* Note: on GCC "no_sanitize_address" is a function attribute only, on llvm it may also be applied to global
16 * variables. We define a specific macro which knows this. Note that on GCC we don't need this decorator so much, since
17 * our primary usecase for this attribute is registration structures placed in named ELF sections which shall not be
18 * padded, but GCC doesn't pad those anyway if AddressSanitizer is enabled. */
19 #if HAS_FEATURE_ADDRESS_SANITIZER && defined(__clang__)
20 #define _variable_no_sanitize_address_ __attribute__((__no_sanitize_address__))
22 #define _variable_no_sanitize_address_
25 /* Apparently there's no has_feature() call defined to check for ubsan, hence let's define this
26 * unconditionally on llvm */
27 #if defined(__clang__)
28 #define _function_no_sanitize_float_cast_overflow_ __attribute__((no_sanitize("float-cast-overflow")))
30 #define _function_no_sanitize_float_cast_overflow_
33 /* Temporarily disable some warnings */
34 #define DISABLE_WARNING_DEPRECATED_DECLARATIONS \
35 _Pragma("GCC diagnostic push"); \
36 _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
38 #define DISABLE_WARNING_FORMAT_NONLITERAL \
39 _Pragma("GCC diagnostic push"); \
40 _Pragma("GCC diagnostic ignored \"-Wformat-nonliteral\"")
42 #define DISABLE_WARNING_MISSING_PROTOTYPES \
43 _Pragma("GCC diagnostic push"); \
44 _Pragma("GCC diagnostic ignored \"-Wmissing-prototypes\"")
46 #define DISABLE_WARNING_NONNULL \
47 _Pragma("GCC diagnostic push"); \
48 _Pragma("GCC diagnostic ignored \"-Wnonnull\"")
50 #define DISABLE_WARNING_SHADOW \
51 _Pragma("GCC diagnostic push"); \
52 _Pragma("GCC diagnostic ignored \"-Wshadow\"")
54 #define DISABLE_WARNING_INCOMPATIBLE_POINTER_TYPES \
55 _Pragma("GCC diagnostic push"); \
56 _Pragma("GCC diagnostic ignored \"-Wincompatible-pointer-types\"")
58 #if HAVE_WSTRINGOP_TRUNCATION
59 # define DISABLE_WARNING_STRINGOP_TRUNCATION \
60 _Pragma("GCC diagnostic push"); \
61 _Pragma("GCC diagnostic ignored \"-Wstringop-truncation\"")
63 # define DISABLE_WARNING_STRINGOP_TRUNCATION \
64 _Pragma("GCC diagnostic push")
67 #define DISABLE_WARNING_TYPE_LIMITS \
68 _Pragma("GCC diagnostic push"); \
69 _Pragma("GCC diagnostic ignored \"-Wtype-limits\"")
71 #define DISABLE_WARNING_ADDRESS \
72 _Pragma("GCC diagnostic push"); \
73 _Pragma("GCC diagnostic ignored \"-Waddress\"")
75 #define REENABLE_WARNING \
76 _Pragma("GCC diagnostic pop")
78 /* automake test harness */
79 #define EXIT_TEST_SKIP 77
82 #if __SIZEOF_INT__ == 4
83 #define BUILTIN_FFS_U32(x) __builtin_ffs(x);
84 #elif __SIZEOF_LONG__ == 4
85 #define BUILTIN_FFS_U32(x) __builtin_ffsl(x);
87 #error "neither int nor long are four bytes long?!?"
90 /* align to next higher power-of-2 (except for: 0 => 0, overflow => 0) */
91 static inline unsigned long ALIGN_POWER2(unsigned long u
) {
93 /* Avoid subtraction overflow */
97 /* clz(0) is undefined */
101 /* left-shift overflow is undefined */
102 if (__builtin_clzl(u
- 1UL) < 1)
105 return 1UL << (sizeof(u
) * 8 - __builtin_clzl(u
- 1UL));
108 static inline size_t GREEDY_ALLOC_ROUND_UP(size_t l
) {
111 /* Round up allocation sizes a bit to some reasonable, likely larger value. This is supposed to be
112 * used for cases which are likely called in an allocation loop of some form, i.e. that repetitively
113 * grow stuff, for example strv_extend() and suchlike.
115 * Note the difference to GREEDY_REALLOC() here, as this helper operates on a single size value only,
116 * and rounds up to next multiple of 2, needing no further counter.
118 * Note the benefits of direct ALIGN_POWER2() usage: type-safety for size_t, sane handling for very
119 * small (i.e. <= 2) and safe handling for very large (i.e. > SSIZE_MAX) values. */
122 return 2; /* Never allocate less than 2 of something. */
125 if (m
== 0) /* overflow? */
132 * container_of - cast a member of a structure out to the containing structure
133 * @ptr: the pointer to the member.
134 * @type: the type of the container struct this is embedded in.
135 * @member: the name of the member within the struct.
137 #define container_of(ptr, type, member) __container_of(UNIQ, (ptr), type, member)
138 #define __container_of(uniq, ptr, type, member) \
140 const typeof( ((type*)0)->member ) *UNIQ_T(A, uniq) = (ptr); \
141 (type*)( (char *)UNIQ_T(A, uniq) - offsetof(type, member) ); \
146 /* Use special definitions of assertion macros in order to prevent
147 * false positives of ASSERT_SIDE_EFFECT on Coverity static analyzer
148 * for uses of assert_se() and assert_return().
150 * These definitions make expression go through a (trivial) function
151 * call to ensure they are not discarded. Also use ! or !! to ensure
152 * the boolean expressions are seen as such.
154 * This technique has been described and recommended in:
155 * https://community.synopsys.com/s/question/0D534000046Yuzb/suppressing-assertsideeffect-for-functions-that-allow-for-sideeffects
158 extern void __coverity_panic__(void);
160 static inline void __coverity_check__(int condition
) {
162 __coverity_panic__();
165 static inline int __coverity_check_and_return__(int condition
) {
169 #define assert_message_se(expr, message) __coverity_check__(!!(expr))
171 #define assert_log(expr, message) __coverity_check_and_return__(!!(expr))
173 #else /* ! __COVERITY__ */
175 #define assert_message_se(expr, message) \
177 if (_unlikely_(!(expr))) \
178 log_assert_failed(message, PROJECT_FILE, __LINE__, __func__); \
181 #define assert_log(expr, message) ((_likely_(expr)) \
183 : (log_assert_failed_return(message, PROJECT_FILE, __LINE__, __func__), false))
185 #endif /* __COVERITY__ */
187 #define assert_se(expr) assert_message_se(expr, #expr)
189 /* We override the glibc assert() here. */
192 #define assert(expr) do {} while (false)
194 #define assert(expr) assert_message_se(expr, #expr)
197 #define assert_not_reached() \
198 log_assert_failed_unreachable(PROJECT_FILE, __LINE__, __func__)
200 #define assert_return(expr, r) \
202 if (!assert_log(expr, #expr)) \
206 #define assert_return_errno(expr, r, err) \
208 if (!assert_log(expr, #expr)) { \
214 #define return_with_errno(r, err) \
220 #define PTR_TO_INT(p) ((int) ((intptr_t) (p)))
221 #define INT_TO_PTR(u) ((void *) ((intptr_t) (u)))
222 #define PTR_TO_UINT(p) ((unsigned) ((uintptr_t) (p)))
223 #define UINT_TO_PTR(u) ((void *) ((uintptr_t) (u)))
225 #define PTR_TO_LONG(p) ((long) ((intptr_t) (p)))
226 #define LONG_TO_PTR(u) ((void *) ((intptr_t) (u)))
227 #define PTR_TO_ULONG(p) ((unsigned long) ((uintptr_t) (p)))
228 #define ULONG_TO_PTR(u) ((void *) ((uintptr_t) (u)))
230 #define PTR_TO_UINT8(p) ((uint8_t) ((uintptr_t) (p)))
231 #define UINT8_TO_PTR(u) ((void *) ((uintptr_t) (u)))
233 #define PTR_TO_INT32(p) ((int32_t) ((intptr_t) (p)))
234 #define INT32_TO_PTR(u) ((void *) ((intptr_t) (u)))
235 #define PTR_TO_UINT32(p) ((uint32_t) ((uintptr_t) (p)))
236 #define UINT32_TO_PTR(u) ((void *) ((uintptr_t) (u)))
238 #define PTR_TO_INT64(p) ((int64_t) ((intptr_t) (p)))
239 #define INT64_TO_PTR(u) ((void *) ((intptr_t) (u)))
240 #define PTR_TO_UINT64(p) ((uint64_t) ((uintptr_t) (p)))
241 #define UINT64_TO_PTR(u) ((void *) ((uintptr_t) (u)))
243 #define PTR_TO_SIZE(p) ((size_t) ((uintptr_t) (p)))
244 #define SIZE_TO_PTR(u) ((void *) ((uintptr_t) (u)))
246 #define CHAR_TO_STR(x) ((char[2]) { x, 0 })
248 #define char_array_0(x) x[sizeof(x)-1] = 0;
250 #define sizeof_field(struct_type, member) sizeof(((struct_type *) 0)->member)
252 /* Returns the number of chars needed to format variables of the specified type as a decimal string. Adds in
253 * extra space for a negative '-' prefix for signed types. Includes space for the trailing NUL. */
254 #define DECIMAL_STR_MAX(type) \
255 ((size_t) IS_SIGNED_INTEGER_TYPE(type) + 1U + \
256 (sizeof(type) <= 1 ? 3U : \
257 sizeof(type) <= 2 ? 5U : \
258 sizeof(type) <= 4 ? 10U : \
259 sizeof(type) <= 8 ? (IS_SIGNED_INTEGER_TYPE(type) ? 19U : 20U) : sizeof(int[-2*(sizeof(type) > 8)])))
261 /* Returns the number of chars needed to format the specified integer value. It's hence more specific than
262 * DECIMAL_STR_MAX() which answers the same question for all possible values of the specified type. Does
263 * *not* include space for a trailing NUL. (If you wonder why we special case _x_ == 0 here: it's to trick
264 * out gcc's -Wtype-limits, which would complain on comparing an unsigned type with < 0, otherwise. By
265 * special-casing == 0 here first, we can use <= 0 instead of < 0 to trick out gcc.) */
266 #define DECIMAL_STR_WIDTH(x) \
268 typeof(x) _x_ = (x); \
273 ans = _x_ <= 0 ? 2 : 1; \
274 while ((_x_ /= 10) != 0) \
280 #define SWAP_TWO(x, y) do { \
281 typeof(x) _t = (x); \
286 #define STRV_MAKE(...) ((char**) ((const char*[]) { __VA_ARGS__, NULL }))
287 #define STRV_MAKE_EMPTY ((char*[1]) { NULL })
288 #define STRV_MAKE_CONST(...) ((const char* const*) ((const char*[]) { __VA_ARGS__, NULL }))
290 /* Pointers range from NULL to POINTER_MAX */
291 #define POINTER_MAX ((void*) UINTPTR_MAX)
293 /* Iterates through a specified list of pointers. Accepts NULL pointers, but uses POINTER_MAX as internal marker for EOL. */
294 #define FOREACH_POINTER(p, x, ...) \
295 for (typeof(p) *_l = (typeof(p)[]) { ({ p = x; }), ##__VA_ARGS__, POINTER_MAX }; \
296 p != (typeof(p)) POINTER_MAX; \
299 /* Define C11 thread_local attribute even on older gcc compiler
303 * Don't break on glibc < 2.16 that doesn't define __STDC_NO_THREADS__
304 * see https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53769
306 #if __STDC_VERSION__ >= 201112L && !(defined(__STDC_NO_THREADS__) || (defined(__GNU_LIBRARY__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 16))
307 #define thread_local _Thread_local
309 #define thread_local __thread
313 #define DEFINE_TRIVIAL_DESTRUCTOR(name, type, func) \
314 static inline void name(type *p) { \
318 /* When func() returns the void value (NULL, -1, …) of the appropriate type */
319 #define DEFINE_TRIVIAL_CLEANUP_FUNC(type, func) \
320 static inline void func##p(type *p) { \
325 /* When func() doesn't return the appropriate type, set variable to empty afterwards.
326 * The func() may be provided by a dynamically loaded shared library, hence add an assertion. */
327 #define DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(type, func, empty) \
328 static inline void func##p(type *p) { \
329 if (*p != (empty)) { \
330 DISABLE_WARNING_ADDRESS; \
338 #define _DEFINE_TRIVIAL_REF_FUNC(type, name, scope) \
339 scope type *name##_ref(type *p) { \
343 /* For type check. */ \
344 unsigned *q = &p->n_ref; \
346 assert_se(*q < UINT_MAX); \
352 #define _DEFINE_TRIVIAL_UNREF_FUNC(type, name, free_func, scope) \
353 scope type *name##_unref(type *p) { \
357 assert(p->n_ref > 0); \
362 return free_func(p); \
365 #define DEFINE_TRIVIAL_REF_FUNC(type, name) \
366 _DEFINE_TRIVIAL_REF_FUNC(type, name,)
367 #define DEFINE_PRIVATE_TRIVIAL_REF_FUNC(type, name) \
368 _DEFINE_TRIVIAL_REF_FUNC(type, name, static)
369 #define DEFINE_PUBLIC_TRIVIAL_REF_FUNC(type, name) \
370 _DEFINE_TRIVIAL_REF_FUNC(type, name, _public_)
372 #define DEFINE_TRIVIAL_UNREF_FUNC(type, name, free_func) \
373 _DEFINE_TRIVIAL_UNREF_FUNC(type, name, free_func,)
374 #define DEFINE_PRIVATE_TRIVIAL_UNREF_FUNC(type, name, free_func) \
375 _DEFINE_TRIVIAL_UNREF_FUNC(type, name, free_func, static)
376 #define DEFINE_PUBLIC_TRIVIAL_UNREF_FUNC(type, name, free_func) \
377 _DEFINE_TRIVIAL_UNREF_FUNC(type, name, free_func, _public_)
379 #define DEFINE_TRIVIAL_REF_UNREF_FUNC(type, name, free_func) \
380 DEFINE_TRIVIAL_REF_FUNC(type, name); \
381 DEFINE_TRIVIAL_UNREF_FUNC(type, name, free_func);
383 #define DEFINE_PRIVATE_TRIVIAL_REF_UNREF_FUNC(type, name, free_func) \
384 DEFINE_PRIVATE_TRIVIAL_REF_FUNC(type, name); \
385 DEFINE_PRIVATE_TRIVIAL_UNREF_FUNC(type, name, free_func);
387 #define DEFINE_PUBLIC_TRIVIAL_REF_UNREF_FUNC(type, name, free_func) \
388 DEFINE_PUBLIC_TRIVIAL_REF_FUNC(type, name); \
389 DEFINE_PUBLIC_TRIVIAL_UNREF_FUNC(type, name, free_func);
391 /* A macro to force copying of a variable from memory. This is useful whenever we want to read something from
392 * memory and want to make sure the compiler won't optimize away the destination variable for us. It's not
393 * supposed to be a full CPU memory barrier, i.e. CPU is still allowed to reorder the reads, but it is not
394 * allowed to remove our local copies of the variables. We want this to work for unaligned memory, hence
395 * memcpy() is great for our purposes. */
396 #define READ_NOW(x) \
399 memcpy(&_copy, &(x), sizeof(_copy)); \
400 asm volatile ("" : : : "memory"); \
404 #define saturate_add(x, y, limit) \
406 typeof(limit) _x = (x); \
407 typeof(limit) _y = (y); \
408 _x > (limit) || _y >= (limit) - _x ? (limit) : _x + _y; \
411 static inline size_t size_add(size_t x
, size_t y
) {
412 return saturate_add(x
, y
, SIZE_MAX
);
419 assert_cc(sizeof(dummy_t
) == 0);
421 /* A little helper for subtracting 1 off a pointer in a safe UB-free way. This is intended to be used for for
422 * loops that count down from a high pointer until some base. A naive loop would implement this like this:
424 * for (p = end-1; p >= base; p--) …
426 * But this is not safe because p before the base is UB in C. With this macro the loop becomes this instead:
428 * for (p = PTR_SUB1(end, base); p; p = PTR_SUB1(p, base)) …
430 * And is free from UB! */
431 #define PTR_SUB1(p, base) \
433 typeof(p) _q = (p); \
434 _q && _q > (base) ? &_q[-1] : NULL; \