• 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

95.12
/src/basic/alloc-util.h
1
/* SPDX-License-Identifier: LGPL-2.1-or-later */
2
#pragma once
3

4
#include <alloca.h>
5
#include <malloc.h>
6
#include <stddef.h>
7
#include <stdlib.h>
8
#include <string.h>
9

10
#include "assert-util.h"
11
#include "macro.h"
12
#include "memory-util.h"
13

14
#if HAS_FEATURE_MEMORY_SANITIZER
15
#  include <sanitizer/msan_interface.h>
16
#endif
17

18
typedef void (*free_func_t)(void *p);
19
typedef void* (*mfree_func_t)(void *p);
20

21
/* If for some reason more than 4M are allocated on the stack, let's abort immediately. It's better than
22
 * proceeding and smashing the stack limits. Note that by default RLIMIT_STACK is 8M on Linux. */
23
#define ALLOCA_MAX (4U*1024U*1024U)
24

25
#define new(t, n) ((t*) malloc_multiply(n, sizeof(t)))
26

27
#define new0(t, n) ((t*) calloc((n) ?: 1, sizeof(t)))
28

29
#define alloca_safe(n)                                                  \
30
        ({                                                              \
31
                size_t _nn_ = (n);                                      \
32
                assert(_nn_ <= ALLOCA_MAX);                             \
33
                alloca(_nn_ == 0 ? 1 : _nn_);                           \
34
        })                                                              \
35

36
#define newa(t, n)                                                      \
37
        ({                                                              \
38
                size_t _n_ = (n);                                       \
39
                assert_se(MUL_ASSIGN_SAFE(&_n_, sizeof(t)));            \
40
                (t*) alloca_safe(_n_);                                  \
41
        })
42

43
#define newa0(t, n)                                                     \
44
        ({                                                              \
45
                size_t _n_ = (n);                                       \
46
                assert_se(MUL_ASSIGN_SAFE(&_n_, sizeof(t)));            \
47
                (t*) alloca0(_n_);                                      \
48
        })
49

50
#define newdup(t, p, n) ((t*) memdup_multiply(p, n, sizeof(t)))
51

52
#define newdup_suffix0(t, p, n) ((t*) memdup_suffix0_multiply(p, n, sizeof(t)))
53

54
#define malloc0(n) (calloc(1, (n) ?: 1))
55

56
#define free_and_replace_full(a, b, free_func)  \
57
        ({                                      \
58
                typeof(a)* _a = &(a);           \
59
                typeof(b)* _b = &(b);           \
60
                free_func(*_a);                 \
61
                *_a = *_b;                      \
62
                *_b = NULL;                     \
63
                0;                              \
64
        })
65

66
#define free_and_replace(a, b)                  \
67
        free_and_replace_full(a, b, free)
68

69
/* This is similar to free_and_replace_full(), but NULL is not assigned to 'b', and its reference counter is
70
 * increased. */
71
#define unref_and_replace_full(a, b, ref_func, unref_func)      \
72
        ({                                       \
73
                typeof(a)* _a = &(a);            \
74
                typeof(b) _b = ref_func(b);      \
75
                unref_func(*_a);                 \
76
                *_a = _b;                        \
77
                0;                               \
78
        })
79

80
void* memdup(const void *p, size_t l) _alloc_(2);
81
void* memdup_suffix0(const void *p, size_t l); /* We can't use _alloc_() here, since we return a buffer one byte larger than the specified size */
82

83
#define memdupa(p, l)                           \
84
        ({                                      \
85
                void *_q_;                      \
86
                size_t _l_ = l;                 \
87
                _q_ = alloca_safe(_l_);         \
88
                memcpy_safe(_q_, p, _l_);       \
89
        })
90

91
#define memdupa_suffix0(p, l)                   \
92
        ({                                      \
93
                void *_q_;                      \
94
                size_t _l_ = l;                 \
95
                _q_ = alloca_safe(_l_ + 1);     \
96
                ((uint8_t*) _q_)[_l_] = 0;      \
97
                memcpy_safe(_q_, p, _l_);       \
98
        })
99

