]>
git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/alloc-util.h
1 /* SPDX-License-Identifier: LGPL-2.1+ */
11 #define new(t, n) ((t*) malloc_multiply(sizeof(t), (n)))
13 #define new0(t, n) ((t*) calloc((n), sizeof(t)))
17 assert(!size_multiply_overflow(sizeof(t), n)); \
18 (t*) alloca(sizeof(t)*(n)); \
23 assert(!size_multiply_overflow(sizeof(t), n)); \
24 (t*) alloca0(sizeof(t)*(n)); \
27 #define newdup(t, p, n) ((t*) memdup_multiply(p, sizeof(t), (n)))
29 #define newdup_suffix0(t, p, n) ((t*) memdup_suffix0_multiply(p, sizeof(t), (n)))
31 #define malloc0(n) (calloc(1, (n)))
33 static inline void *mfree(void *memory
) {
38 #define free_and_replace(a, b) \
46 void* memdup(const void *p
, size_t l
) _alloc_(2);
47 void* memdup_suffix0(const void *p
, size_t l
) _alloc_(2);
49 static inline void freep(void *p
) {
53 #define _cleanup_free_ _cleanup_(freep)
55 static inline bool size_multiply_overflow(size_t size
, size_t need
) {
56 return _unlikely_(need
!= 0 && size
> (SIZE_MAX
/ need
));
59 _malloc_
_alloc_(1, 2) static inline void *malloc_multiply(size_t size
, size_t need
) {
60 if (size_multiply_overflow(size
, need
))
63 return malloc(size
* need
);
66 #if !HAVE_REALLOCARRAY
67 _alloc_(2, 3) static inline void *reallocarray(void *p
, size_t need
, size_t size
) {
68 if (size_multiply_overflow(size
, need
))
71 return realloc(p
, size
* need
);
75 _alloc_(2, 3) static inline void *memdup_multiply(const void *p
, size_t size
, size_t need
) {
76 if (size_multiply_overflow(size
, need
))
79 return memdup(p
, size
* need
);
82 _alloc_(2, 3) static inline void *memdup_suffix0_multiply(const void *p
, size_t size
, size_t need
) {
83 if (size_multiply_overflow(size
, need
))
86 return memdup_suffix0(p
, size
* need
);
89 void* greedy_realloc(void **p
, size_t *allocated
, size_t need
, size_t size
);
90 void* greedy_realloc0(void **p
, size_t *allocated
, size_t need
, size_t size
);
92 #define GREEDY_REALLOC(array, allocated, need) \
93 greedy_realloc((void**) &(array), &(allocated), (need), sizeof((array)[0]))
95 #define GREEDY_REALLOC0(array, allocated, need) \
96 greedy_realloc0((void**) &(array), &(allocated), (need), sizeof((array)[0]))
102 _new_ = alloca(_len_); \
103 (void *) memset(_new_, 0, _len_); \
106 /* It's not clear what alignment glibc/gcc alloca() guarantee, hence provide a guaranteed safe version */
107 #define alloca_align(size, align) \
110 size_t _mask_ = (align) - 1; \
111 _ptr_ = alloca((size) + _mask_); \
112 (void*)(((uintptr_t)_ptr_ + _mask_) & ~_mask_); \
115 #define alloca0_align(size, align) \
118 size_t _size_ = (size); \
119 _new_ = alloca_align(_size_, (align)); \
120 (void*)memset(_new_, 0, _size_); \
123 /* Takes inspiration from Rusts's Option::take() method: reads and returns a pointer, but at the same time resets it to
124 * NULL. See: https://doc.rust-lang.org/std/option/enum.Option.html#method.take */
125 #define TAKE_PTR(ptr) \
127 typeof(ptr) _ptr_ = (ptr); \