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