| 1 | //===-- copyprof_per_object_state.cpp ------------------------------------===// |
|---|---|
| 2 | // |
| 3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 | // See https://llvm.org/LICENSE.txt for license information. |
| 5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 6 | // |
| 7 | //===----------------------------------------------------------------------===// |
| 8 | /// |
| 9 | /// This file implements per-object state tracking utilities for CopyProf, |
| 10 | /// managing transitive object sizes and allocation flags. |
| 11 | /// |
| 12 | //===----------------------------------------------------------------------===// |
| 13 | |
| 14 | #include "copyprof_per_object_state.h" |
| 15 | |
| 16 | #include "copyprof_state.h" |
| 17 | #include "sanitizer_common/sanitizer_dense_map.h" |
| 18 | #include "sanitizer_common/sanitizer_mutex.h" |
| 19 | #include "sanitizer_common/sanitizer_placement_new.h" |
| 20 | |
| 21 | namespace __copyprof { |
| 22 | namespace { |
| 23 | |
| 24 | using PerObjMap = DenseMap<const void*, PerObjectState>; |
| 25 | |
| 26 | // Global map for per-object size tracking. |
| 27 | // Protected by mutex for thread-safe access. |
| 28 | StaticSpinMutex g_per_obj_map_mutex; |
| 29 | alignas(PerObjMap) char g_per_obj_map_placeholder[sizeof(PerObjMap)]; |
| 30 | PerObjMap* g_per_obj_map = nullptr; |
| 31 | |
| 32 | } // namespace |
| 33 | |
| 34 | void InitializePerObjectTracking() { |
| 35 | g_per_obj_map_mutex.Init(); |
| 36 | g_per_obj_map = new (g_per_obj_map_placeholder) PerObjMap(); |
| 37 | } |
| 38 | |
| 39 | void InitPerObjectState(const void* this_ptr, uptr static_size) { |
| 40 | SpinMutexLock lock(&g_per_obj_map_mutex); |
| 41 | PerObjectState& state = (*g_per_obj_map)[this_ptr]; |
| 42 | state.SetStaticSize(static_size); |
| 43 | state.did_allocate = false; |
| 44 | } |
| 45 | |
| 46 | void RecordPerObjectAllocation(const void* this_ptr, uptr num_bytes) { |
| 47 | SpinMutexLock lock(&g_per_obj_map_mutex); |
| 48 | PerObjectState& state = (*g_per_obj_map)[this_ptr]; |
| 49 | state.IncreaseTrackedSize(num_bytes); |
| 50 | state.did_allocate = true; |
| 51 | } |
| 52 | |
| 53 | uptr GetPerObjectTrackedSize(const void* this_ptr) { |
| 54 | SpinMutexLock lock(&g_per_obj_map_mutex); |
| 55 | const auto* it = g_per_obj_map->find(Key: this_ptr); |
| 56 | return it ? it->second.GetTrackedSize() : 0; |
| 57 | } |
| 58 | |
| 59 | bool GetPerObjectDidAllocate(const void* this_ptr) { |
| 60 | SpinMutexLock lock(&g_per_obj_map_mutex); |
| 61 | const auto* it = g_per_obj_map->find(Key: this_ptr); |
| 62 | return it ? it->second.did_allocate : false; |
| 63 | } |
| 64 | |
| 65 | void RemovePerObjectState(const void* this_ptr) { |
| 66 | SpinMutexLock lock(&g_per_obj_map_mutex); |
| 67 | g_per_obj_map->erase(Val: this_ptr); |
| 68 | } |
| 69 | |
| 70 | } // namespace __copyprof |
| 71 |