]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/macro.h
repart: Remove outdated comment
[thirdparty/systemd.git] / src / basic / macro.h
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 "constants.h"
13 #include "macro-fundamental.h"
14
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__))
21 #else
22 #define _variable_no_sanitize_address_
23 #endif
24
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")))
29 #else
30 #define _function_no_sanitize_float_cast_overflow_
31 #endif
32
33 /* Temporarily disable some warnings */
34 #define DISABLE_WARNING_DEPRECATED_DECLARATIONS \
35 _Pragma("GCC diagnostic push"); \
36 _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
37
38 #define DISABLE_WARNING_FORMAT_NONLITERAL \
39 _Pragma("GCC diagnostic push"); \
40 _Pragma("GCC diagnostic ignored \"-Wformat-nonliteral\"")
41
42 #define DISABLE_WARNING_MISSING_PROTOTYPES \
43 _Pragma("GCC diagnostic push"); \
44 _Pragma("GCC diagnostic ignored \"-Wmissing-prototypes\"")
45
46 #define DISABLE_WARNING_NONNULL \
47 _Pragma("GCC diagnostic push"); \
48 _Pragma("GCC diagnostic ignored \"-Wnonnull\"")
49
50 #define DISABLE_WARNING_SHADOW \
51 _Pragma("GCC diagnostic push"); \
52 _Pragma("GCC diagnostic ignored \"-Wshadow\"")
53
54 #define DISABLE_WARNING_INCOMPATIBLE_POINTER_TYPES \
55 _Pragma("GCC diagnostic push"); \
56 _Pragma("GCC diagnostic ignored \"-Wincompatible-pointer-types\"")
57
58 #if HAVE_WSTRINGOP_TRUNCATION
59 # define DISABLE_WARNING_STRINGOP_TRUNCATION \
60 _Pragma("GCC diagnostic push"); \
61 _Pragma("GCC diagnostic ignored \"-Wstringop-truncation\"")
62 #else
63 # define DISABLE_WARNING_STRINGOP_TRUNCATION \
64 _Pragma("GCC diagnostic push")
65 #endif
66
67 #define DISABLE_WARNING_TYPE_LIMITS \
68 _Pragma("GCC diagnostic push"); \
69 _Pragma("GCC diagnostic ignored \"-Wtype-limits\"")
70
71 #define DISABLE_WARNING_ADDRESS \
72 _Pragma("GCC diagnostic push"); \
73 _Pragma("GCC diagnostic ignored \"-Waddress\"")
74
75 #define REENABLE_WARNING \
76 _Pragma("GCC diagnostic pop")
77
78 /* automake test harness */
79 #define EXIT_TEST_SKIP 77
80
81 /* builtins */
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);
86 #else
87 #error "neither int nor long are four bytes long?!?"
88 #endif
89
90 /* align to next higher power-of-2 (except for: 0 => 0, overflow => 0) */
91 static inline unsigned long ALIGN_POWER2(unsigned long u) {
92
93 /* Avoid subtraction overflow */
94 if (u == 0)
95 return 0;
96
97 /* clz(0) is undefined */
98 if (u == 1)
99 return 1;
100
101 /* left-shift overflow is undefined */
102 if (__builtin_clzl(u - 1UL) < 1)
103 return 0;
104
105 return 1UL << (sizeof(u) * 8 - __builtin_clzl(u - 1UL));
106 }
107
108 static inline size_t GREEDY_ALLOC_ROUND_UP(size_t l) {
109 size_t m;
110
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.
114 *
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.
117 *
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. */
120
121 if (l <= 2)
122 return 2; /* Never allocate less than 2 of something. */
123
124 m = ALIGN_POWER2(l);
125 if (m == 0) /* overflow? */
126 return l;
127
128 return m;
129 }
130
131 /*
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.
136 */
137 #define container_of(ptr, type, member) __container_of(UNIQ, (ptr), type, member)
138 #define __container_of(uniq, ptr, type, member) \
139 ({ \
140 const typeof( ((type*)0)->member ) *UNIQ_T(A, uniq) = (ptr); \
141 (type*)( (char *)UNIQ_T(A, uniq) - offsetof(type, member) ); \
142 })
143
144 #ifdef __COVERITY__
145
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().
149 *
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.
153 *
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
156 */
157
158 extern void __coverity_panic__(void);
159
160 static inline void __coverity_check__(int condition) {
161 if (!condition)
162 __coverity_panic__();
163 }
164
165 static inline int __coverity_check_and_return__(int condition) {
166 return condition;
167 }
168
169 #define assert_message_se(expr, message) __coverity_check__(!!(expr))
170
171 #define assert_log(expr, message) __coverity_check_and_return__(!!(expr))
172
173 #else /* ! __COVERITY__ */
174
175 #define assert_message_se(expr, message) \
176 do { \
177 if (_unlikely_(!(expr))) \
178 log_assert_failed(message, PROJECT_FILE, __LINE__, __func__); \
179 } while (false)
180
181 #define assert_log(expr, message) ((_likely_(expr)) \
182 ? (true) \
183 : (log_assert_failed_return(message, PROJECT_FILE, __LINE__, __func__), false))
184
185 #endif /* __COVERITY__ */
186
187 #define assert_se(expr) assert_message_se(expr, #expr)
188
189 /* We override the glibc assert() here. */
190 #undef assert
191 #ifdef NDEBUG
192 #define assert(expr) do {} while (false)
193 #else
194 #define assert(expr) assert_message_se(expr, #expr)
195 #endif
196
197 #define assert_not_reached() \
198 log_assert_failed_unreachable(PROJECT_FILE, __LINE__, __func__)
199
200 #define assert_return(expr, r) \
201 do { \
202 if (!assert_log(expr, #expr)) \
203 return (r); \
204 } while (false)
205
206 #define assert_return_errno(expr, r, err) \
207 do { \
208 if (!assert_log(expr, #expr)) { \
209 errno = err; \
210 return (r); \
211 } \
212 } while (false)
213
214 #define return_with_errno(r, err) \
215 do { \
216 errno = abs(err); \
217 return r; \
218 } while (false)
219
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)))
224
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)))
229
230 #define PTR_TO_UINT8(p) ((uint8_t) ((uintptr_t) (p)))
231 #define UINT8_TO_PTR(u) ((void *) ((uintptr_t) (u)))
232
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)))
237
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)))
242
243 #define PTR_TO_SIZE(p) ((size_t) ((uintptr_t) (p)))
244 #define SIZE_TO_PTR(u) ((void *) ((uintptr_t) (u)))
245
246 #define CHAR_TO_STR(x) ((char[2]) { x, 0 })
247
248 #define char_array_0(x) x[sizeof(x)-1] = 0;
249
250 #define sizeof_field(struct_type, member) sizeof(((struct_type *) 0)->member)
251
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)])))
260
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) \
267 ({ \
268 typeof(x) _x_ = (x); \
269 size_t ans; \
270 if (_x_ == 0) \
271 ans = 1; \
272 else { \
273 ans = _x_ <= 0 ? 2 : 1; \
274 while ((_x_ /= 10) != 0) \
275 ans++; \
276 } \
277 ans; \
278 })
279
280 #define SWAP_TWO(x, y) do { \
281 typeof(x) _t = (x); \
282 (x) = (y); \
283 (y) = (_t); \
284 } while (false)
285
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 }))
289
290 /* Pointers range from NULL to POINTER_MAX */
291 #define POINTER_MAX ((void*) UINTPTR_MAX)
292
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; \
297 p = *(++_l))
298
299 /* Define C11 thread_local attribute even on older gcc compiler
300 * version */
301 #ifndef thread_local
302 /*
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
305 */
306 #if __STDC_VERSION__ >= 201112L && !(defined(__STDC_NO_THREADS__) || (defined(__GNU_LIBRARY__) && __GLIBC__ == 2 && __GLIBC_MINOR__ < 16))
307 #define thread_local _Thread_local
308 #else
309 #define thread_local __thread
310 #endif
311 #endif
312
313 #define DEFINE_TRIVIAL_DESTRUCTOR(name, type, func) \
314 static inline void name(type *p) { \
315 func(p); \
316 }
317
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) { \
321 if (*p) \
322 *p = func(*p); \
323 }
324
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; \
331 assert(func); \
332 REENABLE_WARNING; \
333 func(*p); \
334 *p = (empty); \
335 } \
336 }
337
338 #define _DEFINE_TRIVIAL_REF_FUNC(type, name, scope) \
339 scope type *name##_ref(type *p) { \
340 if (!p) \
341 return NULL; \
342 \
343 /* For type check. */ \
344 unsigned *q = &p->n_ref; \
345 assert(*q > 0); \
346 assert_se(*q < UINT_MAX); \
347 \
348 (*q)++; \
349 return p; \
350 }
351
352 #define _DEFINE_TRIVIAL_UNREF_FUNC(type, name, free_func, scope) \
353 scope type *name##_unref(type *p) { \
354 if (!p) \
355 return NULL; \
356 \
357 assert(p->n_ref > 0); \
358 p->n_ref--; \
359 if (p->n_ref > 0) \
360 return NULL; \
361 \
362 return free_func(p); \
363 }
364
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_)
371
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_)
378
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);
382
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);
386
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);
390
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) \
397 ({ \
398 typeof(x) _copy; \
399 memcpy(&_copy, &(x), sizeof(_copy)); \
400 asm volatile ("" : : : "memory"); \
401 _copy; \
402 })
403
404 #define saturate_add(x, y, limit) \
405 ({ \
406 typeof(limit) _x = (x); \
407 typeof(limit) _y = (y); \
408 _x > (limit) || _y >= (limit) - _x ? (limit) : _x + _y; \
409 })
410
411 static inline size_t size_add(size_t x, size_t y) {
412 return saturate_add(x, y, SIZE_MAX);
413 }
414
415 typedef struct {
416 int _empty[0];
417 } dummy_t;
418
419 assert_cc(sizeof(dummy_t) == 0);
420
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:
423 *
424 * for (p = end-1; p >= base; p--) …
425 *
426 * But this is not safe because p before the base is UB in C. With this macro the loop becomes this instead:
427 *
428 * for (p = PTR_SUB1(end, base); p; p = PTR_SUB1(p, base)) …
429 *
430 * And is free from UB! */
431 #define PTR_SUB1(p, base) \
432 ({ \
433 typeof(p) _q = (p); \
434 _q && _q > (base) ? &_q[-1] : NULL; \
435 })
436
437 #include "log.h"