1 /* 2 * Copyright (c) 2021 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 #ifndef FOUNDATION_ACE_FRAMEWORKS_BASE_MEMORY_MEMORY_MONITOR_H 17 #define FOUNDATION_ACE_FRAMEWORKS_BASE_MEMORY_MEMORY_MONITOR_H 18 19 #include <string> 20 21 #include "base/memory/memory_monitor_def.h" 22 #include "base/memory/type_info_base.h" 23 #include "base/utils/macros.h" 24 25 namespace OHOS::Ace { 26 27 void PurgeMallocCache(); 28 29 class ACE_FORCE_EXPORT MemoryMonitor { 30 public: 31 static MemoryMonitor& GetInstance(); 32 33 virtual ~MemoryMonitor() = default; 34 35 virtual void Add(void* ptr) = 0; 36 virtual void Remove(void* ptr) = 0; 37 virtual void Update(void* ptr, size_t size, const std::string& typeName) = 0; 38 virtual void Dump() const = 0; 39 40 template<class T> Update(T * ptr,void * refPtr)41 void Update(T* ptr, void* refPtr) 42 { 43 if (ptr != nullptr && ptr->RefCount() == 0) { 44 Update(refPtr, TypeInfo<T>::Size(ptr), TypeInfo<T>::Name(ptr)); 45 } 46 } 47 IsEnable()48 static bool IsEnable() 49 { 50 return isEnable_; 51 } 52 53 private: 54 template<class T, bool hasTypeInfo = std::is_base_of_v<TypeInfoBase, T>> 55 struct TypeInfo; 56 57 template<class T> 58 struct TypeInfo<T, false> { 59 static const char* Name(T*) 60 { 61 return "Unknown"; 62 } 63 64 static size_t Size(T*) 65 { 66 return sizeof(T); 67 } 68 }; 69 70 template<class T> 71 struct TypeInfo<T, true> { 72 static const char* Name(T* rawPtr) 73 { 74 return TypeInfoHelper::TypeName(rawPtr); 75 } 76 77 static size_t Size(T* rawPtr) 78 { 79 return TypeInfoHelper::TypeSize(rawPtr); 80 } 81 }; 82 static bool isEnable_; 83 }; 84 } // namespace OHOS::Ace 85 86 #endif // FOUNDATION_ACE_FRAMEWORKS_BASE_MEMORY_MEMORY_MONITOR_H 87