mem.h (20555B)
1 /* 2 * copyright (c) 2006 Michael Niedermayer <michaelni@gmx.at> 3 * 4 * This file is part of FFmpeg. 5 * 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. 10 * 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. 15 * 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 19 */ 20 21 /** 22 * @file 23 * @ingroup lavu_mem 24 * Memory handling functions 25 */ 26 27 #ifndef AVUTIL_MEM_H 28 #define AVUTIL_MEM_H 29 30 #include <stddef.h> 31 #include <stdint.h> 32 33 #include "attributes.h" 34 35 /** 36 * @addtogroup lavu_mem 37 * Utilities for manipulating memory. 38 * 39 * FFmpeg has several applications of memory that are not required of a typical 40 * program. For example, the computing-heavy components like video decoding and 41 * encoding can be sped up significantly through the use of aligned memory. 42 * 43 * However, for each of FFmpeg's applications of memory, there might not be a 44 * recognized or standardized API for that specific use. Memory alignment, for 45 * instance, varies wildly depending on operating systems, architectures, and 46 * compilers. Hence, this component of @ref libavutil is created to make 47 * dealing with memory consistently possible on all platforms. 48 * 49 * @{ 50 */ 51 52 /** 53 * @defgroup lavu_mem_attrs Function Attributes 54 * Function attributes applicable to memory handling functions. 55 * 56 * These function attributes can help compilers emit more useful warnings, or 57 * generate better code. 58 * @{ 59 */ 60 61 /** 62 * @def av_malloc_attrib 63 * Function attribute denoting a malloc-like function. 64 * 65 * @see <a 66 * href="https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#index-g_t_0040code_007bmalloc_007d-function-attribute-3251">Function 67 * attribute `malloc` in GCC's documentation</a> 68 */ 69 70 #if AV_GCC_VERSION_AT_LEAST(3, 1) 71 # define av_malloc_attrib __attribute__((__malloc__)) 72 #else 73 # define av_malloc_attrib 74 #endif 75 76 /** 77 * @def av_alloc_size(...) 78 * Function attribute used on a function that allocates memory, whose size is 79 * given by the specified parameter(s). 80 * 81 * @code{.c} 82 * void *av_malloc(size_t size) av_alloc_size(1); 83 * void *av_calloc(size_t nmemb, size_t size) av_alloc_size(1, 2); 84 * @endcode 85 * 86 * @param ... One or two parameter indexes, separated by a comma 87 * 88 * @see <a 89 * href="https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#index-g_t_0040code_007balloc_005fsize_007d-function-attribute-3220">Function 90 * attribute `alloc_size` in GCC's documentation</a> 91 */ 92 93 #if AV_GCC_VERSION_AT_LEAST(4, 3) 94 # define av_alloc_size(...) __attribute__((alloc_size(__VA_ARGS__))) 95 #else 96 # define av_alloc_size(...) 97 #endif 98 99 /** 100 * @} 101 */ 102 103 /** 104 * @defgroup lavu_mem_funcs Heap Management 105 * Functions responsible for allocating, freeing, and copying memory. 106 * 107 * All memory allocation functions have a built-in upper limit of `INT_MAX` 108 * bytes. This may be changed with av_max_alloc(), although exercise extreme 109 * caution when doing so. 110 * 111 * @{ 112 */ 113 114 /** 115 * Allocate a memory block with alignment suitable for all memory accesses 116 * (including vectors if available on the CPU). 117 * 118 * @param size Size in bytes for the memory block to be allocated 119 * @return Pointer to the allocated block, or `NULL` if the block cannot 120 * be allocated 121 * @see av_mallocz() 122 */ 123 void* av_malloc(size_t size) av_malloc_attrib av_alloc_size(1); 124 125 /** 126 * Allocate a memory block with alignment suitable for all memory accesses 127 * (including vectors if available on the CPU) and zero all the bytes of the 128 * block. 129 * 130 * @param size Size in bytes for the memory block to be allocated 131 * @return Pointer to the allocated block, or `NULL` if it cannot be allocated 132 * @see av_malloc() 133 */ 134 void* av_mallocz(size_t size) av_malloc_attrib av_alloc_size(1); 135 136 /** 137 * Allocate a memory block for an array with av_malloc(). 138 * 139 * The allocated memory will have size `size * nmemb` bytes. 140 * 141 * @param nmemb Number of element 142 * @param size Size of a single element 143 * @return Pointer to the allocated block, or `NULL` if the block cannot 144 * be allocated 145 * @see av_malloc() 146 */ 147 av_alloc_size(1, 2) void* av_malloc_array(size_t nmemb, size_t size); 148 149 /** 150 * Allocate a memory block for an array with av_mallocz(). 151 * 152 * The allocated memory will have size `size * nmemb` bytes. 153 * 154 * @param nmemb Number of elements 155 * @param size Size of the single element 156 * @return Pointer to the allocated block, or `NULL` if the block cannot 157 * be allocated 158 * 159 * @see av_mallocz() 160 * @see av_malloc_array() 161 */ 162 void* av_calloc(size_t nmemb, size_t size) av_malloc_attrib av_alloc_size(1, 2); 163 164 /** 165 * Allocate, reallocate, or free a block of memory. 166 * 167 * If `ptr` is `NULL` and `size` > 0, allocate a new block. Otherwise, expand or 168 * shrink that block of memory according to `size`. 169 * 170 * @param ptr Pointer to a memory block already allocated with 171 * av_realloc() or `NULL` 172 * @param size Size in bytes of the memory block to be allocated or 173 * reallocated 174 * 175 * @return Pointer to a newly-reallocated block or `NULL` if the block 176 * cannot be reallocated 177 * 178 * @warning Unlike av_malloc(), the returned pointer is not guaranteed to be 179 * correctly aligned. The returned pointer must be freed after even 180 * if size is zero. 181 * @see av_fast_realloc() 182 * @see av_reallocp() 183 */ 184 void* av_realloc(void* ptr, size_t size) av_alloc_size(2); 185 186 /** 187 * Allocate, reallocate, or free a block of memory through a pointer to a 188 * pointer. 189 * 190 * If `*ptr` is `NULL` and `size` > 0, allocate a new block. If `size` is 191 * zero, free the memory block pointed to by `*ptr`. Otherwise, expand or 192 * shrink that block of memory according to `size`. 193 * 194 * @param[in,out] ptr Pointer to a pointer to a memory block already allocated 195 * with av_realloc(), or a pointer to `NULL`. The pointer 196 * is updated on success, or freed on failure. 197 * @param[in] size Size in bytes for the memory block to be allocated or 198 * reallocated 199 * 200 * @return Zero on success, an AVERROR error code on failure 201 * 202 * @warning Unlike av_malloc(), the allocated memory is not guaranteed to be 203 * correctly aligned. 204 */ 205 av_warn_unused_result int av_reallocp(void* ptr, size_t size); 206 207 /** 208 * Allocate, reallocate, or free a block of memory. 209 * 210 * This function does the same thing as av_realloc(), except: 211 * - It takes two size arguments and allocates `nelem * elsize` bytes, 212 * after checking the result of the multiplication for integer overflow. 213 * - It frees the input block in case of failure, thus avoiding the memory 214 * leak with the classic 215 * @code{.c} 216 * buf = realloc(buf); 217 * if (!buf) 218 * return -1; 219 * @endcode 220 * pattern. 221 */ 222 void* av_realloc_f(void* ptr, size_t nelem, size_t elsize); 223 224 /** 225 * Allocate, reallocate, or free an array. 226 * 227 * If `ptr` is `NULL` and `nmemb` > 0, allocate a new block. 228 * 229 * @param ptr Pointer to a memory block already allocated with 230 * av_realloc() or `NULL` 231 * @param nmemb Number of elements in the array 232 * @param size Size of the single element of the array 233 * 234 * @return Pointer to a newly-reallocated block or NULL if the block 235 * cannot be reallocated 236 * 237 * @warning Unlike av_malloc(), the allocated memory is not guaranteed to be 238 * correctly aligned. The returned pointer must be freed after even if 239 * nmemb is zero. 240 * @see av_reallocp_array() 241 */ 242 av_alloc_size(2, 3) void* av_realloc_array(void* ptr, size_t nmemb, 243 size_t size); 244 245 /** 246 * Allocate, reallocate an array through a pointer to a pointer. 247 * 248 * If `*ptr` is `NULL` and `nmemb` > 0, allocate a new block. 249 * 250 * @param[in,out] ptr Pointer to a pointer to a memory block already 251 * allocated with av_realloc(), or a pointer to `NULL`. 252 * The pointer is updated on success, or freed on failure. 253 * @param[in] nmemb Number of elements 254 * @param[in] size Size of the single element 255 * 256 * @return Zero on success, an AVERROR error code on failure 257 * 258 * @warning Unlike av_malloc(), the allocated memory is not guaranteed to be 259 * correctly aligned. *ptr must be freed after even if nmemb is zero. 260 */ 261 int av_reallocp_array(void* ptr, size_t nmemb, size_t size); 262 263 /** 264 * Reallocate the given buffer if it is not large enough, otherwise do nothing. 265 * 266 * If the given buffer is `NULL`, then a new uninitialized buffer is allocated. 267 * 268 * If the given buffer is not large enough, and reallocation fails, `NULL` is 269 * returned and `*size` is set to 0, but the original buffer is not changed or 270 * freed. 271 * 272 * A typical use pattern follows: 273 * 274 * @code{.c} 275 * uint8_t *buf = ...; 276 * uint8_t *new_buf = av_fast_realloc(buf, ¤t_size, size_needed); 277 * if (!new_buf) { 278 * // Allocation failed; clean up original buffer 279 * av_freep(&buf); 280 * return AVERROR(ENOMEM); 281 * } 282 * @endcode 283 * 284 * @param[in,out] ptr Already allocated buffer, or `NULL` 285 * @param[in,out] size Pointer to the size of buffer `ptr`. `*size` is 286 * updated to the new allocated size, in particular 0 287 * in case of failure. 288 * @param[in] min_size Desired minimal size of buffer `ptr` 289 * @return `ptr` if the buffer is large enough, a pointer to newly reallocated 290 * buffer if the buffer was not large enough, or `NULL` in case of 291 * error 292 * @see av_realloc() 293 * @see av_fast_malloc() 294 */ 295 void* av_fast_realloc(void* ptr, unsigned int* size, size_t min_size); 296 297 /** 298 * Allocate a buffer, reusing the given one if large enough. 299 * 300 * Contrary to av_fast_realloc(), the current buffer contents might not be 301 * preserved and on error the old buffer is freed, thus no special handling to 302 * avoid memleaks is necessary. 303 * 304 * `*ptr` is allowed to be `NULL`, in which case allocation always happens if 305 * `size_needed` is greater than 0. 306 * 307 * @code{.c} 308 * uint8_t *buf = ...; 309 * av_fast_malloc(&buf, ¤t_size, size_needed); 310 * if (!buf) { 311 * // Allocation failed; buf already freed 312 * return AVERROR(ENOMEM); 313 * } 314 * @endcode 315 * 316 * @param[in,out] ptr Pointer to pointer to an already allocated buffer. 317 * `*ptr` will be overwritten with pointer to new 318 * buffer on success or `NULL` on failure 319 * @param[in,out] size Pointer to the size of buffer `*ptr`. `*size` is 320 * updated to the new allocated size, in particular 0 321 * in case of failure. 322 * @param[in] min_size Desired minimal size of buffer `*ptr` 323 * @see av_realloc() 324 * @see av_fast_mallocz() 325 */ 326 void av_fast_malloc(void* ptr, unsigned int* size, size_t min_size); 327 328 /** 329 * Allocate and clear a buffer, reusing the given one if large enough. 330 * 331 * Like av_fast_malloc(), but all newly allocated space is initially cleared. 332 * Reused buffer is not cleared. 333 * 334 * `*ptr` is allowed to be `NULL`, in which case allocation always happens if 335 * `size_needed` is greater than 0. 336 * 337 * @param[in,out] ptr Pointer to pointer to an already allocated buffer. 338 * `*ptr` will be overwritten with pointer to new 339 * buffer on success or `NULL` on failure 340 * @param[in,out] size Pointer to the size of buffer `*ptr`. `*size` is 341 * updated to the new allocated size, in particular 0 342 * in case of failure. 343 * @param[in] min_size Desired minimal size of buffer `*ptr` 344 * @see av_fast_malloc() 345 */ 346 void av_fast_mallocz(void* ptr, unsigned int* size, size_t min_size); 347 348 /** 349 * Free a memory block which has been allocated with a function of av_malloc() 350 * or av_realloc() family. 351 * 352 * @param ptr Pointer to the memory block which should be freed. 353 * 354 * @note `ptr = NULL` is explicitly allowed. 355 * @note It is recommended that you use av_freep() instead, to prevent leaving 356 * behind dangling pointers. 357 * @see av_freep() 358 */ 359 void av_free(void* ptr); 360 361 /** 362 * Free a memory block which has been allocated with a function of av_malloc() 363 * or av_realloc() family, and set the pointer pointing to it to `NULL`. 364 * 365 * @code{.c} 366 * uint8_t *buf = av_malloc(16); 367 * av_free(buf); 368 * // buf now contains a dangling pointer to freed memory, and accidental 369 * // dereference of buf will result in a use-after-free, which may be a 370 * // security risk. 371 * 372 * uint8_t *buf = av_malloc(16); 373 * av_freep(&buf); 374 * // buf is now NULL, and accidental dereference will only result in a 375 * // NULL-pointer dereference. 376 * @endcode 377 * 378 * @param ptr Pointer to the pointer to the memory block which should be freed 379 * @note `*ptr = NULL` is safe and leads to no action. 380 * @see av_free() 381 */ 382 void av_freep(void* ptr); 383 384 /** 385 * Duplicate a string. 386 * 387 * @param s String to be duplicated 388 * @return Pointer to a newly-allocated string containing a 389 * copy of `s` or `NULL` if the string cannot be allocated 390 * @see av_strndup() 391 */ 392 char* av_strdup(const char* s) av_malloc_attrib; 393 394 /** 395 * Duplicate a substring of a string. 396 * 397 * @param s String to be duplicated 398 * @param len Maximum length of the resulting string (not counting the 399 * terminating byte) 400 * @return Pointer to a newly-allocated string containing a 401 * substring of `s` or `NULL` if the string cannot be allocated 402 */ 403 char* av_strndup(const char* s, size_t len) av_malloc_attrib; 404 405 /** 406 * Duplicate a buffer with av_malloc(). 407 * 408 * @param p Buffer to be duplicated 409 * @param size Size in bytes of the buffer copied 410 * @return Pointer to a newly allocated buffer containing a 411 * copy of `p` or `NULL` if the buffer cannot be allocated 412 */ 413 void* av_memdup(const void* p, size_t size); 414 415 /** 416 * Overlapping memcpy() implementation. 417 * 418 * @param dst Destination buffer 419 * @param back Number of bytes back to start copying (i.e. the initial size of 420 * the overlapping window); must be > 0 421 * @param cnt Number of bytes to copy; must be >= 0 422 * 423 * @note `cnt > back` is valid, this will copy the bytes we just copied, 424 * thus creating a repeating pattern with a period length of `back`. 425 */ 426 void av_memcpy_backptr(uint8_t* dst, int back, int cnt); 427 428 /** 429 * @} 430 */ 431 432 /** 433 * @defgroup lavu_mem_dynarray Dynamic Array 434 * 435 * Utilities to make an array grow when needed. 436 * 437 * Sometimes, the programmer would want to have an array that can grow when 438 * needed. The libavutil dynamic array utilities fill that need. 439 * 440 * libavutil supports two systems of appending elements onto a dynamically 441 * allocated array, the first one storing the pointer to the value in the 442 * array, and the second storing the value directly. In both systems, the 443 * caller is responsible for maintaining a variable containing the length of 444 * the array, as well as freeing of the array after use. 445 * 446 * The first system stores pointers to values in a block of dynamically 447 * allocated memory. Since only pointers are stored, the function does not need 448 * to know the size of the type. Both av_dynarray_add() and 449 * av_dynarray_add_nofree() implement this system. 450 * 451 * @code 452 * type **array = NULL; //< an array of pointers to values 453 * int nb = 0; //< a variable to keep track of the length of the array 454 * 455 * type to_be_added = ...; 456 * type to_be_added2 = ...; 457 * 458 * av_dynarray_add(&array, &nb, &to_be_added); 459 * if (nb == 0) 460 * return AVERROR(ENOMEM); 461 * 462 * av_dynarray_add(&array, &nb, &to_be_added2); 463 * if (nb == 0) 464 * return AVERROR(ENOMEM); 465 * 466 * // Now: 467 * // nb == 2 468 * // &to_be_added == array[0] 469 * // &to_be_added2 == array[1] 470 * 471 * av_freep(&array); 472 * @endcode 473 * 474 * The second system stores the value directly in a block of memory. As a 475 * result, the function has to know the size of the type. av_dynarray2_add() 476 * implements this mechanism. 477 * 478 * @code 479 * type *array = NULL; //< an array of values 480 * int nb = 0; //< a variable to keep track of the length of the array 481 * 482 * type to_be_added = ...; 483 * type to_be_added2 = ...; 484 * 485 * type *addr = av_dynarray2_add((void **)&array, &nb, sizeof(*array), NULL); 486 * if (!addr) 487 * return AVERROR(ENOMEM); 488 * memcpy(addr, &to_be_added, sizeof(to_be_added)); 489 * 490 * // Shortcut of the above. 491 * type *addr = av_dynarray2_add((void **)&array, &nb, sizeof(*array), 492 * (const void *)&to_be_added2); 493 * if (!addr) 494 * return AVERROR(ENOMEM); 495 * 496 * // Now: 497 * // nb == 2 498 * // to_be_added == array[0] 499 * // to_be_added2 == array[1] 500 * 501 * av_freep(&array); 502 * @endcode 503 * 504 * @{ 505 */ 506 507 /** 508 * Add the pointer to an element to a dynamic array. 509 * 510 * The array to grow is supposed to be an array of pointers to 511 * structures, and the element to add must be a pointer to an already 512 * allocated structure. 513 * 514 * The array is reallocated when its size reaches powers of 2. 515 * Therefore, the amortized cost of adding an element is constant. 516 * 517 * In case of success, the pointer to the array is updated in order to 518 * point to the new grown array, and the number pointed to by `nb_ptr` 519 * is incremented. 520 * In case of failure, the array is freed, `*tab_ptr` is set to `NULL` and 521 * `*nb_ptr` is set to 0. 522 * 523 * @param[in,out] tab_ptr Pointer to the array to grow 524 * @param[in,out] nb_ptr Pointer to the number of elements in the array 525 * @param[in] elem Element to add 526 * @see av_dynarray_add_nofree(), av_dynarray2_add() 527 */ 528 void av_dynarray_add(void* tab_ptr, int* nb_ptr, void* elem); 529 530 /** 531 * Add an element to a dynamic array. 532 * 533 * Function has the same functionality as av_dynarray_add(), 534 * but it doesn't free memory on fails. It returns error code 535 * instead and leave current buffer untouched. 536 * 537 * @return >=0 on success, negative otherwise 538 * @see av_dynarray_add(), av_dynarray2_add() 539 */ 540 av_warn_unused_result int av_dynarray_add_nofree(void* tab_ptr, int* nb_ptr, 541 void* elem); 542 543 /** 544 * Add an element of size `elem_size` to a dynamic array. 545 * 546 * The array is reallocated when its number of elements reaches powers of 2. 547 * Therefore, the amortized cost of adding an element is constant. 548 * 549 * In case of success, the pointer to the array is updated in order to 550 * point to the new grown array, and the number pointed to by `nb_ptr` 551 * is incremented. 552 * In case of failure, the array is freed, `*tab_ptr` is set to `NULL` and 553 * `*nb_ptr` is set to 0. 554 * 555 * @param[in,out] tab_ptr Pointer to the array to grow 556 * @param[in,out] nb_ptr Pointer to the number of elements in the array 557 * @param[in] elem_size Size in bytes of an element in the array 558 * @param[in] elem_data Pointer to the data of the element to add. If 559 * `NULL`, the space of the newly added element is 560 * allocated but left uninitialized. 561 * 562 * @return Pointer to the data of the element to copy in the newly allocated 563 * space 564 * @see av_dynarray_add(), av_dynarray_add_nofree() 565 */ 566 void* av_dynarray2_add(void** tab_ptr, int* nb_ptr, size_t elem_size, 567 const uint8_t* elem_data); 568 569 /** 570 * @} 571 */ 572 573 /** 574 * @defgroup lavu_mem_misc Miscellaneous Functions 575 * 576 * Other functions related to memory allocation. 577 * 578 * @{ 579 */ 580 581 /** 582 * Multiply two `size_t` values checking for overflow. 583 * 584 * @param[in] a Operand of multiplication 585 * @param[in] b Operand of multiplication 586 * @param[out] r Pointer to the result of the operation 587 * @return 0 on success, AVERROR(EINVAL) on overflow 588 */ 589 int av_size_mult(size_t a, size_t b, size_t* r); 590 591 /** 592 * Set the maximum size that may be allocated in one block. 593 * 594 * The value specified with this function is effective for all libavutil's @ref 595 * lavu_mem_funcs "heap management functions." 596 * 597 * By default, the max value is defined as `INT_MAX`. 598 * 599 * @param max Value to be set as the new maximum size 600 * 601 * @warning Exercise extreme caution when using this function. Don't touch 602 * this if you do not understand the full consequence of doing so. 603 */ 604 void av_max_alloc(size_t max); 605 606 /** 607 * @} 608 * @} 609 */ 610 611 #endif /* AVUTIL_MEM_H */