3 * Copyright (c) 2021 Project CHIP Authors
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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 #include "PrivateHeap.h"
23 #include <support/CodeUtils.h>
24 #include <system/SystemMutex.h>
31 void * gPrivateHeap = nullptr;
33 #if CHIP_SYSTEM_CONFIG_NO_LOCKING
44 chip::System::Mutex gHeapLock;
49 HeapLocked() { gHeapLock.Lock(); }
50 ~HeapLocked() { gHeapLock.Unlock(); }
56 CHIP_ERROR MemoryAllocatorInit(void * buf, size_t bufSize)
58 ReturnErrorCodeIf(buf == nullptr, CHIP_ERROR_INVALID_ARGUMENT);
59 ReturnErrorCodeIf(gPrivateHeap != nullptr, CHIP_ERROR_INCORRECT_STATE);
61 PrivateHeapInit(buf, bufSize);
64 #if CHIP_SYSTEM_CONFIG_NO_LOCKING
67 return chip::System::Mutex::Init(gHeapLock);
71 void MemoryAllocatorShutdown()
73 gPrivateHeap = nullptr;
76 void * MemoryAlloc(size_t size)
80 if (gPrivateHeap == nullptr)
85 return PrivateHeapAlloc(gPrivateHeap, size);
88 void * MemoryCalloc(size_t num, size_t size)
90 size_t total = num * size;
92 // check for multiplication overflow
93 if (size != total / num)
98 void * result = MemoryAlloc(total);
99 if (result != nullptr)
101 memset(result, 0, total);
106 void * MemoryRealloc(void * p, size_t size)
110 if (gPrivateHeap == nullptr)
115 return PrivateHeapRealloc(gPrivateHeap, p, size);
118 void MemoryFree(void * p)
122 if (gPrivateHeap == nullptr)
129 } // namespace Platform