Fix for x86_64 build fail
[platform/upstream/connectedhomeip.git] / src / lib / support / CHIPMem-Simple.cpp
1 /*
2  *
3  *    Copyright (c) 2021 Project CHIP Authors
4  *
5  *    Licensed under the Apache License, Version 2.0 (the "License");
6  *    you may not use this file except in compliance with the License.
7  *    You may obtain a copy of the License at
8  *
9  *        http://www.apache.org/licenses/LICENSE-2.0
10  *
11  *    Unless required by applicable law or agreed to in writing, software
12  *    distributed under the License is distributed on an "AS IS" BASIS,
13  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *    See the License for the specific language governing permissions and
15  *    limitations under the License.
16  */
17
18 #include "CHIPMem.h"
19 #include "PrivateHeap.h"
20
21 #include <string.h>
22
23 #include <support/CodeUtils.h>
24 #include <system/SystemMutex.h>
25
26 namespace chip {
27 namespace Platform {
28
29 namespace {
30
31 void * gPrivateHeap = nullptr;
32
33 #if CHIP_SYSTEM_CONFIG_NO_LOCKING
34
35 class HeapLocked
36 {
37 public:
38     HeapLocked() {}
39     ~HeapLocked() {}
40 };
41
42 #else
43
44 chip::System::Mutex gHeapLock;
45
46 class HeapLocked
47 {
48 public:
49     HeapLocked() { gHeapLock.Lock(); }
50     ~HeapLocked() { gHeapLock.Unlock(); }
51 };
52 #endif
53
54 } // namespace
55
56 CHIP_ERROR MemoryAllocatorInit(void * buf, size_t bufSize)
57 {
58     ReturnErrorCodeIf(buf == nullptr, CHIP_ERROR_INVALID_ARGUMENT);
59     ReturnErrorCodeIf(gPrivateHeap != nullptr, CHIP_ERROR_INCORRECT_STATE);
60
61     PrivateHeapInit(buf, bufSize);
62     gPrivateHeap = buf;
63
64 #if CHIP_SYSTEM_CONFIG_NO_LOCKING
65     return CHIP_NO_ERROR;
66 #else
67     return chip::System::Mutex::Init(gHeapLock);
68 #endif
69 }
70
71 void MemoryAllocatorShutdown()
72 {
73     gPrivateHeap = nullptr;
74 }
75
76 void * MemoryAlloc(size_t size)
77 {
78     HeapLocked lock;
79
80     if (gPrivateHeap == nullptr)
81     {
82         return nullptr;
83     }
84
85     return PrivateHeapAlloc(gPrivateHeap, size);
86 }
87
88 void * MemoryCalloc(size_t num, size_t size)
89 {
90     size_t total = num * size;
91
92     // check for multiplication overflow
93     if (size != total / num)
94     {
95         return nullptr;
96     }
97
98     void * result = MemoryAlloc(total);
99     if (result != nullptr)
100     {
101         memset(result, 0, total);
102     }
103     return result;
104 }
105
106 void * MemoryRealloc(void * p, size_t size)
107 {
108     HeapLocked lock;
109
110     if (gPrivateHeap == nullptr)
111     {
112         return nullptr;
113     }
114
115     return PrivateHeapRealloc(gPrivateHeap, p, size);
116 }
117
118 void MemoryFree(void * p)
119 {
120     HeapLocked lock;
121
122     if (gPrivateHeap == nullptr)
123     {
124         return;
125     }
126     PrivateHeapFree(p);
127 }
128
129 } // namespace Platform
130 } // namespace chip