• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

systemd / systemd / 14554080340

19 Apr 2025 11:46AM UTC coverage: 72.101% (-0.03%) from 72.13%
14554080340

push

github

web-flow
Add two new paragraphs to coding style about header files (#37188)

296880 of 411754 relevant lines covered (72.1%)

687547.52 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

93.75
/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 use case 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
/* test harness */
34
#define EXIT_TEST_SKIP 77
35

36
/* builtins */
37
#if __SIZEOF_INT__ == 4
38
#define BUILTIN_FFS_U32(x) __builtin_ffs(x);
39
#elif __SIZEOF_LONG__ == 4
40
#define BUILTIN_FFS_U32(x) __builtin_ffsl(x);
41
#else
42
#error "neither int nor long are four bytes long?!?"
43
#endif
44

45
assert_cc(STRLEN(__FILE__) > STRLEN(RELATIVE_SOURCE_PATH) + 1);
46
#define PROJECT_FILE (&__FILE__[STRLEN(RELATIVE_SOURCE_PATH) + 1])
47

48
static inline uint64_t u64_multiply_safe(uint64_t a, uint64_t b) {
780✔
49
        if (_unlikely_(a != 0 && b > (UINT64_MAX / a)))
780✔
50
                return 0; /* overflow */
51

52
        return a * b;
780✔
53
}
54

55
/* align to next higher power-of-2 (except for: 0 => 0, overflow => 0) */
56
static inline unsigned long ALIGN_POWER2(unsigned long u) {
43,018,664✔
57

58
        /* Avoid subtraction overflow */
59
        if (u == 0)
43,018,664✔
60
                return 0;
61

62
        /* clz(0) is undefined */
63
        if (u == 1)
43,018,664✔
64
                return 1;
65

66
        /* left-shift overflow is undefined */
67
        if (__builtin_clzl(u - 1UL) < 1)
43,018,663✔
68
                return 0;
69

70
        return 1UL << (sizeof(u) * 8 - __builtin_clzl(u - 1UL));
43,017,639✔
71
}
72

73
static inline size_t GREEDY_ALLOC_ROUND_UP(size_t l) {
44,669,574✔
74
        size_t m;
44,669,574✔
75

76
        /* Round up allocation sizes a bit to some reasonable, likely larger value. This is supposed to be
77
         * used for cases which are likely called in an allocation loop of some form, i.e. that repetitively
78
         * grow stuff, for example strv_extend() and suchlike.
79
         *
80
         * Note the difference to GREEDY_REALLOC() here, as this helper operates on a single size value only,
81
         * and rounds up to next multiple of 2, needing no further counter.
82
         *
83
         * Note the benefits of direct ALIGN_POWER2() usage: type-safety for size_t, sane handling for very
84
         * small (i.e. <= 2) and safe handling for very large (i.e. > SSIZE_MAX) values. */
85

86
        if (l <= 2)
44,669,574✔
87
                return 2; /* Never allocate less than 2 of something.  */
88

89
        m = ALIGN_POWER2(l);
42,886,570✔
90
        if (m == 0) /* overflow? */
42,886,570✔
91
                return l;
×
92

93
        return m;
94
}
95

96
/*
97
 * container_of - cast a member of a structure out to the containing structure
98
 * @ptr: the pointer to the member.
99
 * @type: the type of the container struct this is embedded in.
100
 * @member: the name of the member within the struct.
101
 */
102
#define container_of(ptr, type, member) __container_of(UNIQ, (ptr), type, member)
103
#define __container_of(uniq, ptr, type, member)                         \
104
        ({                                                              \
105
                const typeof( ((type*)0)->member ) *UNIQ_T(A, uniq) = (ptr); \
106
                (type*)( (char *)UNIQ_T(A, uniq) - offsetof(type, member) ); \
107
        })
108

109
#define return_with_errno(r, err)                     \
110
        do {                                          \
111
                errno = abs(err);                     \
112
                return r;                             \
113
        } while (false)
114

115
#define PTR_TO_INT(p) ((int) ((intptr_t) (p)))
116
#define INT_TO_PTR(u) ((void *) ((intptr_t) (u)))
117
#define PTR_TO_UINT(p) ((unsigned) ((uintptr_t) (p)))
118
#define UINT_TO_PTR(u) ((void *) ((uintptr_t) (u)))
119

120
#define PTR_TO_LONG(p) ((long) ((intptr_t) (p)))
121
#define LONG_TO_PTR(u) ((void *) ((intptr_t) (u)))
122
#define PTR_TO_ULONG(p) ((unsigned long) ((uintptr_t) (p)))
123
#define ULONG_TO_PTR(u) ((void *) ((uintptr_t) (u)))
124

125
#define PTR_TO_UINT8(p) ((uint8_t) ((uintptr_t) (p)))
126
#define UINT8_TO_PTR(u) ((void *) ((uintptr_t) (u)))
127

128
#define PTR_TO_INT32(p) ((int32_t) ((intptr_t) (p)))
129
#define INT32_TO_PTR(u) ((void *) ((intptr_t) (u)))
130
#define PTR_TO_UINT32(p) ((uint32_t) ((uintptr_t) (p)))
131
#define UINT32_TO_PTR(u) ((void *) ((uintptr_t) (u)))
132

133
#define PTR_TO_INT64(p) ((int64_t) ((intptr_t) (p)))
134
#define INT64_TO_PTR(u) ((void *) ((intptr_t) (u)))
135
#define PTR_TO_UINT64(p) ((uint64_t) ((uintptr_t) (p)))
136
#define UINT64_TO_PTR(u) ((void *) ((uintptr_t) (u)))
137

138
#define CHAR_TO_STR(x) ((char[2]) { x, 0 })
139

140
#define char_array_0(x) x[sizeof(x)-1] = 0;
141

142
/* Maximum buffer size needed for formatting an unsigned integer type as hex, including space for '0x'
143
 * prefix and trailing NUL suffix. */
144
#define HEXADECIMAL_STR_MAX(type) (2 + sizeof(type) * 2 + 1)
145

146
/* Returns the number of chars needed to format variables of the specified type as a decimal string. Adds in
147
 * extra space for a negative '-' prefix for signed types. Includes space for the trailing NUL. */
148
#define DECIMAL_STR_MAX(type)                                           \
149
        ((size_t) IS_SIGNED_INTEGER_TYPE(type) + 1U +                   \
150
            (sizeof(type) <= 1 ? 3U :                                   \
151
             sizeof(type) <= 2 ? 5U :                                   \
152
             sizeof(type) <= 4 ? 10U :                                  \
153
             sizeof(type) <= 8 ? (IS_SIGNED_INTEGER_TYPE(type) ? 19U : 20U) : sizeof(int[-2*(sizeof(type) > 8)])))
154

155
/* Returns the number of chars needed to format the specified integer value. It's hence more specific than
156
 * DECIMAL_STR_MAX() which answers the same question for all possible values of the specified type. Does
157
 * *not* include space for a trailing NUL. (If you wonder why we special case _x_ == 0 here: it's to trick
158
 * out gcc's -Wtype-limits, which would complain on comparing an unsigned type with < 0, otherwise. By
159
 * special-casing == 0 here first, we can use <= 0 instead of < 0 to trick out gcc.) */
160
#define DECIMAL_STR_WIDTH(x)                                      \
161
        ({                                                        \
162
                typeof(x) _x_ = (x);                              \
163
                size_t ans;                                       \
164
                if (_x_ == 0)                                     \
165
                        ans = 1;                                  \
166
                else {                                            \
167
                        ans = _x_ <= 0 ? 2 : 1;                   \
168
                        while ((_x_ /= 10) != 0)                  \
169
                                ans++;                            \
170
                }                                                 \
171
                ans;                                              \
172
        })
173

174
#define SWAP_TWO(x, y) do {                        \
175
                typeof(x) _t = (x);                \
176
                (x) = (y);                         \
177
                (y) = (_t);                        \
178
        } while (false)
