3 * Copyright (c) 2020-2021 Project CHIP Authors
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
21 * This file implements heap memory allocation APIs for CHIP. These functions are platform
22 * specific and might be C Standard Library heap functions re-direction in most of cases.
26 #include <core/CHIPConfig.h>
27 #include <support/CHIPMem.h>
36 #if CHIP_CONFIG_MEMORY_DEBUG_DMALLOC
38 #include <support/SafeInt.h>
39 #endif // CHIP_CONFIG_MEMORY_DEBUG_DMALLOC
41 #if CHIP_CONFIG_MEMORY_MGMT_MALLOC
48 #define VERIFY_INITIALIZED()
49 #define VERIFY_POINTER(p)
53 #define VERIFY_INITIALIZED() VerifyInitialized(__func__)
55 static std::atomic_int memoryInitialized{ 0 };
57 static void VerifyInitialized(const char * func)
59 if (!memoryInitialized)
61 fprintf(stderr, "ABORT: chip::Platform::%s() called before chip::Platform::MemoryInit()\n", func);
66 #define VERIFY_POINTER(p) \
68 if (((p) != nullptr) && (MemoryDebugCheckPointer((p)) == false)) \
70 fprintf(stderr, "ABORT: chip::Platform::%s() found corruption on %p\n", __func__, (p)); \
77 CHIP_ERROR MemoryAllocatorInit(void * buf, size_t bufSize)
80 if (memoryInitialized++ > 0)
82 fprintf(stderr, "ABORT: chip::Platform::MemoryInit() called twice.\n");
89 void MemoryAllocatorShutdown()
92 if (--memoryInitialized < 0)
94 fprintf(stderr, "ABORT: chip::Platform::MemoryShutdown() called twice.\n");
98 #if CHIP_CONFIG_MEMORY_DEBUG_DMALLOC
100 #endif // CHIP_CONFIG_MEMORY_DEBUG_DMALLOC
103 void * MemoryAlloc(size_t size)
105 VERIFY_INITIALIZED();
109 void * MemoryCalloc(size_t num, size_t size)
111 VERIFY_INITIALIZED();
112 return calloc(num, size);
115 void * MemoryRealloc(void * p, size_t size)
117 VERIFY_INITIALIZED();
119 return realloc(p, size);
122 void MemoryFree(void * p)
124 VERIFY_INITIALIZED();
129 bool MemoryInternalCheckPointer(const void * p, size_t min_size)
131 #if CHIP_CONFIG_MEMORY_DEBUG_DMALLOC
132 return CanCastTo<int>(min_size) && (p != nullptr) &&
133 (dmalloc_verify_pnt(__FILE__, __LINE__, __func__, p, 1, static_cast<int>(min_size)) == MALLOC_VERIFY_NOERROR);
134 #else // CHIP_CONFIG_MEMORY_DEBUG_DMALLOC
135 return (p != nullptr);
136 #endif // CHIP_CONFIG_MEMORY_DEBUG_DMALLOC
139 } // namespace Platform
142 #endif // CHIP_CONFIG_MEMORY_MGMT_MALLOC