1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2 #pragma once
3 
4 #include <alloca.h>
5 #include <stddef.h>
6 #include <stdlib.h>
7 #include <string.h>
8 
9 #include "macro.h"
10 
11 #if HAS_FEATURE_MEMORY_SANITIZER
12 #  include <sanitizer/msan_interface.h>
13 #endif
14 
15 typedef void (*free_func_t)(void *p);
16 typedef void* (*mfree_func_t)(void *p);
17 
18 /* If for some reason more than 4M are allocated on the stack, let's abort immediately. It's better than
19  * proceeding and smashing the stack limits. Note that by default RLIMIT_STACK is 8M on Linux. */
20 #define ALLOCA_MAX (4U*1024U*1024U)
21 
22 #define new(t, n) ((t*) malloc_multiply(sizeof(t), (n)))
23 
24 #define new0(t, n) ((t*) calloc((n) ?: 1, sizeof(t)))
25 
26 #define alloca_safe(n)                                                  \
27         ({                                                              \
28                 size_t _nn_ = n;                                        \
29                 assert(_nn_ <= ALLOCA_MAX);                             \
30                 alloca(_nn_ == 0 ? 1 : _nn_);                           \
31         })                                                              \
32 
33 #define newa(t, n)                                                      \
34         ({                                                              \
35                 size_t _n_ = n;                                         \
36                 assert(!size_multiply_overflow(sizeof(t), _n_));        \
37                 (t*) alloca_safe(sizeof(t)*_n_);                        \
38         })
39 
40 #define newa0(t, n)                                                     \
41         ({                                                              \
42                 size_t _n_ = n;                                         \
43                 assert(!size_multiply_overflow(sizeof(t), _n_));        \
44                 (t*) alloca0((sizeof(t)*_n_));                          \
45         })
46 
47 #define newdup(t, p, n) ((t*) memdup_multiply(p, sizeof(t), (n)))
48 
49 #define newdup_suffix0(t, p, n) ((t*) memdup_suffix0_multiply(p, sizeof(t), (n)))
50 
51 #define malloc0(n) (calloc(1, (n) ?: 1))
52 
53 #define free_and_replace(a, b)                  \
54         ({                                      \
55                 typeof(a)* _a = &(a);           \
56                 typeof(b)* _b = &(b);           \
57                 free(*_a);                      \
58                 *_a = *_b;                      \
59                 *_b = NULL;                     \
60                 0;                              \
61         })
62 
63 void* memdup(const void *p, size_t l) _alloc_(2);
64 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 */
65 
66 #define memdupa(p, l)                           \
67         ({                                      \
68                 void *_q_;                      \
69                 size_t _l_ = l;                 \
70                 _q_ = alloca_safe(_l_);         \
71                 memcpy_safe(_q_, p, _l_);       \
72         })
73 
74 #define memdupa_suffix0(p, l)                   \
75         ({                                      \
76                 void *_q_;                      \
77                 size_t _l_ = l;                 \
78                 _q_ = alloca_safe(_l_ + 1);     \
79                 ((uint8_t*) _q_)[_l_] = 0;      \
80                 memcpy_safe(_q_, p, _l_);       \
81         })
82 
unsetp(void * p)83 static inline void unsetp(void *p) {
84         /* A trivial "destructor" that can be used in cases where we want to
85          * unset a pointer from a _cleanup_ function. */
86 
87         *(void**)p = NULL;
88 }
89 
freep(void * p)90 static inline void freep(void *p) {
91         *(void**)p = mfree(*(void**) p);
92 }
93 
94 #define _cleanup_free_ _cleanup_(freep)
95 
size_multiply_overflow(size_t size,size_t need)96 static inline bool size_multiply_overflow(size_t size, size_t need) {
97         return _unlikely_(need != 0 && size > (SIZE_MAX / need));
98 }
99 
malloc_multiply(size_t size,size_t need)100 _malloc_  _alloc_(1, 2) static inline void *malloc_multiply(size_t size, size_t need) {
101         if (size_multiply_overflow(size, need))
102                 return NULL;
103 
104         return malloc(size * need ?: 1);
105 }
106 
107 #if !HAVE_REALLOCARRAY
reallocarray(void * p,size_t need,size_t size)108 _alloc_(2, 3) static inline void *reallocarray(void *p, size_t need, size_t size) {
109         if (size_multiply_overflow(size, need))
110                 return NULL;
111 
112         return realloc(p, size * need ?: 1);
113 }
114 #endif
115 
memdup_multiply(const void * p,size_t size,size_t need)116 _alloc_(2, 3) static inline void *memdup_multiply(const void *p, size_t size, size_t need) {
117         if (size_multiply_overflow(size, need))
118                 return NULL;
119 
120         return memdup(p, size * need);
121 }
122 
123 /* Note that we can't decorate this function with _alloc_() since the returned memory area is one byte larger
124  * than the product of its parameters. */
memdup_suffix0_multiply(const void * p,size_t size,size_t need)125 static inline void *memdup_suffix0_multiply(const void *p, size_t size, size_t need) {
126         if (size_multiply_overflow(size, need))
127                 return NULL;
128 
129         return memdup_suffix0(p, size * need);
130 }
131 
132 void* greedy_realloc(void **p, size_t need, size_t size);
133 void* greedy_realloc0(void **p, size_t need, size_t size);
134 
135 #define GREEDY_REALLOC(array, need)                                     \
136         greedy_realloc((void**) &(array), (need), sizeof((array)[0]))
137 
138 #define GREEDY_REALLOC0(array, need)                                    \
139         greedy_realloc0((void**) &(array), (need), sizeof((array)[0]))
140 
141 #define alloca0(n)                                      \
142         ({                                              \
143                 char *_new_;                            \
144                 size_t _len_ = n;                       \
145                 _new_ = alloca_safe(_len_);             \
146                 memset(_new_, 0, _len_);                \
147         })
148 
149 /* It's not clear what alignment glibc/gcc alloca() guarantee, hence provide a guaranteed safe version */
150 #define alloca_align(size, align)                                       \
151         ({                                                              \
152                 void *_ptr_;                                            \
153                 size_t _mask_ = (align) - 1;                            \
154                 size_t _size_ = size;                                   \
155                 _ptr_ = alloca_safe(_size_ + _mask_);                   \
156                 (void*)(((uintptr_t)_ptr_ + _mask_) & ~_mask_);         \
157         })
158 
159 #define alloca0_align(size, align)                                      \
160         ({                                                              \
161                 void *_new_;                                            \
162                 size_t _xsize_ = (size);                                \
163                 _new_ = alloca_align(_xsize_, (align));                 \
164                 memset(_new_, 0, _xsize_);                              \
165         })
166 
167 #if HAS_FEATURE_MEMORY_SANITIZER
168 #  define msan_unpoison(r, s) __msan_unpoison(r, s)
169 #else
170 #  define msan_unpoison(r, s)
171 #endif
172 
173 /* This returns the number of usable bytes in a malloc()ed region as per malloc_usable_size(), in a way that
174  * is compatible with _FORTIFY_SOURCES. If _FORTIFY_SOURCES is used many memory operations will take the
175  * object size as returned by __builtin_object_size() into account. Hence, let's return the smaller size of
176  * malloc_usable_size() and __builtin_object_size() here, so that we definitely operate in safe territory by
177  * both the compiler's and libc's standards. Note that _FORTIFY_SOURCES=3 handles also dynamically allocated
178  * objects and thus it's safer using __builtin_dynamic_object_size if _FORTIFY_SOURCES=3 is used (#22801).
179  * Moreover, when NULL is passed malloc_usable_size() is documented to return zero, and
180  * __builtin_object_size() returns SIZE_MAX too, hence we also return a sensible value of 0 in this corner
181  * case. */
182 
183 #if defined __has_builtin
184 #  if __has_builtin(__builtin_dynamic_object_size)
185 #    define MALLOC_SIZEOF_SAFE(x) \
186         MIN(malloc_usable_size(x), __builtin_dynamic_object_size(x, 0))
187 #  endif
188 #endif
189 
190 #ifndef MALLOC_SIZEOF_SAFE
191 #define MALLOC_SIZEOF_SAFE(x) \
192         MIN(malloc_usable_size(x), __builtin_object_size(x, 0))
193 #endif
194 
195 /* Inspired by ELEMENTSOF() but operates on malloc()'ed memory areas: typesafely returns the number of items
196  * that fit into the specified memory block */
197 #define MALLOC_ELEMENTSOF(x) \
198         (__builtin_choose_expr(                                         \
199                 __builtin_types_compatible_p(typeof(x), typeof(&*(x))), \
200                 MALLOC_SIZEOF_SAFE(x)/sizeof((x)[0]),                   \
201                 VOID_0))
202 
203 
204 /* These are like strdupa()/strndupa(), but honour ALLOCA_MAX */
205 #define strdupa_safe(s)                                                 \
206         ({                                                              \
207                 const char *_t = (s);                                   \
208                 (char*) memdupa_suffix0(_t, strlen(_t));                \
209         })
210 
211 #define strndupa_safe(s, n)                                             \
212         ({                                                              \
213                 const char *_t = (s);                                   \
214                 (char*) memdupa_suffix0(_t, strnlen(_t, (n)));          \
215         })
216 
217 #include "memory-util.h"
218