1 /* 2 * Copyright (c) 2016, Alliance for Open Media. All rights reserved 3 * 4 * This source code is subject to the terms of the BSD 2 Clause License and 5 * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License 6 * was not distributed with this source code in the LICENSE file, you can 7 * obtain it at www.aomedia.org/license/software. If the Alliance for Open 8 * Media Patent License 1.0 was not distributed with this source code in the 9 * PATENTS file, you can obtain it at www.aomedia.org/license/patent. 10 */ 11 12 #include "aom_mem.h" 13 #include <stdio.h> 14 #include <stdlib.h> 15 #include <string.h> 16 #include "include/aom_mem_intrnl.h" 17 #include "aom/aom_integer.h" 18 19 #if defined(AOM_MAX_ALLOCABLE_MEMORY) 20 // Returns 0 in case of overflow of nmemb * size. 21 static int check_size_argument_overflow(uint64_t nmemb, uint64_t size) { 22 const uint64_t total_size = nmemb * size; 23 if (nmemb == 0) return 1; 24 if (size > AOM_MAX_ALLOCABLE_MEMORY / nmemb) return 0; 25 if (total_size != (size_t)total_size) return 0; 26 return 1; 27 } 28 #endif 29 30 static size_t GetAlignedMallocSize(size_t size, size_t align) { 31 return size + align - 1 + ADDRESS_STORAGE_SIZE; 32 } 33 34 static size_t *GetMallocAddressLocation(void *const mem) { 35 return ((size_t *)mem) - 1; 36 } 37 38 static void SetActualMallocAddress(void *const mem, 39 const void *const malloc_addr) { 40 size_t *const malloc_addr_location = GetMallocAddressLocation(mem); 41 *malloc_addr_location = (size_t)malloc_addr; 42 } 43 44 static void *GetActualMallocAddress(void *const mem) { 45 const size_t *const malloc_addr_location = GetMallocAddressLocation(mem); 46 return (void *)(*malloc_addr_location); 47 } 48 49 void *aom_memalign(size_t align, size_t size) { 50 void *x = NULL; 51 const size_t aligned_size = GetAlignedMallocSize(size, align); 52 #if defined(AOM_MAX_ALLOCABLE_MEMORY) 53 if (!check_size_argument_overflow(1, aligned_size)) return NULL; 54 #endif 55 void *const addr = malloc(aligned_size); 56 if (addr) { 57 x = align_addr((unsigned char *)addr + ADDRESS_STORAGE_SIZE, align); 58 SetActualMallocAddress(x, addr); 59 } 60 return x; 61 } 62 63 void *aom_malloc(size_t size) { return aom_memalign(DEFAULT_ALIGNMENT, size); } 64 65 void *aom_calloc(size_t num, size_t size) { 66 const size_t total_size = num * size; 67 void *const x = aom_malloc(total_size); 68 if (x) memset(x, 0, total_size); 69 return x; 70 } 71 72 void aom_free(void *memblk) { 73 if (memblk) { 74 void *addr = GetActualMallocAddress(memblk); 75 free(addr); 76 } 77 } 78 79 void *aom_memset16(void *dest, int val, size_t length) { 80 size_t i; 81 uint16_t *dest16 = (uint16_t *)dest; 82 for (i = 0; i < length; i++) *dest16++ = val; 83 return dest; 84 } 85