100
static inline void unsetp(void *p) {
67,128✔
101
        /* A trivial "destructor" that can be used in cases where we want to
102
         * unset a pointer from a _cleanup_ function. */
103

104
        *(void**)p = NULL;
67,128✔
105
}
106

107
static inline void freep(void *p) {
185,423,252✔
108
        *(void**)p = mfree(*(void**) p);
225,497,717✔
109
}
7,584,867✔
110

111
#define _cleanup_free_ _cleanup_(freep)
112

113
static inline bool size_multiply_overflow(size_t size, size_t need) {
11,009,248✔
114
        return _unlikely_(need != 0 && size > (SIZE_MAX / need));
10,993,492✔
115
}
116

117
_malloc_ _alloc_(1, 2) static inline void *malloc_multiply(size_t need, size_t size) {
21,555,364✔
118
        if (size_multiply_overflow(size, need))
18,907,688✔
119
                return NULL;
120

121
        return malloc(size * need ?: 1);
21,571,165✔
122
}
123

124
_alloc_(2, 3) static inline void *memdup_multiply(const void *p, size_t need, size_t size) {
404,126✔
125
        if (size_multiply_overflow(size, need))
404,126✔
126
                return NULL;
127

128
        return memdup(p, size * need);
404,126✔
129
}
130

131
/* Note that we can't decorate this function with _alloc_() since the returned memory area is one byte larger
132
 * than the product of its parameters. */
133
static inline void *memdup_suffix0_multiply(const void *p, size_t need, size_t size) {
939,052✔
134
        if (size_multiply_overflow(size, need))
939,052✔
135
                return NULL;
136

137
        return memdup_suffix0(p, size * need);
939,052✔
138
}
139

140
void* greedy_realloc(void **p, size_t need, size_t size);
141
void* greedy_realloc0(void **p, size_t need, size_t size);
142
void* greedy_realloc_append(void **p, size_t *n_p, const void *from, size_t n_from, size_t size);
143

144
#define GREEDY_REALLOC(array, need)                                     \
145
        greedy_realloc((void**) &(array), (need), sizeof((array)[0]))
146

147
#define GREEDY_REALLOC0(array, need)                                    \
148
        greedy_realloc0((void**) &(array), (need), sizeof((array)[0]))
149

150
#define GREEDY_REALLOC_APPEND(array, n_array, from, n_from)             \
151
        ({                                                              \
152
                const typeof(*(array)) *_from_ = (from);                \
153
                greedy_realloc_append((void**) &(array), &(n_array), _from_, (n_from), sizeof((array)[0])); \
154
        })
155

156
#define alloca0(n)                                      \
157
        ({                                              \
158
                char *_new_;                            \
159
                size_t _len_ = n;                       \
160
                _new_ = alloca_safe(_len_);             \
161
                memset(_new_, 0, _len_);                \
162
        })
163

164
/* It's not clear what alignment glibc/gcc alloca() guarantee, hence provide a guaranteed safe version */
165
#define alloca_align(size, align)                                       \
166
        ({                                                              \
167
                void *_ptr_;                                            \
168
                size_t _mask_ = (align) - 1;                            \
169
                size_t _size_ = size;                                   \
170
                _ptr_ = alloca_safe(_size_ + _mask_);                   \
171
                (void*)(((uintptr_t)_ptr_ + _mask_) & ~_mask_);         \
172
        })
173

174
#define alloca0_align(size, align)                                      \
175
        ({                                                              \
176
                void *_new_;                                            \
177
                size_t _xsize_ = (size);                                \
178
                _new_ = alloca_align(_xsize_, (align));                 \
179
                memset(_new_, 0, _xsize_);                              \
180
        })
181

182
#if HAS_FEATURE_MEMORY_SANITIZER
183
#  define msan_unpoison(r, s) __msan_unpoison(r, s)
184
#else
185
#  define msan_unpoison(r, s)
186
#endif
187

188
/* Dummy allocator to tell the compiler that the new size of p is newsize. The implementation returns the
189
 * pointer as is; the only reason for its existence is as a conduit for the _alloc_ attribute.  This must not
190
 * be inlined (hence a non-static function with _noinline_ because LTO otherwise tries to inline it) because
191
 * gcc then loses the attributes on the function.
192
 * See: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=96503 */
