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 ECMASCRIPT_HPROF_HEAP_TRACKER_H 17 #define ECMASCRIPT_HPROF_HEAP_TRACKER_H 18 19 #include <atomic> 20 #include <cstdint> 21 #include <thread> 22 23 #include "libpandabase/macros.h" 24 25 namespace panda::ecmascript { 26 class HeapSnapShot; 27 28 class HeapTrackerSample { 29 public: HeapTrackerSample(HeapSnapShot * snapShot,double timeInterval)30 explicit HeapTrackerSample(HeapSnapShot *snapShot, double timeInterval) 31 : timeInterval_(timeInterval), snapShot_(snapShot) 32 { 33 } 34 ~HeapTrackerSample()35 ~HeapTrackerSample() 36 { 37 isInterrupt_ = true; 38 } 39 Start()40 void Start() 41 { 42 isInterrupt_ = false; 43 thread_ = std::thread(&HeapTrackerSample::Run, this); 44 } 45 Stop()46 void Stop() 47 { 48 isInterrupt_ = true; 49 if (thread_.joinable()) { 50 thread_.join(); 51 } 52 } 53 54 void Run(); 55 56 NO_COPY_SEMANTIC(HeapTrackerSample); 57 NO_MOVE_SEMANTIC(HeapTrackerSample); 58 59 private: 60 std::thread thread_; 61 std::atomic_bool isInterrupt_ = true; 62 double timeInterval_ = 0; 63 HeapSnapShot *snapShot_; 64 }; 65 66 class HeapTracker { 67 public: HeapTracker(HeapSnapShot * snapShot,double timeInterval)68 HeapTracker(HeapSnapShot *snapShot, double timeInterval) : snapShot_(snapShot), sample_(snapShot, timeInterval) {} 69 ~HeapTracker() = default; 70 StartTracing()71 void StartTracing() 72 { 73 sample_.Start(); 74 } 75 StopTracing()76 void StopTracing() 77 { 78 sample_.Stop(); 79 } 80 81 void AllocationEvent(uintptr_t address); 82 void MoveEvent(uintptr_t address, uintptr_t forward_address); 83 84 NO_COPY_SEMANTIC(HeapTracker); 85 NO_MOVE_SEMANTIC(HeapTracker); 86 87 private: 88 HeapSnapShot *snapShot_; 89 HeapTrackerSample sample_; 90 }; 91 } // namespace panda::ecmascript 92 #endif // ECMASCRIPT_HPROF_HEAP_TRACKER_H 93