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
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
HcfFree(void * addr)51 void HcfFree(void *addr)
52 {
53 if (addr != NULL) {
54 free(addr);
55 }
56 }
57
StartRecordMallocNum(void)58 void StartRecordMallocNum(void)
59 {
60 ResetRecordMallocNum();
61 g_isRecordMallocNum = true;
62 }
63
EndRecordMallocNum(void)64 void EndRecordMallocNum(void)
65 {
66 ResetRecordMallocNum();
67 g_isRecordMallocNum = false;
68 }
69
GetMallocNum(void)70 uint32_t GetMallocNum(void)
71 {
72 return g_mallocNum;
73 }
74
ResetRecordMallocNum(void)75 void ResetRecordMallocNum(void)
76 {
77 g_mallocNum = 0;
78 g_mallocMockIndex = __INT32_MAX__;
79 }
80
SetMockMallocIndex(uint32_t index)81 void SetMockMallocIndex(uint32_t index)
82 {
83 g_mallocMockIndex = index;
84 }