1 /*
2  * SPDX-FileCopyrightText: 2019-2021 Espressif Systems (Shanghai) CO LTD
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #pragma once
8 
9 #include <stdint.h>
10 #include <stdlib.h>
11 #include "multi_heap.h"
12 #include <sdkconfig.h>
13 #include "esp_err.h"
14 #include "esp_attr.h"
15 
16 #ifdef __cplusplus
17 extern "C" {
18 #endif
19 
20 #if CONFIG_HEAP_PLACE_FUNCTION_INTO_FLASH
21 #define HEAP_IRAM_ATTR
22 #else
23 #define HEAP_IRAM_ATTR IRAM_ATTR
24 #endif
25 
26 /**
27  * @brief Flags to indicate the capabilities of the various memory systems
28  */
29 #define MALLOC_CAP_EXEC             (1<<0)  ///< Memory must be able to run executable code
30 #define MALLOC_CAP_32BIT            (1<<1)  ///< Memory must allow for aligned 32-bit data accesses
31 #define MALLOC_CAP_8BIT             (1<<2)  ///< Memory must allow for 8/16/...-bit data accesses
32 #define MALLOC_CAP_DMA              (1<<3)  ///< Memory must be able to accessed by DMA
33 #define MALLOC_CAP_PID2             (1<<4)  ///< Memory must be mapped to PID2 memory space (PIDs are not currently used)
34 #define MALLOC_CAP_PID3             (1<<5)  ///< Memory must be mapped to PID3 memory space (PIDs are not currently used)
35 #define MALLOC_CAP_PID4             (1<<6)  ///< Memory must be mapped to PID4 memory space (PIDs are not currently used)
36 #define MALLOC_CAP_PID5             (1<<7)  ///< Memory must be mapped to PID5 memory space (PIDs are not currently used)
37 #define MALLOC_CAP_PID6             (1<<8)  ///< Memory must be mapped to PID6 memory space (PIDs are not currently used)
38 #define MALLOC_CAP_PID7             (1<<9)  ///< Memory must be mapped to PID7 memory space (PIDs are not currently used)
39 #define MALLOC_CAP_SPIRAM           (1<<10) ///< Memory must be in SPI RAM
40 #define MALLOC_CAP_INTERNAL         (1<<11) ///< Memory must be internal; specifically it should not disappear when flash/spiram cache is switched off
41 #define MALLOC_CAP_DEFAULT          (1<<12) ///< Memory can be returned in a non-capability-specific memory allocation (e.g. malloc(), calloc()) call
42 #define MALLOC_CAP_IRAM_8BIT        (1<<13) ///< Memory must be in IRAM and allow unaligned access
43 #define MALLOC_CAP_RETENTION        (1<<14) ///< Memory must be able to accessed by retention DMA
44 #define MALLOC_CAP_RTCRAM           (1<<15) ///< Memory must be in RTC fast memory
45 
46 #define MALLOC_CAP_INVALID          (1<<31) ///< Memory can't be used / list end marker
47 
48 /**
49  * @brief callback called when an allocation operation fails, if registered
50  * @param size in bytes of failed allocation
51  * @param caps capabilities requested of failed allocation
52  * @param function_name function which generated the failure
53  */
54 typedef void (*esp_alloc_failed_hook_t) (size_t size, uint32_t caps, const char * function_name);
55 
56 /**
57  * @brief registers a callback function to be invoked if a memory allocation operation fails
58  * @param callback caller defined callback to be invoked
59  * @return ESP_OK if callback was registered.
60  */
61 esp_err_t heap_caps_register_failed_alloc_callback(esp_alloc_failed_hook_t callback);
62 
63 #ifdef CONFIG_HEAP_USE_HOOKS
64 /**
65  * @brief callback called after every allocation
66  * @param ptr the allocated memory
67  * @param size in bytes of the allocation
68  * @param caps Bitwise OR of MALLOC_CAP_* flags indicating the type of memory allocated.
69  * @note this hook is called on the same thread as the allocation, which may be within a low level operation.
70  * You should refrain from doing heavy work, logging, flash writes, or any locking.
71  */
72 __attribute__((weak)) HEAP_IRAM_ATTR void esp_heap_trace_alloc_hook(void* ptr, size_t size, uint32_t caps);
73 
74 /**
75  * @brief callback called after every free
76  * @param ptr the memory that was freed
77  * @note this hook is called on the same thread as the allocation, which may be within a low level operation.
78  * You should refrain from doing heavy work, logging, flash writes, or any locking.
79  */
80 __attribute__((weak)) HEAP_IRAM_ATTR void esp_heap_trace_free_hook(void* ptr);
81 #endif
82 
83 /**
84  * @brief Allocate a chunk of memory which has the given capabilities
85  *
86  * Equivalent semantics to libc malloc(), for capability-aware memory.
87  *
88  * @param size Size, in bytes, of the amount of memory to allocate
89  * @param caps        Bitwise OR of MALLOC_CAP_* flags indicating the type
90  *                    of memory to be returned
91  *
92  * @return A pointer to the memory allocated on success, NULL on failure
93  */
94 void *heap_caps_malloc(size_t size, uint32_t caps);
95 
96 
97 /**
98  * @brief Free memory previously allocated via heap_caps_malloc() or heap_caps_realloc().
99  *
100  * Equivalent semantics to libc free(), for capability-aware memory.
101  *
102  *  In IDF, ``free(p)`` is equivalent to ``heap_caps_free(p)``.
103  *
104  * @param ptr Pointer to memory previously returned from heap_caps_malloc() or heap_caps_realloc(). Can be NULL.
105  */
106 void heap_caps_free( void *ptr);
107 
108 /**
109  * @brief Reallocate memory previously allocated via heap_caps_malloc() or heap_caps_realloc().
110  *
111  * Equivalent semantics to libc realloc(), for capability-aware memory.
112  *
113  * In IDF, ``realloc(p, s)`` is equivalent to ``heap_caps_realloc(p, s, MALLOC_CAP_8BIT)``.
114  *
115  * 'caps' parameter can be different to the capabilities that any original 'ptr' was allocated with. In this way,
116  * realloc can be used to "move" a buffer if necessary to ensure it meets a new set of capabilities.
117  *
118  * @param ptr Pointer to previously allocated memory, or NULL for a new allocation.
119  * @param size Size of the new buffer requested, or 0 to free the buffer.
120  * @param caps        Bitwise OR of MALLOC_CAP_* flags indicating the type
121  *                    of memory desired for the new allocation.
122  *
123  * @return Pointer to a new buffer of size 'size' with capabilities 'caps', or NULL if allocation failed.
124  */
125 void *heap_caps_realloc( void *ptr, size_t size, uint32_t caps);
126 
127 /**
128  * @brief Allocate an aligned chunk of memory which has the given capabilities
129  *
130  * Equivalent semantics to libc aligned_alloc(), for capability-aware memory.
131  * @param alignment  How the pointer received needs to be aligned
132  *                   must be a power of two
133  * @param size Size, in bytes, of the amount of memory to allocate
134  * @param caps        Bitwise OR of MALLOC_CAP_* flags indicating the type
135  *                    of memory to be returned
136  *
137  * @return A pointer to the memory allocated on success, NULL on failure
138  *
139  *
140  */
141 void *heap_caps_aligned_alloc(size_t alignment, size_t size, uint32_t caps);
142 
143 /**
144  * @brief Used to deallocate memory previously allocated with heap_caps_aligned_alloc
145  *
146  * @param ptr Pointer to the memory allocated
147  * @note This function is deprecated, please consider using heap_caps_free() instead
148  */
149 void __attribute__((deprecated))  heap_caps_aligned_free(void *ptr);
150 
151 /**
152  * @brief Allocate an aligned chunk of memory which has the given capabilities. The initialized value in the memory is set to zero.
153  *
154  * @param alignment  How the pointer received needs to be aligned
155  *                   must be a power of two
156  * @param n    Number of continuing chunks of memory to allocate
157  * @param size Size, in bytes, of a chunk of memory to allocate
158  * @param caps        Bitwise OR of MALLOC_CAP_* flags indicating the type
159  *                    of memory to be returned
160  *
161  * @return A pointer to the memory allocated on success, NULL on failure
162  *
163  */
164 void *heap_caps_aligned_calloc(size_t alignment, size_t n, size_t size, uint32_t caps);
165 
166 
167 /**
168  * @brief Allocate a chunk of memory which has the given capabilities. The initialized value in the memory is set to zero.
169  *
170  * Equivalent semantics to libc calloc(), for capability-aware memory.
171  *
172  * In IDF, ``calloc(p)`` is equivalent to ``heap_caps_calloc(p, MALLOC_CAP_8BIT)``.
173  *
174  * @param n    Number of continuing chunks of memory to allocate
175  * @param size Size, in bytes, of a chunk of memory to allocate
176  * @param caps        Bitwise OR of MALLOC_CAP_* flags indicating the type
177  *                    of memory to be returned
178  *
179  * @return A pointer to the memory allocated on success, NULL on failure
180  */
181 void *heap_caps_calloc(size_t n, size_t size, uint32_t caps);
182 
183 /**
184  * @brief Get the total size of all the regions that have the given capabilities
185  *
186  * This function takes all regions capable of having the given capabilities allocated in them
187  * and adds up the total space they have.
188  *
189  * @param caps        Bitwise OR of MALLOC_CAP_* flags indicating the type
190  *                    of memory
191  *
192  * @return total size in bytes
193  */
194 
195 size_t heap_caps_get_total_size(uint32_t caps);
196 
197 /**
198  * @brief Get the total free size of all the regions that have the given capabilities
199  *
200  * This function takes all regions capable of having the given capabilities allocated in them
201  * and adds up the free space they have.
202  *
203  * @note Note that because of heap fragmentation it is probably not possible to allocate a single block of memory
204  * of this size. Use heap_caps_get_largest_free_block() for this purpose.
205 
206  * @param caps        Bitwise OR of MALLOC_CAP_* flags indicating the type
207  *                    of memory
208  *
209  * @return Amount of free bytes in the regions
210  */
211 size_t heap_caps_get_free_size( uint32_t caps );
212 
213 
214 /**
215  * @brief Get the total minimum free memory of all regions with the given capabilities
216  *
217  * This adds all the low watermarks of the regions capable of delivering the memory
218  * with the given capabilities.
219  *
220  * @note Note the result may be less than the global all-time minimum available heap of this kind, as "low watermarks" are
221  * tracked per-region. Individual regions' heaps may have reached their "low watermarks" at different points in time. However,
222  * this result still gives a "worst case" indication for all-time minimum free heap.
223  *
224  * @param caps        Bitwise OR of MALLOC_CAP_* flags indicating the type
225  *                    of memory
226  *
227  * @return Amount of free bytes in the regions
228  */
229 size_t heap_caps_get_minimum_free_size( uint32_t caps );
230 
231 /**
232  * @brief Get the largest free block of memory able to be allocated with the given capabilities.
233  *
234  * Returns the largest value of ``s`` for which ``heap_caps_malloc(s, caps)`` will succeed.
235  *
236  * @param caps        Bitwise OR of MALLOC_CAP_* flags indicating the type
237  *                    of memory
238  *
239  * @return Size of the largest free block in bytes.
240  */
241 size_t heap_caps_get_largest_free_block( uint32_t caps );
242 
243 
244 /**
245  * @brief Get heap info for all regions with the given capabilities.
246  *
247  * Calls multi_heap_info() on all heaps which share the given capabilities. The information returned is an aggregate
248  * across all matching heaps. The meanings of fields are the same as defined for multi_heap_info_t, except that
249  * ``minimum_free_bytes`` has the same caveats described in heap_caps_get_minimum_free_size().
250  *
251  * @param info        Pointer to a structure which will be filled with relevant
252  *                    heap metadata.
253  * @param caps        Bitwise OR of MALLOC_CAP_* flags indicating the type
254  *                    of memory
255  *
256  */
257 void heap_caps_get_info( multi_heap_info_t *info, uint32_t caps );
258 
259 
260 /**
261  * @brief Print a summary of all memory with the given capabilities.
262  *
263  * Calls multi_heap_info on all heaps which share the given capabilities, and
264  * prints a two-line summary for each, then a total summary.
265  *
266  * @param caps        Bitwise OR of MALLOC_CAP_* flags indicating the type
267  *                    of memory
268  *
269  */
270 void heap_caps_print_heap_info( uint32_t caps );
271 
272 /**
273  * @brief Check integrity of all heap memory in the system.
274  *
275  * Calls multi_heap_check on all heaps. Optionally print errors if heaps are corrupt.
276  *
277  * Calling this function is equivalent to calling heap_caps_check_integrity
278  * with the caps argument set to MALLOC_CAP_INVALID.
279  *
280  * @param print_errors Print specific errors if heap corruption is found.
281  *
282  * @note Please increase the value of `CONFIG_ESP_INT_WDT_TIMEOUT_MS` when using this API
283  * with PSRAM enabled.
284  *
285  * @return True if all heaps are valid, False if at least one heap is corrupt.
286  */
287 bool heap_caps_check_integrity_all(bool print_errors);
288 
289 /**
290  * @brief Check integrity of all heaps with the given capabilities.
291  *
292  * Calls multi_heap_check on all heaps which share the given capabilities. Optionally
293  * print errors if the heaps are corrupt.
294  *
295  * See also heap_caps_check_integrity_all to check all heap memory
296  * in the system and heap_caps_check_integrity_addr to check memory
297  * around a single address.
298  *
299  * @param caps        Bitwise OR of MALLOC_CAP_* flags indicating the type
300  *                    of memory
301  * @param print_errors Print specific errors if heap corruption is found.
302  *
303  * @note Please increase the value of `CONFIG_ESP_INT_WDT_TIMEOUT_MS` when using this API
304  * with PSRAM capability flag.
305  *
306  * @return True if all heaps are valid, False if at least one heap is corrupt.
307  */
308 bool heap_caps_check_integrity(uint32_t caps, bool print_errors);
309 
310 /**
311  * @brief Check integrity of heap memory around a given address.
312  *
313  * This function can be used to check the integrity of a single region of heap memory,
314  * which contains the given address.
315  *
316  * This can be useful if debugging heap integrity for corruption at a known address,
317  * as it has a lower overhead than checking all heap regions. Note that if the corrupt
318  * address moves around between runs (due to timing or other factors) then this approach
319  * won't work, and you should call heap_caps_check_integrity or
320  * heap_caps_check_integrity_all instead.
321  *
322  * @note The entire heap region around the address is checked, not only the adjacent
323  * heap blocks.
324  *
325  * @param addr Address in memory. Check for corruption in region containing this address.
326  * @param print_errors Print specific errors if heap corruption is found.
327  *
328  * @return True if the heap containing the specified address is valid,
329  * False if at least one heap is corrupt or the address doesn't belong to a heap region.
330  */
331 bool heap_caps_check_integrity_addr(intptr_t addr, bool print_errors);
332 
333 /**
334  * @brief Enable malloc() in external memory and set limit below which
335  *        malloc() attempts are placed in internal memory.
336  *
337  * When external memory is in use, the allocation strategy is to initially try to
338  * satisfy smaller allocation requests with internal memory and larger requests
339  * with external memory. This sets the limit between the two, as well as generally
340  * enabling allocation in external memory.
341  *
342  * @param limit       Limit, in bytes.
343  */
344 void heap_caps_malloc_extmem_enable(size_t limit);
345 
346 /**
347  * @brief Allocate a chunk of memory as preference in decreasing order.
348  *
349  * @attention The variable parameters are bitwise OR of MALLOC_CAP_* flags indicating the type of memory.
350  *            This API prefers to allocate memory with the first parameter. If failed, allocate memory with
351  *            the next parameter. It will try in this order until allocating a chunk of memory successfully
352  *            or fail to allocate memories with any of the parameters.
353  *
354  * @param size Size, in bytes, of the amount of memory to allocate
355  * @param num Number of variable parameters
356  *
357  * @return A pointer to the memory allocated on success, NULL on failure
358  */
359 void *heap_caps_malloc_prefer( size_t size, size_t num, ... );
360 
361 /**
362  * @brief Reallocate a chunk of memory as preference in decreasing order.
363  *
364  * @param ptr Pointer to previously allocated memory, or NULL for a new allocation.
365  * @param size Size of the new buffer requested, or 0 to free the buffer.
366  * @param num Number of variable paramters
367  *
368  * @return Pointer to a new buffer of size 'size', or NULL if allocation failed.
369  */
370 void *heap_caps_realloc_prefer( void *ptr, size_t size, size_t num, ... );
371 
372 /**
373  * @brief Allocate a chunk of memory as preference in decreasing order.
374  *
375  * @param n    Number of continuing chunks of memory to allocate
376  * @param size Size, in bytes, of a chunk of memory to allocate
377  * @param num  Number of variable paramters
378  *
379  * @return A pointer to the memory allocated on success, NULL on failure
380  */
381 void *heap_caps_calloc_prefer( size_t n, size_t size, size_t num, ... );
382 
383 /**
384  * @brief Dump the full structure of all heaps with matching capabilities.
385  *
386  * Prints a large amount of output to serial (because of locking limitations,
387  * the output bypasses stdout/stderr). For each (variable sized) block
388  * in each matching heap, the following output is printed on a single line:
389  *
390  * - Block address (the data buffer returned by malloc is 4 bytes after this
391  *   if heap debugging is set to Basic, or 8 bytes otherwise).
392  * - Data size (the data size may be larger than the size requested by malloc,
393  *   either due to heap fragmentation or because of heap debugging level).
394  * - Address of next block in the heap.
395  * - If the block is free, the address of the next free block is also printed.
396  *
397  * @param caps        Bitwise OR of MALLOC_CAP_* flags indicating the type
398  *                    of memory
399  */
400 void heap_caps_dump(uint32_t caps);
401 
402 /**
403  * @brief Dump the full structure of all heaps.
404  *
405  * Covers all registered heaps. Prints a large amount of output to serial.
406  *
407  * Output is the same as for heap_caps_dump.
408  *
409  */
410 void heap_caps_dump_all(void);
411 
412 /**
413  * @brief Return the size that a particular pointer was allocated with.
414  *
415  * @param ptr Pointer to currently allocated heap memory. Must be a pointer value previously
416  * returned by heap_caps_malloc, malloc, calloc, etc. and not yet freed.
417  *
418  * @note The app will crash with an assertion failure if the pointer is not valid.
419  *
420  * @return Size of the memory allocated at this block.
421  *
422  */
423 size_t heap_caps_get_allocated_size( void *ptr );
424 
425 #ifdef __cplusplus
426 }
427 #endif
428