179

180
#define STRV_MAKE(...) ((char**) ((const char*[]) { __VA_ARGS__, NULL }))
181
#define STRV_MAKE_EMPTY ((char*[1]) { NULL })
182
#define STRV_MAKE_CONST(...) ((const char* const*) ((const char*[]) { __VA_ARGS__, NULL }))
183

184
/* Pointers range from NULL to POINTER_MAX */
185
#define POINTER_MAX ((void*) UINTPTR_MAX)
186

187
/* A macro to force copying of a variable from memory. This is useful whenever we want to read something from
188
 * memory and want to make sure the compiler won't optimize away the destination variable for us. It's not
189
 * supposed to be a full CPU memory barrier, i.e. CPU is still allowed to reorder the reads, but it is not
190
 * allowed to remove our local copies of the variables. We want this to work for unaligned memory, hence
191
 * memcpy() is great for our purposes. */
192
#define READ_NOW(x)                                                     \
193
        ({                                                              \
194
                typeof(x) _copy;                                        \
195
                memcpy(&_copy, &(x), sizeof(_copy));                    \
196
                asm volatile ("" : : : "memory");                       \
197
                _copy;                                                  \
198
        })
199

200
#define saturate_add(x, y, limit)                                       \
201
        ({                                                              \
202
                typeof(limit) _x = (x);                                 \
203
                typeof(limit) _y = (y);                                 \
204
                _x > (limit) || _y >= (limit) - _x ? (limit) : _x + _y; \
205
        })
206

207
static inline size_t size_add(size_t x, size_t y) {
567✔
208
        return saturate_add(x, y, SIZE_MAX);
722✔
209
}
210

211
/* A little helper for subtracting 1 off a pointer in a safe UB-free way. This is intended to be used for
212
 * loops that count down from a high pointer until some base. A naive loop would implement this like this:
213
 *
214
 * for (p = end-1; p >= base; p--) …
215
 *
216
 * But this is not safe because p before the base is UB in C. With this macro the loop becomes this instead:
217
 *
218
 * for (p = PTR_SUB1(end, base); p; p = PTR_SUB1(p, base)) …
219
 *
220
 * And is free from UB! */
221
#define PTR_SUB1(p, base)                                \
222
        ({                                               \
223
                typeof(p) _q = (p);                      \
224
                _q && _q > (base) ? &_q[-1] : NULL;      \
225
        })
226

227
/* Iterate through each argument passed. All must be the same type as 'entry' or must be implicitly
228
 * convertible. The iteration variable 'entry' must already be defined. */
229
#define FOREACH_ARGUMENT(entry, ...)                                     \
230
        _FOREACH_ARGUMENT(entry, UNIQ_T(_entries_, UNIQ), UNIQ_T(_current_, UNIQ), UNIQ_T(_va_sentinel_, UNIQ), ##__VA_ARGS__)
231
#define _FOREACH_ARGUMENT(entry, _entries_, _current_, _va_sentinel_, ...)      \
232
        for (typeof(entry) _va_sentinel_[1] = {}, _entries_[] = { __VA_ARGS__ __VA_OPT__(,) _va_sentinel_[0] }, *_current_ = _entries_; \
233
             ((long)(_current_ - _entries_) < (long)(ELEMENTSOF(_entries_) - 1)) && ({ entry = *_current_; true; }); \
234
             _current_++)
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc