1 /** 2 * Copyright (c) 2021-2024 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 #ifndef PANDA_RUNTIME_MEM_MALLOC_PROXY_ALLOCATOR_H 16 #define PANDA_RUNTIME_MEM_MALLOC_PROXY_ALLOCATOR_H 17 18 #include <functional> 19 #include <map> 20 #include <memory> 21 #include <unordered_map> 22 #include <type_traits> 23 24 #include "libpandabase/mem/mem.h" 25 #include "libpandabase/mem/space.h" 26 #include "libpandabase/os/mutex.h" 27 28 namespace ark::mem { 29 30 using ark::Alignment; 31 class EmptyMemoryConfig; 32 33 /// @brief Class-proxy to the malloc, do some logging. 34 template <typename AllocConfigT> 35 class MallocProxyAllocator { 36 public: 37 NO_COPY_SEMANTIC(MallocProxyAllocator); 38 NO_MOVE_SEMANTIC(MallocProxyAllocator); 39 40 explicit MallocProxyAllocator(MemStatsType *memStats, SpaceType typeAllocation = SpaceType::SPACE_TYPE_INTERNAL) typeAllocation_(typeAllocation)41 : typeAllocation_(typeAllocation), memStats_ {memStats} 42 { 43 } 44 45 ~MallocProxyAllocator(); 46 47 [[nodiscard]] void *Alloc(size_t size, Alignment align = DEFAULT_ALIGNMENT); 48 49 template <class T> AllocArray(size_t size)50 T *AllocArray(size_t size) 51 { 52 return static_cast<T *>(this->Alloc(sizeof(T) * size)); 53 } 54 55 void Free(void *mem); 56 57 private: 58 static constexpr bool DUMMY_ALLOC_CONFIG = std::is_same<AllocConfigT, EmptyMemoryConfig>::value; 59 std::unordered_map<void *, size_t> allocatedMemory_; 60 SpaceType typeAllocation_; 61 MemStatsType *memStats_; 62 os::memory::Mutex lock_; 63 }; 64 65 } // namespace ark::mem 66 67 #endif // PANDA_RUNTIME_MEM_MALLOC_PROXY_ALLOCATOR_H 68