2 * copyright (c) 2006 Michael Niedermayer <michaelni@gmx.at>
4 * This file is part of FFmpeg.
6 * FFmpeg is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * FFmpeg is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with FFmpeg; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
24 * Memory handling functions
33 #include "attributes.h"
38 * @addtogroup lavu_mem
39 * Utilities for manipulating memory.
41 * FFmpeg has several applications of memory that are not required of a typical
42 * program. For example, the computing-heavy components like video decoding and
43 * encoding can be sped up significantly through the use of aligned memory.
45 * However, for each of FFmpeg's applications of memory, there might not be a
46 * recognized or standardized API for that specific use. Memory alignment, for
47 * instance, varies wildly depending on operating systems, architectures, and
48 * compilers. Hence, this component of @ref libavutil is created to make
49 * dealing with memory consistently possible on all platforms.
53 * @defgroup lavu_mem_macros Alignment Macros
54 * Helper macros for declaring aligned variables.
59 * @def DECLARE_ALIGNED(n,t,v)
60 * Declare a variable that is aligned in memory.
63 * DECLARE_ALIGNED(16, uint16_t, aligned_int) = 42;
64 * DECLARE_ALIGNED(32, uint8_t, aligned_array)[128];
66 * // The default-alignment equivalent would be
67 * uint16_t aligned_int = 42;
68 * uint8_t aligned_array[128];
71 * @param n Minimum alignment in bytes
72 * @param t Type of the variable (or array element)
73 * @param v Name of the variable
77 * @def DECLARE_ASM_CONST(n,t,v)
78 * Declare a static constant aligned variable appropriate for use in inline
82 * DECLARE_ASM_CONST(16, uint64_t, pw_08) = UINT64_C(0x0008000800080008);
85 * @param n Minimum alignment in bytes
86 * @param t Type of the variable (or array element)
87 * @param v Name of the variable
90 #if defined(__INTEL_COMPILER) && __INTEL_COMPILER < 1110 || defined(__SUNPRO_C)
91 #define DECLARE_ALIGNED(n,t,v) t __attribute__ ((aligned (n))) v
92 #define DECLARE_ASM_CONST(n,t,v) const t __attribute__ ((aligned (n))) v
93 #elif defined(__TI_COMPILER_VERSION__)
94 #define DECLARE_ALIGNED(n,t,v) \
95 AV_PRAGMA(DATA_ALIGN(v,n)) \
96 t __attribute__((aligned(n))) v
97 #define DECLARE_ASM_CONST(n,t,v) \
98 AV_PRAGMA(DATA_ALIGN(v,n)) \
99 static const t __attribute__((aligned(n))) v
100 #elif defined(__DJGPP__)
101 #define DECLARE_ALIGNED(n,t,v) t __attribute__ ((aligned (FFMIN(n, 16)))) v
102 #define DECLARE_ASM_CONST(n,t,v) static const t av_used __attribute__ ((aligned (FFMIN(n, 16)))) v
103 #elif defined(__GNUC__) || defined(__clang__)
104 #define DECLARE_ALIGNED(n,t,v) t __attribute__ ((aligned (n))) v
105 #define DECLARE_ASM_CONST(n,t,v) static const t av_used __attribute__ ((aligned (n))) v
106 #elif defined(_MSC_VER)
107 #define DECLARE_ALIGNED(n,t,v) __declspec(align(n)) t v
108 #define DECLARE_ASM_CONST(n,t,v) __declspec(align(n)) static const t v
110 #define DECLARE_ALIGNED(n,t,v) t v
111 #define DECLARE_ASM_CONST(n,t,v) static const t v
119 * @defgroup lavu_mem_attrs Function Attributes
120 * Function attributes applicable to memory handling functions.
122 * These function attributes can help compilers emit more useful warnings, or
123 * generate better code.
128 * @def av_malloc_attrib
129 * Function attribute denoting a malloc-like function.
131 * @see <a href="https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#index-g_t_0040code_007bmalloc_007d-function-attribute-3251">Function attribute `malloc` in GCC's documentation</a>
134 #if AV_GCC_VERSION_AT_LEAST(3,1)
135 #define av_malloc_attrib __attribute__((__malloc__))
137 #define av_malloc_attrib
141 * @def av_alloc_size(...)
142 * Function attribute used on a function that allocates memory, whose size is
143 * given by the specified parameter(s).
146 * void *av_malloc(size_t size) av_alloc_size(1);
147 * void *av_calloc(size_t nmemb, size_t size) av_alloc_size(1, 2);
150 * @param ... One or two parameter indexes, separated by a comma
152 * @see <a href="https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#index-g_t_0040code_007balloc_005fsize_007d-function-attribute-3220">Function attribute `alloc_size` in GCC's documentation</a>
155 #if AV_GCC_VERSION_AT_LEAST(4,3)
156 #define av_alloc_size(...) __attribute__((alloc_size(__VA_ARGS__)))
158 #define av_alloc_size(...)
166 * @defgroup lavu_mem_funcs Heap Management
167 * Functions responsible for allocating, freeing, and copying memory.
169 * All memory allocation functions have a built-in upper limit of `INT_MAX`
170 * bytes. This may be changed with av_max_alloc(), although exercise extreme
171 * caution when doing so.
177 * Allocate a memory block with alignment suitable for all memory accesses
178 * (including vectors if available on the CPU).
180 * @param size Size in bytes for the memory block to be allocated
181 * @return Pointer to the allocated block, or `NULL` if the block cannot
185 void *av_malloc(size_t size) av_malloc_attrib av_alloc_size(1);
188 * Allocate a memory block with alignment suitable for all memory accesses
189 * (including vectors if available on the CPU) and zero all the bytes of the
192 * @param size Size in bytes for the memory block to be allocated
193 * @return Pointer to the allocated block, or `NULL` if it cannot be allocated
196 void *av_mallocz(size_t size) av_malloc_attrib av_alloc_size(1);
199 * Allocate a memory block for an array with av_malloc().
201 * The allocated memory will have size `size * nmemb` bytes.
203 * @param nmemb Number of element
204 * @param size Size of a single element
205 * @return Pointer to the allocated block, or `NULL` if the block cannot
209 av_alloc_size(1, 2) void *av_malloc_array(size_t nmemb, size_t size);
212 * Allocate a memory block for an array with av_mallocz().
214 * The allocated memory will have size `size * nmemb` bytes.
216 * @param nmemb Number of elements
217 * @param size Size of the single element
218 * @return Pointer to the allocated block, or `NULL` if the block cannot
222 * @see av_malloc_array()
224 av_alloc_size(1, 2) void *av_mallocz_array(size_t nmemb, size_t size);
227 * Non-inlined equivalent of av_mallocz_array().
229 * Created for symmetry with the calloc() C function.
231 void *av_calloc(size_t nmemb, size_t size) av_malloc_attrib;
234 * Allocate, reallocate, or free a block of memory.
236 * If `ptr` is `NULL` and `size` > 0, allocate a new block. If `size` is
237 * zero, free the memory block pointed to by `ptr`. Otherwise, expand or
238 * shrink that block of memory according to `size`.
240 * @param ptr Pointer to a memory block already allocated with
241 * av_realloc() or `NULL`
242 * @param size Size in bytes of the memory block to be allocated or
245 * @return Pointer to a newly-reallocated block or `NULL` if the block
246 * cannot be reallocated or the function is used to free the memory block
248 * @warning Unlike av_malloc(), the returned pointer is not guaranteed to be
250 * @see av_fast_realloc()
253 void *av_realloc(void *ptr, size_t size) av_alloc_size(2);
256 * Allocate, reallocate, or free a block of memory through a pointer to a
259 * If `*ptr` is `NULL` and `size` > 0, allocate a new block. If `size` is
260 * zero, free the memory block pointed to by `*ptr`. Otherwise, expand or
261 * shrink that block of memory according to `size`.
263 * @param[in,out] ptr Pointer to a pointer to a memory block already allocated
264 * with av_realloc(), or a pointer to `NULL`. The pointer
265 * is updated on success, or freed on failure.
266 * @param[in] size Size in bytes for the memory block to be allocated or
269 * @return Zero on success, an AVERROR error code on failure
271 * @warning Unlike av_malloc(), the allocated memory is not guaranteed to be
274 av_warn_unused_result
275 int av_reallocp(void *ptr, size_t size);
278 * Allocate, reallocate, or free a block of memory.
280 * This function does the same thing as av_realloc(), except:
281 * - It takes two size arguments and allocates `nelem * elsize` bytes,
282 * after checking the result of the multiplication for integer overflow.
283 * - It frees the input block in case of failure, thus avoiding the memory
284 * leak with the classic
286 * buf = realloc(buf);
292 void *av_realloc_f(void *ptr, size_t nelem, size_t elsize);
295 * Allocate, reallocate, or free an array.
297 * If `ptr` is `NULL` and `nmemb` > 0, allocate a new block. If
298 * `nmemb` is zero, free the memory block pointed to by `ptr`.
300 * @param ptr Pointer to a memory block already allocated with
301 * av_realloc() or `NULL`
302 * @param nmemb Number of elements in the array
303 * @param size Size of the single element of the array
305 * @return Pointer to a newly-reallocated block or NULL if the block
306 * cannot be reallocated or the function is used to free the memory block
308 * @warning Unlike av_malloc(), the allocated memory is not guaranteed to be
310 * @see av_reallocp_array()
312 av_alloc_size(2, 3) void *av_realloc_array(void *ptr, size_t nmemb, size_t size);
315 * Allocate, reallocate, or free an array through a pointer to a pointer.
317 * If `*ptr` is `NULL` and `nmemb` > 0, allocate a new block. If `nmemb` is
318 * zero, free the memory block pointed to by `*ptr`.
320 * @param[in,out] ptr Pointer to a pointer to a memory block already
321 * allocated with av_realloc(), or a pointer to `NULL`.
322 * The pointer is updated on success, or freed on failure.
323 * @param[in] nmemb Number of elements
324 * @param[in] size Size of the single element
326 * @return Zero on success, an AVERROR error code on failure
328 * @warning Unlike av_malloc(), the allocated memory is not guaranteed to be
331 av_alloc_size(2, 3) int av_reallocp_array(void *ptr, size_t nmemb, size_t size);
334 * Reallocate the given buffer if it is not large enough, otherwise do nothing.
336 * If the given buffer is `NULL`, then a new uninitialized buffer is allocated.
338 * If the given buffer is not large enough, and reallocation fails, `NULL` is
339 * returned and `*size` is set to 0, but the original buffer is not changed or
342 * A typical use pattern follows:
345 * uint8_t *buf = ...;
346 * uint8_t *new_buf = av_fast_realloc(buf, ¤t_size, size_needed);
348 * // Allocation failed; clean up original buffer
350 * return AVERROR(ENOMEM);
354 * @param[in,out] ptr Already allocated buffer, or `NULL`
355 * @param[in,out] size Pointer to current size of buffer `ptr`. `*size` is
356 * changed to `min_size` in case of success or 0 in
358 * @param[in] min_size New size of buffer `ptr`
359 * @return `ptr` if the buffer is large enough, a pointer to newly reallocated
360 * buffer if the buffer was not large enough, or `NULL` in case of
363 * @see av_fast_malloc()
365 void *av_fast_realloc(void *ptr, unsigned int *size, size_t min_size);
368 * Allocate a buffer, reusing the given one if large enough.
370 * Contrary to av_fast_realloc(), the current buffer contents might not be
371 * preserved and on error the old buffer is freed, thus no special handling to
372 * avoid memleaks is necessary.
374 * `*ptr` is allowed to be `NULL`, in which case allocation always happens if
375 * `size_needed` is greater than 0.
378 * uint8_t *buf = ...;
379 * av_fast_malloc(&buf, ¤t_size, size_needed);
381 * // Allocation failed; buf already freed
382 * return AVERROR(ENOMEM);
386 * @param[in,out] ptr Pointer to pointer to an already allocated buffer.
387 * `*ptr` will be overwritten with pointer to new
388 * buffer on success or `NULL` on failure
389 * @param[in,out] size Pointer to current size of buffer `*ptr`. `*size` is
390 * changed to `min_size` in case of success or 0 in
392 * @param[in] min_size New size of buffer `*ptr`
394 * @see av_fast_mallocz()
396 void av_fast_malloc(void *ptr, unsigned int *size, size_t min_size);
399 * Allocate and clear a buffer, reusing the given one if large enough.
401 * Like av_fast_malloc(), but all newly allocated space is initially cleared.
402 * Reused buffer is not cleared.
404 * `*ptr` is allowed to be `NULL`, in which case allocation always happens if
405 * `size_needed` is greater than 0.
407 * @param[in,out] ptr Pointer to pointer to an already allocated buffer.
408 * `*ptr` will be overwritten with pointer to new
409 * buffer on success or `NULL` on failure
410 * @param[in,out] size Pointer to current size of buffer `*ptr`. `*size` is
411 * changed to `min_size` in case of success or 0 in
413 * @param[in] min_size New size of buffer `*ptr`
414 * @see av_fast_malloc()
416 void av_fast_mallocz(void *ptr, unsigned int *size, size_t min_size);
419 * Free a memory block which has been allocated with a function of av_malloc()
420 * or av_realloc() family.
422 * @param ptr Pointer to the memory block which should be freed.
424 * @note `ptr = NULL` is explicitly allowed.
425 * @note It is recommended that you use av_freep() instead, to prevent leaving
426 * behind dangling pointers.
429 void av_free(void *ptr);
432 * Free a memory block which has been allocated with a function of av_malloc()
433 * or av_realloc() family, and set the pointer pointing to it to `NULL`.
436 * uint8_t *buf = av_malloc(16);
438 * // buf now contains a dangling pointer to freed memory, and accidental
439 * // dereference of buf will result in a use-after-free, which may be a
442 * uint8_t *buf = av_malloc(16);
444 * // buf is now NULL, and accidental dereference will only result in a
445 * // NULL-pointer dereference.
448 * @param ptr Pointer to the pointer to the memory block which should be freed
449 * @note `*ptr = NULL` is safe and leads to no action.
452 void av_freep(void *ptr);
455 * Duplicate a string.
457 * @param s String to be duplicated
458 * @return Pointer to a newly-allocated string containing a
459 * copy of `s` or `NULL` if the string cannot be allocated
462 char *av_strdup(const char *s) av_malloc_attrib;
465 * Duplicate a substring of a string.
467 * @param s String to be duplicated
468 * @param len Maximum length of the resulting string (not counting the
470 * @return Pointer to a newly-allocated string containing a
471 * substring of `s` or `NULL` if the string cannot be allocated
473 char *av_strndup(const char *s, size_t len) av_malloc_attrib;
476 * Duplicate a buffer with av_malloc().
478 * @param p Buffer to be duplicated
479 * @param size Size in bytes of the buffer copied
480 * @return Pointer to a newly allocated buffer containing a
481 * copy of `p` or `NULL` if the buffer cannot be allocated
483 void *av_memdup(const void *p, size_t size);
486 * Overlapping memcpy() implementation.
488 * @param dst Destination buffer
489 * @param back Number of bytes back to start copying (i.e. the initial size of
490 * the overlapping window); must be > 0
491 * @param cnt Number of bytes to copy; must be >= 0
493 * @note `cnt > back` is valid, this will copy the bytes we just copied,
494 * thus creating a repeating pattern with a period length of `back`.
496 void av_memcpy_backptr(uint8_t *dst, int back, int cnt);
503 * @defgroup lavu_mem_dynarray Dynamic Array
505 * Utilities to make an array grow when needed.
507 * Sometimes, the programmer would want to have an array that can grow when
508 * needed. The libavutil dynamic array utilities fill that need.
510 * libavutil supports two systems of appending elements onto a dynamically
511 * allocated array, the first one storing the pointer to the value in the
512 * array, and the second storing the value directly. In both systems, the
513 * caller is responsible for maintaining a variable containing the length of
514 * the array, as well as freeing of the array after use.
516 * The first system stores pointers to values in a block of dynamically
517 * allocated memory. Since only pointers are stored, the function does not need
518 * to know the size of the type. Both av_dynarray_add() and
519 * av_dynarray_add_nofree() implement this system.
522 * type **array = NULL; //< an array of pointers to values
523 * int nb = 0; //< a variable to keep track of the length of the array
525 * type to_be_added = ...;
526 * type to_be_added2 = ...;
528 * av_dynarray_add(&array, &nb, &to_be_added);
530 * return AVERROR(ENOMEM);
532 * av_dynarray_add(&array, &nb, &to_be_added2);
534 * return AVERROR(ENOMEM);
538 * // &to_be_added == array[0]
539 * // &to_be_added2 == array[1]
544 * The second system stores the value directly in a block of memory. As a
545 * result, the function has to know the size of the type. av_dynarray2_add()
546 * implements this mechanism.
549 * type *array = NULL; //< an array of values
550 * int nb = 0; //< a variable to keep track of the length of the array
552 * type to_be_added = ...;
553 * type to_be_added2 = ...;
555 * type *addr = av_dynarray2_add((void **)&array, &nb, sizeof(*array), NULL);
557 * return AVERROR(ENOMEM);
558 * memcpy(addr, &to_be_added, sizeof(to_be_added));
560 * // Shortcut of the above.
561 * type *addr = av_dynarray2_add((void **)&array, &nb, sizeof(*array),
562 * (const void *)&to_be_added2);
564 * return AVERROR(ENOMEM);
568 * // to_be_added == array[0]
569 * // to_be_added2 == array[1]
578 * Add the pointer to an element to a dynamic array.
580 * The array to grow is supposed to be an array of pointers to
581 * structures, and the element to add must be a pointer to an already
582 * allocated structure.
584 * The array is reallocated when its size reaches powers of 2.
585 * Therefore, the amortized cost of adding an element is constant.
587 * In case of success, the pointer to the array is updated in order to
588 * point to the new grown array, and the number pointed to by `nb_ptr`
590 * In case of failure, the array is freed, `*tab_ptr` is set to `NULL` and
591 * `*nb_ptr` is set to 0.
593 * @param[in,out] tab_ptr Pointer to the array to grow
594 * @param[in,out] nb_ptr Pointer to the number of elements in the array
595 * @param[in] elem Element to add
596 * @see av_dynarray_add_nofree(), av_dynarray2_add()
598 void av_dynarray_add(void *tab_ptr, int *nb_ptr, void *elem);
601 * Add an element to a dynamic array.
603 * Function has the same functionality as av_dynarray_add(),
604 * but it doesn't free memory on fails. It returns error code
605 * instead and leave current buffer untouched.
607 * @return >=0 on success, negative otherwise
608 * @see av_dynarray_add(), av_dynarray2_add()
610 av_warn_unused_result
611 int av_dynarray_add_nofree(void *tab_ptr, int *nb_ptr, void *elem);
614 * Add an element of size `elem_size` to a dynamic array.
616 * The array is reallocated when its number of elements reaches powers of 2.
617 * Therefore, the amortized cost of adding an element is constant.
619 * In case of success, the pointer to the array is updated in order to
620 * point to the new grown array, and the number pointed to by `nb_ptr`
622 * In case of failure, the array is freed, `*tab_ptr` is set to `NULL` and
623 * `*nb_ptr` is set to 0.
625 * @param[in,out] tab_ptr Pointer to the array to grow
626 * @param[in,out] nb_ptr Pointer to the number of elements in the array
627 * @param[in] elem_size Size in bytes of an element in the array
628 * @param[in] elem_data Pointer to the data of the element to add. If
629 * `NULL`, the space of the newly added element is
630 * allocated but left uninitialized.
632 * @return Pointer to the data of the element to copy in the newly allocated
634 * @see av_dynarray_add(), av_dynarray_add_nofree()
636 void *av_dynarray2_add(void **tab_ptr, int *nb_ptr, size_t elem_size,
637 const uint8_t *elem_data);
644 * @defgroup lavu_mem_misc Miscellaneous Functions
646 * Other functions related to memory allocation.
652 * Multiply two `size_t` values checking for overflow.
654 * @param[in] a,b Operands of multiplication
655 * @param[out] r Pointer to the result of the operation
656 * @return 0 on success, AVERROR(EINVAL) on overflow
658 static inline int av_size_mult(size_t a, size_t b, size_t *r)
661 /* Hack inspired from glibc: don't try the division if nelem and elsize
662 * are both less than sqrt(SIZE_MAX). */
663 if ((a | b) >= ((size_t)1 << (sizeof(size_t) * 4)) && a && t / a != b)
664 return AVERROR(EINVAL);
670 * Set the maximum size that may be allocated in one block.
672 * The value specified with this function is effective for all libavutil's @ref
673 * lavu_mem_funcs "heap management functions."
675 * By default, the max value is defined as `INT_MAX`.
677 * @param max Value to be set as the new maximum size
679 * @warning Exercise extreme caution when using this function. Don't touch
680 * this if you do not understand the full consequence of doing so.
682 void av_max_alloc(size_t max);
689 #endif /* AVUTIL_MEM_H */