1 /*
2 * Copyright (c) 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 #include "cf_memory.h"
17 #include "memory_mock.h"
18
19 #include "cf_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
SetMockFlag(bool flag)27 void SetMockFlag(bool flag)
28 {
29 g_isMock = flag;
30 }
31
HcfMalloc(uint32_t size,char val)32 void *HcfMalloc(uint32_t size, char val)
33 {
34 if (g_isMock) {
35 return NULL;
36 }
37 if (g_isRecordMallocNum) {
38 if (g_mallocNum == g_mallocMockIndex) {
39 LOGI("mock malloc return NULL.");
40 return NULL;
41 }
42 g_mallocNum++;
43 }
44 void *addr = malloc(size);
45 if (addr != NULL) {
46 (void)memset_s(addr, size, val, size);
47 }
48 return addr;
49 }
50
CfMalloc(uint32_t size)51 void *CfMalloc(uint32_t size)
52 {
53 return HcfMalloc(size, 0);
54 }
55
CfFree(void * addr)56 void CfFree(void *addr)
57 {
58 if (addr != NULL) {
59 free(addr);
60 }
61 }
62
StartRecordMallocNum(void)63 void StartRecordMallocNum(void)
64 {
65 ResetRecordMallocNum();
66 g_isRecordMallocNum = true;
67 }
68
EndRecordMallocNum(void)69 void EndRecordMallocNum(void)
70 {
71 ResetRecordMallocNum();
72 g_isRecordMallocNum = false;
73 }
74
GetMallocNum(void)75 uint32_t GetMallocNum(void)
76 {
77 return g_mallocNum;
78 }
79
ResetRecordMallocNum(void)80 void ResetRecordMallocNum(void)
81 {
82 g_mallocNum = 0;
83 g_mallocMockIndex = __INT32_MAX__;
84 }
85
SetMockMallocIndex(uint32_t index)86 void SetMockMallocIndex(uint32_t index)
87 {
88 g_mallocMockIndex = index;
89 }