1 /* 2 * Copyright (c) 2021-2023 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 #ifndef HKS_MEM_H 17 #define HKS_MEM_H 18 19 #ifdef __cplusplus 20 #include <cstdint> 21 #include <cstdlib> 22 23 #define HKS_NULL_POINTER nullptr 24 #else 25 #include <stdint.h> 26 #include <stdlib.h> 27 28 #define HKS_NULL_POINTER NULL 29 #endif 30 31 #ifdef __cplusplus 32 extern "C" { 33 #endif 34 35 #define MAX_MALLOC_SIZE 0x800000 // 8M 36 37 void *HksMalloc(size_t size); 38 void HksFreeImpl(void *addr); 39 int32_t HksMemCmp(const void *ptr1, const void *ptr2, uint32_t size); 40 41 #define SELF_FREE_PTR(PTR, FREE_FUNC) \ 42 { \ 43 if ((PTR) != HKS_NULL_POINTER) { \ 44 FREE_FUNC(PTR); \ 45 (PTR) = HKS_NULL_POINTER; \ 46 } \ 47 } 48 49 #define HKS_FREE(p) ({SELF_FREE_PTR(p, HksFreeImpl)}) 50 51 #define HKS_FREE_BLOB(blob) do { \ 52 if ((blob).data != HKS_NULL_POINTER) { \ 53 HksFreeImpl((blob).data); \ 54 (blob).data = HKS_NULL_POINTER; \ 55 } \ 56 (blob).size = 0; \ 57 } while (0) 58 59 #define HKS_MEMSET_FREE_PTR(ptr, size) \ 60 { \ 61 if ((ptr) != HKS_NULL_POINTER) { \ 62 (void)memset_s((ptr), (size), 0, (size)); \ 63 HksFreeImpl(ptr); \ 64 (ptr) = HKS_NULL_POINTER; \ 65 } \ 66 } 67 68 #define HKS_MEMSET_FREE_BLOB(blob) do { \ 69 if ((blob).data != HKS_NULL_POINTER) { \ 70 (void)memset_s((blob).data, (blob).size, 0, (blob).size); \ 71 HksFreeImpl((blob).data); \ 72 (blob).data = HKS_NULL_POINTER; \ 73 } \ 74 (blob).size = 0; \ 75 } while (0) 76 77 #ifdef __cplusplus 78 } 79 #endif 80 81 #endif /* HKS_MEM_H */ 82