4 This file is part of systemd.
6 Copyright 2010 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
18 You should have received a copy of the GNU Lesser General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
29 #define new(t, n) ((t*) malloc_multiply(sizeof(t), (n)))
31 #define new0(t, n) ((t*) calloc((n), sizeof(t)))
33 #define newa(t, n) ((t*) alloca(sizeof(t)*(n)))
35 #define newa0(t, n) ((t*) alloca0(sizeof(t)*(n)))
37 #define newdup(t, p, n) ((t*) memdup_multiply(p, sizeof(t), (n)))
39 #define malloc0(n) (calloc(1, (n)))
41 static inline void *mfree(void *memory) {
46 #define free_and_replace(a, b) \
54 void* memdup(const void *p, size_t l) _alloc_(2);
56 static inline void freep(void *p) {
60 #define _cleanup_free_ _cleanup_(freep)
62 static inline bool size_multiply_overflow(size_t size, size_t need) {
63 return _unlikely_(need != 0 && size > (SIZE_MAX / need));
66 _malloc_ _alloc_(1, 2) static inline void *malloc_multiply(size_t size, size_t need) {
67 if (size_multiply_overflow(size, need))
70 return malloc(size * need);
73 _alloc_(2, 3) static inline void *realloc_multiply(void *p, size_t size, size_t need) {
74 if (size_multiply_overflow(size, need))
77 return realloc(p, size * need);
80 _alloc_(2, 3) static inline void *memdup_multiply(const void *p, size_t size, size_t need) {
81 if (size_multiply_overflow(size, need))
84 return memdup(p, size * need);
87 void* greedy_realloc(void **p, size_t *allocated, size_t need, size_t size);
88 void* greedy_realloc0(void **p, size_t *allocated, size_t need, size_t size);
90 #define GREEDY_REALLOC(array, allocated, need) \
91 greedy_realloc((void**) &(array), &(allocated), (need), sizeof((array)[0]))
93 #define GREEDY_REALLOC0(array, allocated, need) \
94 greedy_realloc0((void**) &(array), &(allocated), (need), sizeof((array)[0]))
100 _new_ = alloca(_len_); \
101 (void *) memset(_new_, 0, _len_); \
104 /* It's not clear what alignment glibc/gcc alloca() guarantee, hence provide a guaranteed safe version */
105 #define alloca_align(size, align) \
108 size_t _mask_ = (align) - 1; \
109 _ptr_ = alloca((size) + _mask_); \
110 (void*)(((uintptr_t)_ptr_ + _mask_) & ~_mask_); \
113 #define alloca0_align(size, align) \
116 size_t _size_ = (size); \
117 _new_ = alloca_align(_size_, (align)); \
118 (void*)memset(_new_, 0, _size_); \