193
void *expand_to_usable(void *p, size_t newsize) _alloc_(2) _returns_nonnull_ _noinline_;
194

195
static inline size_t malloc_sizeof_safe(void **xp) {
518,194,829✔
196
        if (_unlikely_(!xp || !*xp))
518,194,829✔
197
                return 0;
198

199
        size_t sz = malloc_usable_size(*xp);
517,867,604✔
200
        *xp = expand_to_usable(*xp, sz);
517,867,604✔
201
        /* GCC doesn't see the _returns_nonnull_ when built with ubsan, so yet another hint to make it doubly
202
         * clear that expand_to_usable won't return NULL.
203
         * See: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=79265 */
204
        if (!*xp)
517,867,604✔
205
                assert_not_reached();
×
206
        return sz;
207
}
208

209
/* This returns the number of usable bytes in a malloc()ed region as per malloc_usable_size(), which may
210
 * return a value larger than the size that was actually allocated. Access to that additional memory is
211
 * discouraged because it violates the C standard; a compiler cannot see that this as valid. To help the
212
 * compiler out, the MALLOC_SIZEOF_SAFE macro 'allocates' the usable size using a dummy allocator function
213
 * expand_to_usable. There is a possibility of malloc_usable_size() returning different values during the
214
 * lifetime of an object, which may cause problems, but the glibc allocator does not do that at the moment. */
215
#define MALLOC_SIZEOF_SAFE(x) \
216
        malloc_sizeof_safe((void**) &__builtin_choose_expr(__builtin_constant_p(x), (void*) { NULL }, (x)))
217

218
/* Inspired by ELEMENTSOF() but operates on malloc()'ed memory areas: typesafely returns the number of items
219
 * that fit into the specified memory block */
220
#define MALLOC_ELEMENTSOF(x) \
221
        (__builtin_choose_expr(                                         \
222
                __builtin_types_compatible_p(typeof(x), typeof(&*(x))), \
223
                MALLOC_SIZEOF_SAFE(x)/sizeof((x)[0]),                   \
224
                VOID_0))
225

226
/* These are like strdupa()/strndupa(), but honour ALLOCA_MAX */
227
#define strdupa_safe(s)                                                 \
228
        ({                                                              \
229
                const char *_t = (s);                                   \
230
                (char*) memdupa_suffix0(_t, strlen(_t));                \
231
        })
232

233
#define strndupa_safe(s, n)                                             \
234
        ({                                                              \
235
                const char *_t = (s);                                   \
236
                (char*) memdupa_suffix0(_t, strnlen(_t, n));            \
237
        })
238

239
/* Free every element of the array. */
240
static inline void free_many(void **p, size_t n) {
56,983✔
241
        assert(p || n == 0);
56,983✔
242

243
        FOREACH_ARRAY(i, p, n)
986,372✔
244
                *i = mfree(*i);
929,389✔
245
}
56,983✔
246

247
/* Typesafe wrapper for char** rather than void**. Unfortunately C won't implicitly cast this. */
248
static inline void free_many_charp(char **c, size_t n) {
1,235✔
249
        free_many((void**) c, n);
1,235✔
250
}
×
251

252
_alloc_(2) static inline void *realloc0(void *p, size_t new_size) {
24,868✔
253
        size_t old_size;
24,868✔
254
        void *q;
24,868✔
255

256
        /* Like realloc(), but initializes anything appended to zero */
257

258
        old_size = MALLOC_SIZEOF_SAFE(p);
24,868✔
259

260
        q = realloc(p, new_size);
24,868✔
261
        if (!q)
24,868✔
262
                return NULL;
24,868✔
263

264
        new_size = MALLOC_SIZEOF_SAFE(q); /* Update with actually allocated space */
24,868✔
265

266
        if (new_size > old_size)
24,868✔
267
                memset((uint8_t*) q + old_size, 0, new_size - old_size);
21,901✔
268

269
        return q;
24,868✔
270
}
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