1 // Copyright 2020 The Android Open Source Project 2 // 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 #pragma once 16 17 #include "aemu/base/Compiler.h" 18 19 #include <atomic> 20 #include <memory> 21 #include <string> 22 23 /*Example usage: 24 #include "GLcommon/GLESmacros.h" 25 // inside function where you want to trace 26 MEM_TRACE("<Group name>") 27 28 Implementation: 29 The tracker registers hooks to tcmalloc allocator for 30 functions explicitly declared as being tracked. Now, we tracker every APIs in 31 emugl translator library as "EMUGL". When the hooks are 32 invoked, the callback function gets the backtraces as a list of program 33 counters. Then, it walks up the stack and checks if any registerd 34 function is used in this malloc/free operation. Once hit, it will record 35 stats for total allocation and live memory for each individual function. 36 37 */ 38 namespace android { 39 namespace base { 40 41 class MemoryTracker { 42 DISALLOW_COPY_ASSIGN_AND_MOVE(MemoryTracker); 43 44 public: 45 struct MallocStats { 46 std::atomic<int64_t> mAllocated{0}; 47 std::atomic<int64_t> mLive{0}; 48 std::atomic<int64_t> mPeak{0}; 49 }; 50 51 static MemoryTracker* get(); 52 MemoryTracker(); 53 bool addToGroup(const std::string& group, const std::string& func); 54 std::string printUsage(int verbosity = 0); 55 void start(); 56 void stop(); 57 bool isEnabled(); 58 std::unique_ptr<MemoryTracker::MallocStats> getUsage( 59 const std::string& group); 60 61 private: 62 class Impl; 63 std::unique_ptr<Impl> mImpl; 64 }; 65 66 } // namespace base 67 } // namespace android 68