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 "memory_mock.h"
17 #include "hc_types.h"
18
19 #include <securec.h>
20 #include "exception_controller.h"
21 #include "memory_monitor.h"
22
MockMalloc(uint32_t size,char val,const char * strFile,int nLine)23 void *MockMalloc(uint32_t size, char val, const char *strFile, int nLine)
24 {
25 if (size == 0) {
26 return NULL;
27 }
28 if (IsNeedThrowException()) {
29 AddCallNum();
30 return NULL;
31 } else {
32 AddCallNum();
33 }
34 void* addr = malloc(size);
35 if (addr != NULL) {
36 (void)memset_s(addr, size, val, size);
37 HcMonitorMalloc(addr, size, strFile, nLine);
38 }
39 return addr;
40 }
41
MockFree(void * addr)42 void MockFree(void *addr)
43 {
44 if (addr != NULL) {
45 HcMonitorFree(addr);
46 free(addr);
47 }
48 }
49
MockMallocForJson(size_t size)50 void *MockMallocForJson(size_t size)
51 {
52 return MockMalloc((uint32_t)size, 0, __FILE__, __LINE__);
53 }
54
HcStrlen(const char * str)55 uint32_t HcStrlen(const char *str)
56 {
57 if (str == NULL) {
58 return 0;
59 }
60 const char *p = str;
61 while (*p++ != '\0') {}
62 return p - str - 1;
63 }
64