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 void *HksMalloc(size_t size); 36 void HksFreeImpl(void *addr); 37 int32_t HksMemCmp(const void *ptr1, const void *ptr2, uint32_t size); 38 39 #define SELF_FREE_PTR(PTR, FREE_FUNC) \ 40 { \ 41 if ((PTR) != HKS_NULL_POINTER) { \ 42 FREE_FUNC(PTR); \ 43 (PTR) = HKS_NULL_POINTER; \ 44 } \ 45 } 46 47 #define HKS_FREE(p) ({SELF_FREE_PTR(p, HksFreeImpl)}) 48 49 #define HKS_FREE_BLOB(blob) do { \ 50 if ((blob).data != HKS_NULL_POINTER) { \ 51 HksFreeImpl((blob).data); \ 52 (blob).data = HKS_NULL_POINTER; \ 53 } \ 54 (blob).size = 0; \ 55 } while (0) 56 57 #define HKS_MEMSET_FREE_PTR(ptr, size) \ 58 { \ 59 if ((ptr) != HKS_NULL_POINTER) { \ 60 (void)memset_s((ptr), (size), 0, (size)); \ 61 HksFreeImpl(ptr); \ 62 (ptr) = HKS_NULL_POINTER; \ 63 } \ 64 } 65 66 #define HKS_MEMSET_FREE_BLOB(blob) do { \ 67 if ((blob).data != HKS_NULL_POINTER) { \ 68 (void)memset_s((blob).data, (blob).size, 0, (blob).size); \ 69 HksFreeImpl((blob).data); \ 70 (blob).data = HKS_NULL_POINTER; \ 71 } \ 72 (blob).size = 0; \ 73 } while (0) 74 75 #ifdef __cplusplus 76 } 77 #endif 78 79 #endif /* HKS_MEM_H */ 80