1 /*
2  * Copyright (C) 2022 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 #include "memory.h"
17 #include "memory_mock.h"
18 
19 #include "log.h"
20 #include "securec.h"
21 
22 static bool g_isMock = false;
23 static uint32_t g_mallocMockIndex = __INT32_MAX__;
24 static uint32_t g_mallocNum = 0;
25 static bool g_isRecordMallocNum = false;
26 
HcfMalloc(uint32_t size,char val)27 void *HcfMalloc(uint32_t size, char val)
28 {
29     if (g_isMock) {
30         return NULL;
31     }
32     if (g_isRecordMallocNum) {
33         if (g_mallocNum == g_mallocMockIndex) {
34             LOGD("mock malloc return NULL.");
35             return NULL;
36         }
37         g_mallocNum++;
38     }
39     void *addr = malloc(size);
40     if (addr != NULL) {
41         (void)memset_s(addr, size, val, size);
42     }
43     return addr;
44 }
45 
HcfFree(void * addr)46 void HcfFree(void *addr)
47 {
48     if (addr != NULL) {
49         free(addr);
50     }
51 }
52 
StartRecordMallocNum(void)53 void StartRecordMallocNum(void)
54 {
55     ResetRecordMallocNum();
56     g_isRecordMallocNum = true;
57 }
58 
EndRecordMallocNum(void)59 void EndRecordMallocNum(void)
60 {
61     ResetRecordMallocNum();
62     g_isRecordMallocNum = false;
63 }
64 
GetMallocNum(void)65 uint32_t GetMallocNum(void)
66 {
67     return g_mallocNum;
68 }
69 
ResetRecordMallocNum(void)70 void ResetRecordMallocNum(void)
71 {
72     g_mallocNum = 0;
73     g_mallocMockIndex = __INT32_MAX__;
74 }
75 
SetMockMallocIndex(uint32_t index)76 void SetMockMallocIndex(uint32_t index)
77 {
78     g_mallocMockIndex = index;
79 }