1 /*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #pragma once
18
19 /**
20 * @file malloc.h
21 * @brief Heap memory allocation.
22 *
23 * [Debugging Native Memory Use](https://source.android.com/devices/tech/debug/native-memory)
24 * is the canonical source for documentation on Android's heap debugging
25 * features.
26 */
27
28 #include <sys/cdefs.h>
29 #include <stddef.h>
30 #include <stdio.h>
31
32 __BEGIN_DECLS
33
34 #define __BIONIC_ALLOC_SIZE(...) __attribute__((__alloc_size__(__VA_ARGS__)))
35
36 /**
37 * [malloc(3)](https://man7.org/linux/man-pages/man3/malloc.3.html) allocates
38 * memory on the heap.
39 *
40 * Returns a pointer to the allocated memory on success and returns a null
41 * pointer and sets `errno` on failure.
42 *
43 * Note that Android (like most Unix systems) allows "overcommit". This
44 * allows processes to allocate more memory than the system has, provided
45 * they don't use it all. This works because only "dirty" pages that have
46 * been written to actually require physical memory. In practice, this
47 * means that it's rare to see memory allocation functions return a null
48 * pointer, and that a non-null pointer does not mean that you actually
49 * have all of the memory you asked for.
50 *
51 * Note also that the Linux Out Of Memory (OOM) killer behaves differently
52 * for code run via `adb shell`. The assumption is that if you ran
53 * something via `adb shell` you're a developer who actually wants the
54 * device to do what you're asking it to do _even if_ that means killing
55 * other processes. Obviously this is not the case for apps, which will
56 * be killed in preference to killing other processes.
57 */
58 __nodiscard void* _Nullable malloc(size_t __byte_count) __mallocfunc __BIONIC_ALLOC_SIZE(1);
59
60 /**
61 * [calloc(3)](https://man7.org/linux/man-pages/man3/calloc.3.html) allocates
62 * and clears memory on the heap.
63 *
64 * Returns a pointer to the allocated memory on success and returns a null
65 * pointer and sets `errno` on failure (but see the notes for malloc()).
66 */
67 __nodiscard void* _Nullable calloc(size_t __item_count, size_t __item_size) __mallocfunc __BIONIC_ALLOC_SIZE(1,2);
68
69 /**
70 * [realloc(3)](https://man7.org/linux/man-pages/man3/realloc.3.html) resizes
71 * allocated memory on the heap.
72 *
73 * Returns a pointer (which may be different from `__ptr`) to the resized
74 * memory on success and returns a null pointer and sets `errno` on failure
75 * (but see the notes for malloc()).
76 */
77 __nodiscard void* _Nullable realloc(void* _Nullable __ptr, size_t __byte_count) __BIONIC_ALLOC_SIZE(2);
78
79 /**
80 * [reallocarray(3)](https://man7.org/linux/man-pages/man3/reallocarray.3.html)
81 * resizes allocated memory on the heap.
82 *
83 * Equivalent to `realloc(__ptr, __item_count * __item_size)` but fails if the
84 * multiplication overflows.
85 *
86 * Returns a pointer (which may be different from `__ptr`) to the resized
87 * memory on success and returns a null pointer and sets `errno` on failure
88 * (but see the notes for malloc()).
89 */
90 #if __ANDROID_API__ >= 29
91 __nodiscard void* _Nullable reallocarray(void* _Nullable __ptr, size_t __item_count, size_t __item_size) __BIONIC_ALLOC_SIZE(2, 3) __INTRODUCED_IN(29);
92 #elif defined(__ANDROID_UNAVAILABLE_SYMBOLS_ARE_WEAK__)
93 #include <errno.h>
reallocarray(void * _Nullable __ptr,size_t __item_count,size_t __item_size)94 static __inline __nodiscard void* _Nullable reallocarray(void* _Nullable __ptr, size_t __item_count, size_t __item_size) __BIONIC_ALLOC_SIZE(2, 3) {
95 size_t __new_size;
96 if (__builtin_mul_overflow(__item_count, __item_size, &__new_size)) {
97 errno = ENOMEM;
98 return NULL;
99 }
100 return realloc(__ptr, __new_size);
101 }
102 #endif
103
104 /**
105 * [free(3)](https://man7.org/linux/man-pages/man3/free.3.html) deallocates
106 * memory on the heap.
107 */
108 void free(void* _Nullable __ptr);
109
110 /**
111 * [memalign(3)](https://man7.org/linux/man-pages/man3/memalign.3.html) allocates
112 * memory on the heap with the required alignment.
113 *
114 * Returns a pointer to the allocated memory on success and returns a null
115 * pointer and sets `errno` on failure (but see the notes for malloc()).
116 *
117 * See also posix_memalign().
118 */
119 __nodiscard void* _Nullable memalign(size_t __alignment, size_t __byte_count) __mallocfunc __BIONIC_ALLOC_SIZE(2);
120
121 /**
122 * [malloc_usable_size(3)](https://man7.org/linux/man-pages/man3/malloc_usable_size.3.html)
123 * returns the actual size of the given heap block.
124 */
125 __nodiscard size_t malloc_usable_size(const void* _Nullable __ptr)
126 #if defined(_FORTIFY_SOURCE)
127 __clang_error_if(_FORTIFY_SOURCE == 3, "malloc_usable_size() and _FORTIFY_SOURCE=3 are incompatible")
128 #endif
129 ;
130
131 #define __MALLINFO_BODY \
132 /** Total number of non-mmapped bytes currently allocated from OS. */ \
133 size_t arena; \
134 /** Number of free chunks. */ \
135 size_t ordblks; \
136 /** (Unused.) */ \
137 size_t smblks; \
138 /** (Unused.) */ \
139 size_t hblks; \
140 /** Total number of bytes in mmapped regions. */ \
141 size_t hblkhd; \
142 /** Maximum total allocated space; greater than total if trimming has occurred. */ \
143 size_t usmblks; \
144 /** (Unused.) */ \
145 size_t fsmblks; \
146 /** Total allocated space (normal or mmapped.) */ \
147 size_t uordblks; \
148 /** Total free space. */ \
149 size_t fordblks; \
150 /** Upper bound on number of bytes releasable by a trim operation. */ \
151 size_t keepcost;
152
153 #ifndef STRUCT_MALLINFO_DECLARED
154 #define STRUCT_MALLINFO_DECLARED 1
155 struct mallinfo { __MALLINFO_BODY };
156 #endif
157
158 /**
159 * [mallinfo(3)](https://man7.org/linux/man-pages/man3/mallinfo.3.html) returns
160 * information about the current state of the heap. Note that mallinfo() is
161 * inherently unreliable and consider using malloc_info() instead.
162 */
163 struct mallinfo mallinfo(void);
164
165 /**
166 * On Android the struct mallinfo and struct mallinfo2 are the same.
167 */
168 struct mallinfo2 { __MALLINFO_BODY };
169
170 /**
171 * [mallinfo2(3)](https://man7.org/linux/man-pages/man3/mallinfo2.3.html) returns
172 * information about the current state of the heap. Note that mallinfo2() is
173 * inherently unreliable and consider using malloc_info() instead.
174 */
175 struct mallinfo2 mallinfo2(void) __RENAME(mallinfo);
176
177 /**
178 * [malloc_info(3)](https://man7.org/linux/man-pages/man3/malloc_info.3.html)
179 * writes information about the current state of the heap to the given stream.
180 *
181 * The XML structure for malloc_info() is as follows:
182 * ```
183 * <malloc version="jemalloc-1">
184 * <heap nr="INT">
185 * <allocated-large>INT</allocated-large>
186 * <allocated-huge>INT</allocated-huge>
187 * <allocated-bins>INT</allocated-bins>
188 * <bins-total>INT</bins-total>
189 * <bin nr="INT">
190 * <allocated>INT</allocated>
191 * <nmalloc>INT</nmalloc>
192 * <ndalloc>INT</ndalloc>
193 * </bin>
194 * <!-- more bins -->
195 * </heap>
196 * <!-- more heaps -->
197 * </malloc>
198 * ```
199 *
200 * Available since API level 23.
201 */
202
203 #if __BIONIC_AVAILABILITY_GUARD(23)
204 int malloc_info(int __must_be_zero, FILE* _Nonnull __fp) __INTRODUCED_IN(23);
205 #endif /* __BIONIC_AVAILABILITY_GUARD(23) */
206
207
208 /**
209 * mallopt() option to set the decay time. Valid values are -1, 0 and 1.
210 * -1 : Disable the releasing of unused pages. This value is available since
211 * API level 35.
212 * 0 : Release the unused pages immediately.
213 * 1 : Release the unused pages at a device-specific interval.
214 *
215 * Available since API level 27.
216 */
217 #define M_DECAY_TIME (-100)
218 /**
219 * mallopt() option to immediately purge any memory not in use. This
220 * will release the memory back to the kernel. The value is ignored.
221 *
222 * Available since API level 28.
223 */
224 #define M_PURGE (-101)
225 /**
226 * mallopt() option to immediately purge all possible memory back to
227 * the kernel. This call can take longer than a normal purge since it
228 * examines everything. In some cases, it can take more than twice the
229 * time of a M_PURGE call. The value is ignored.
230 *
231 * Available since API level 34.
232 */
233 #define M_PURGE_ALL (-104)
234
235 /**
236 * mallopt() option to tune the allocator's choice of memory tags to
237 * make it more likely that a certain class of memory errors will be
238 * detected. This is only relevant if MTE is enabled in this process
239 * and ignored otherwise. The value argument should be one of the
240 * M_MEMTAG_TUNING_* flags.
241 * NOTE: This is only available in scudo.
242 *
243 * Available since API level 31.
244 */
245 #define M_MEMTAG_TUNING (-102)
246
247 /**
248 * When passed as a value of M_MEMTAG_TUNING mallopt() call, enables
249 * deterministic detection of linear buffer overflow and underflow
250 * bugs by assigning distinct tag values to adjacent allocations. This
251 * mode has a slightly reduced chance to detect use-after-free bugs
252 * because only half of the possible tag values are available for each
253 * memory location.
254 *
255 * Please keep in mind that MTE can not detect overflow within the
256 * same tag granule (16-byte aligned chunk), and can miss small
257 * overflows even in this mode. Such overflow can not be the cause of
258 * a memory corruption, because the memory within one granule is never
259 * used for multiple allocations.
260 */
261 #define M_MEMTAG_TUNING_BUFFER_OVERFLOW 0
262
263 /**
264 * When passed as a value of M_MEMTAG_TUNING mallopt() call, enables
265 * independently randomized tags for uniform ~93% probability of
266 * detecting both spatial (buffer overflow) and temporal (use after
267 * free) bugs.
268 */
269 #define M_MEMTAG_TUNING_UAF 1
270
271 /**
272 * mallopt() option for per-thread memory initialization tuning.
273 * The value argument should be one of:
274 * 1: Disable automatic heap initialization on this thread only.
275 * If memory tagging is enabled, disable as much as possible of the
276 * memory tagging initialization for this thread.
277 * 0: Normal behavior.
278 *
279 * Available since API level 31.
280 */
281 #define M_THREAD_DISABLE_MEM_INIT (-103)
282 /**
283 * mallopt() option to set the maximum number of items in the secondary
284 * cache of the scudo allocator.
285 *
286 * Available since API level 31.
287 */
288 #define M_CACHE_COUNT_MAX (-200)
289 /**
290 * mallopt() option to set the maximum size in bytes of a cacheable item in
291 * the secondary cache of the scudo allocator.
292 *
293 * Available since API level 31.
294 */
295 #define M_CACHE_SIZE_MAX (-201)
296 /**
297 * mallopt() option to increase the maximum number of shared thread-specific
298 * data structures that can be created. This number cannot be decreased,
299 * only increased and only applies to the scudo allocator.
300 *
301 * Available since API level 31.
302 */
303 #define M_TSDS_COUNT_MAX (-202)
304
305 /**
306 * mallopt() option to decide whether heap memory is zero-initialized on
307 * allocation across the whole process. May be called at any time, including
308 * when multiple threads are running. An argument of zero indicates memory
309 * should not be zero-initialized, any other value indicates to initialize heap
310 * memory to zero.
311 *
312 * Note that this memory mitigation is only implemented in scudo and therefore
313 * this will have no effect when using another allocator (such as jemalloc on
314 * Android Go devices).
315 *
316 * Available since API level 31.
317 */
318 #define M_BIONIC_ZERO_INIT (-203)
319
320 /**
321 * mallopt() option to change the heap tagging state. May be called at any
322 * time, including when multiple threads are running.
323 * The value must be one of the M_HEAP_TAGGING_LEVEL_ constants.
324 * NOTE: This is only available in scudo.
325 *
326 * Available since API level 31.
327 */
328 #define M_BIONIC_SET_HEAP_TAGGING_LEVEL (-204)
329
330 /**
331 * Constants for use with the M_BIONIC_SET_HEAP_TAGGING_LEVEL mallopt() option.
332 */
333 enum HeapTaggingLevel {
334 /**
335 * Disable heap tagging and memory tag checks (if supported).
336 * Heap tagging may not be re-enabled after being disabled.
337 */
338 M_HEAP_TAGGING_LEVEL_NONE = 0,
339 #define M_HEAP_TAGGING_LEVEL_NONE M_HEAP_TAGGING_LEVEL_NONE
340 /**
341 * Address-only tagging. Heap pointers have a non-zero tag in the
342 * most significant ("top") byte which is checked in free(). Memory
343 * accesses ignore the tag using arm64's Top Byte Ignore (TBI) feature.
344 */
345 M_HEAP_TAGGING_LEVEL_TBI = 1,
346 #define M_HEAP_TAGGING_LEVEL_TBI M_HEAP_TAGGING_LEVEL_TBI
347 /**
348 * Enable heap tagging and asynchronous memory tag checks (if supported).
349 * Disable stack trace collection.
350 */
351 M_HEAP_TAGGING_LEVEL_ASYNC = 2,
352 #define M_HEAP_TAGGING_LEVEL_ASYNC M_HEAP_TAGGING_LEVEL_ASYNC
353 /**
354 * Enable heap tagging and synchronous memory tag checks (if supported).
355 * Enable stack trace collection.
356 */
357 M_HEAP_TAGGING_LEVEL_SYNC = 3,
358 #define M_HEAP_TAGGING_LEVEL_SYNC M_HEAP_TAGGING_LEVEL_SYNC
359 };
360
361 /**
362 * mallopt() option to print human readable statistics about the memory
363 * allocator to the log. There is no format for this data, each allocator
364 * can use a different format, and the data that is printed can
365 * change at any time. This is expected to be used as a debugging aid.
366 *
367 * Available since API level 35.
368 */
369 #define M_LOG_STATS (-205)
370
371 /**
372 * [mallopt(3)](https://man7.org/linux/man-pages/man3/mallopt.3.html) modifies
373 * heap behavior. Values of `__option` are the `M_` constants from this header.
374 *
375 * Returns 1 on success, 0 on error.
376 *
377 * Available since API level 26.
378 */
379
380 #if __BIONIC_AVAILABILITY_GUARD(26)
381 int mallopt(int __option, int __value) __INTRODUCED_IN(26);
382 #endif /* __BIONIC_AVAILABILITY_GUARD(26) */
383
384
385 /**
386 * [__malloc_hook(3)](https://man7.org/linux/man-pages/man3/__malloc_hook.3.html)
387 * is called to implement malloc(). By default this points to the system's
388 * implementation.
389 *
390 * Available since API level 28.
391 *
392 * See also: [extra documentation](https://android.googlesource.com/platform/bionic/+/main/libc/malloc_hooks/README.md)
393 */
394
395 #if __BIONIC_AVAILABILITY_GUARD(28)
396 extern void* _Nonnull (*volatile _Nonnull __malloc_hook)(size_t __byte_count, const void* _Nonnull __caller) __INTRODUCED_IN(28);
397
398 /**
399 * [__realloc_hook(3)](https://man7.org/linux/man-pages/man3/__realloc_hook.3.html)
400 * is called to implement realloc(). By default this points to the system's
401 * implementation.
402 *
403 * Available since API level 28.
404 *
405 * See also: [extra documentation](https://android.googlesource.com/platform/bionic/+/main/libc/malloc_hooks/README.md)
406 */
407 extern void* _Nonnull (*volatile _Nonnull __realloc_hook)(void* _Nullable __ptr, size_t __byte_count, const void* _Nonnull __caller) __INTRODUCED_IN(28);
408
409 /**
410 * [__free_hook(3)](https://man7.org/linux/man-pages/man3/__free_hook.3.html)
411 * is called to implement free(). By default this points to the system's
412 * implementation.
413 *
414 * Available since API level 28.
415 *
416 * See also: [extra documentation](https://android.googlesource.com/platform/bionic/+/main/libc/malloc_hooks/README.md)
417 */
418 extern void (*volatile _Nonnull __free_hook)(void* _Nullable __ptr, const void* _Nonnull __caller) __INTRODUCED_IN(28);
419
420 /**
421 * [__memalign_hook(3)](https://man7.org/linux/man-pages/man3/__memalign_hook.3.html)
422 * is called to implement memalign(). By default this points to the system's
423 * implementation.
424 *
425 * Available since API level 28.
426 *
427 * See also: [extra documentation](https://android.googlesource.com/platform/bionic/+/main/libc/malloc_hooks/README.md)
428 */
429 extern void* _Nonnull (*volatile _Nonnull __memalign_hook)(size_t __alignment, size_t __byte_count, const void* _Nonnull __caller) __INTRODUCED_IN(28);
430 #endif /* __BIONIC_AVAILABILITY_GUARD(28) */
431
432
433 __END_DECLS
434