1 /*
2 * Copyright (c) 2025 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 #include "common_components/log/log.h"
17 #include "common_components/mutator/mutator_manager.h"
18 #include "common_interfaces/profiler/heap_profiler_listener.h"
19
20 namespace common {
GetInstance()21 HeapProfilerListener &HeapProfilerListener::GetInstance()
22 {
23 static HeapProfilerListener instance;
24 return instance;
25 }
26
RegisterMoveEventCb(const std::function<void (uintptr_t,uintptr_t,size_t)> & cb)27 uint32_t HeapProfilerListener::RegisterMoveEventCb(const std::function<void(uintptr_t, uintptr_t, size_t)> &cb)
28 {
29 std::unique_lock<std::shared_mutex> lock(mutex_);
30 moveEventCbs_.emplace(moveEventCbId_, cb);
31 return moveEventCbId_++;
32 }
33
UnRegisterMoveEventCb(uint32_t key)34 void HeapProfilerListener::UnRegisterMoveEventCb(uint32_t key)
35 {
36 std::unique_lock<std::shared_mutex> lock(mutex_);
37 moveEventCbs_.erase(key);
38 }
39
OnMoveEvent(uintptr_t fromObj,uintptr_t toObj,size_t size)40 void HeapProfilerListener::OnMoveEvent(uintptr_t fromObj, uintptr_t toObj, size_t size)
41 {
42 std::shared_lock<std::shared_mutex> lock(mutex_);
43 for (const auto &pair : moveEventCbs_) {
44 if (pair.second) {
45 pair.second(fromObj, toObj, size);
46 }
47 }
48 }
49
RegisterOutOfMemoryEventCb(const std::function<void (void * thread)> & cb)50 void HeapProfilerListener::RegisterOutOfMemoryEventCb(const std::function<void(void *thread)> &cb)
51 {
52 outOfMemoryEventCb_ = cb;
53 }
OnOutOfMemoryEventCb()54 void HeapProfilerListener::OnOutOfMemoryEventCb()
55 {
56 void *thread = nullptr;
57 if (!IsGcThread()) {
58 thread = Mutator::GetMutator()->GetThreadHolder()->GetJSThread();
59 }
60 outOfMemoryEventCb_(thread);
61 }
62 } // namespace common