OLD | NEW |
(Empty) | |
| 1 // Copyright 2015 The Chromium Authors. All rights reserved. |
| 2 // Use of this source code is governed by a BSD-style license that can be |
| 3 // found in the LICENSE file. |
| 4 |
| 5 #include "components/metrics/leak_detector/leak_detector.h" |
| 6 |
| 7 #include <link.h> |
| 8 #include <stdint.h> |
| 9 #include <unistd.h> |
| 10 |
| 11 #include <new> |
| 12 |
| 13 #include "base/logging.h" |
| 14 #include "components/metrics/leak_detector/leak_detector_impl.h" |
| 15 #include <gperftools/custom_allocator.h> |
| 16 #include <gperftools/malloc_extension.h> |
| 17 #include <gperftools/malloc_hook.h> |
| 18 #include <gperftools/spin_lock_wrapper.h> |
| 19 |
| 20 namespace leak_detector { |
| 21 |
| 22 namespace { |
| 23 |
| 24 // We strip out different number of stack frames in debug mode |
| 25 // because less inlining happens in that case |
| 26 #ifdef NDEBUG |
| 27 static const int kStripFrames = 2; |
| 28 #else |
| 29 static const int kStripFrames = 3; |
| 30 #endif |
| 31 |
| 32 // For storing the address range of the Chrome binary in memory. |
| 33 struct MappingInfo { |
| 34 uintptr_t addr; |
| 35 size_t size; |
| 36 } chrome_mapping; |
| 37 |
| 38 // TODO(sque): This is a temporary solution for leak detector params. Eventually |
| 39 // params should be passed in from elsewhere in Chromium, and this file should |
| 40 // be deleted. |
| 41 |
| 42 bool EnvToBool(const char* envname, const bool default_value) { |
| 43 return !getenv(envname) |
| 44 ? default_value |
| 45 : memchr("tTyY1\0", getenv(envname)[0], 6) != NULL; |
| 46 } |
| 47 |
| 48 int EnvToInt(const char* envname, const int default_value) { |
| 49 return !getenv(envname) |
| 50 ? default_value |
| 51 : strtol(getenv(envname), NULL, 10); |
| 52 } |
| 53 |
| 54 // Used for sampling allocs and frees. Randomly samples |g_sampling_factor|/256 |
| 55 // of the pointers being allocated and freed. |
| 56 int g_sampling_factor = EnvToInt("LEAK_DETECTOR_SAMPLING_FACTOR", 1); |
| 57 |
| 58 // The number of call stack levels to unwind when profiling allocations by call |
| 59 // stack. |
| 60 int g_stack_depth = EnvToInt("LEAK_DETECTOR_STACK_DEPTH", 4); |
| 61 |
| 62 // Dump allocation stats and check for memory leaks after this many bytes have |
| 63 // been allocated since the last dump/check. Does not get affected by sampling. |
| 64 uint64_t g_dump_interval_bytes = |
| 65 EnvToInt("LEAK_DETECTOR_DUMP_INTERVAL_KB", 32768) * 1024; |
| 66 |
| 67 // Enable verbose logging. Dump all leak analysis data, not just analysis |
| 68 // summaries and suspected leak reports. |
| 69 bool g_dump_leak_analysis = EnvToBool("LEAK_DETECTOR_VERBOSE", false); |
| 70 |
| 71 // The number of times an allocation size must be suspected as a leak before it |
| 72 // gets reported. |
| 73 int g_size_suspicion_threshold = |
| 74 EnvToInt("LEAK_DETECTOR_SIZE_SUSPICION_THRESHOLD", 4); |
| 75 |
| 76 // The number of times a call stack for a particular allocation size must be |
| 77 // suspected as a leak before it gets reported. |
| 78 int g_call_stack_suspicion_threshold = |
| 79 EnvToInt("LEAK_DETECTOR_CALL_STACK_SUSPICION_THRESHOLD", 4); |
| 80 |
| 81 // Use a simple spinlock for locking. Don't use a mutex, which can call malloc |
| 82 // and cause infinite recursion. |
| 83 SpinLockWrapper* g_heap_lock = nullptr; |
| 84 |
| 85 // Points to the active instance of the leak detector. |
| 86 // Modify this only when locked. |
| 87 LeakDetectorImpl* g_leak_detector = nullptr; |
| 88 |
| 89 // Keep track of the total number of bytes allocated. |
| 90 // Modify this only when locked. |
| 91 uint64_t g_total_alloc_size = 0; |
| 92 |
| 93 // Keep track of the total alloc size when the last dump occurred. |
| 94 // Modify this only when locked. |
| 95 uint64_t g_last_alloc_dump_size = 0; |
| 96 |
| 97 // Dump allocation stats and check for leaks after |g_dump_interval_bytes| bytes |
| 98 // have been allocated since the last time that was done. Should be called with |
| 99 // a lock since it modifies the global variable |g_last_alloc_dump_size|. |
| 100 inline void MaybeDumpStatsAndCheckForLeaks() { |
| 101 if (g_total_alloc_size > g_last_alloc_dump_size + g_dump_interval_bytes) { |
| 102 g_leak_detector->DumpStats(); |
| 103 g_last_alloc_dump_size = g_total_alloc_size; |
| 104 g_leak_detector->TestForLeaks(); |
| 105 } |
| 106 } |
| 107 |
| 108 // Convert a pointer to a hash value. Returns only the upper eight bits. |
| 109 inline uint64_t PointerToHash(const void* ptr) { |
| 110 // The input data is the pointer address, not the location in memory pointed |
| 111 // to by the pointer. |
| 112 const uint64_t kMultiplier = 0x9ddfea08eb382d69ULL; |
| 113 uint64_t value = reinterpret_cast<uint64_t>(ptr) * kMultiplier; |
| 114 return value >> 56; |
| 115 } |
| 116 |
| 117 // Uses PointerToHash() to pseudorandomly sample |ptr|. |
| 118 inline bool ShouldSample(const void* ptr) { |
| 119 return PointerToHash(ptr) < static_cast<uint64_t>(g_sampling_factor); |
| 120 } |
| 121 |
| 122 // Allocation/deallocation hooks for MallocHook. |
| 123 void NewHook(const void* ptr, size_t size) { |
| 124 { |
| 125 ScopedSpinLockHolder lock(g_heap_lock); |
| 126 g_total_alloc_size += size; |
| 127 } |
| 128 |
| 129 if (!ShouldSample(ptr) || !ptr || !g_leak_detector) |
| 130 return; |
| 131 |
| 132 // Take the stack trace outside the critical section. |
| 133 // |g_leak_detector->ShouldGetStackTraceForSize()| is const; there is no need |
| 134 // for a lock. |
| 135 void* stack[g_stack_depth]; |
| 136 int depth = 0; |
| 137 if (g_leak_detector->ShouldGetStackTraceForSize(size)) { |
| 138 depth = MallocHook::GetCallerStackTrace( |
| 139 stack, g_stack_depth, kStripFrames + 1); |
| 140 } |
| 141 |
| 142 ScopedSpinLockHolder lock(g_heap_lock); |
| 143 g_leak_detector->RecordAlloc(ptr, size, depth, stack); |
| 144 MaybeDumpStatsAndCheckForLeaks(); |
| 145 } |
| 146 |
| 147 void DeleteHook(const void* ptr) { |
| 148 if (!ShouldSample(ptr) || !ptr || !g_leak_detector) |
| 149 return; |
| 150 |
| 151 ScopedSpinLockHolder lock(g_heap_lock); |
| 152 g_leak_detector->RecordFree(ptr); |
| 153 } |
| 154 |
| 155 // Callback for dl_iterate_phdr() to find the Chrome binary mapping. |
| 156 int IterateLoadedObjects(struct dl_phdr_info *shared_object, |
| 157 size_t /* size */, |
| 158 void *data) { |
| 159 if (g_dump_leak_analysis) { |
| 160 LOG(ERROR) << "name=" << shared_object->dlpi_name << ", " |
| 161 << "addr=" << std::hex << shared_object->dlpi_phnum; |
| 162 } |
| 163 for (int i = 0; i < shared_object->dlpi_phnum; i++) { |
| 164 // Find the ELF segment header that contains the actual code of the Chrome |
| 165 // binary. |
| 166 const ElfW(Phdr)& segment_header = shared_object->dlpi_phdr[i]; |
| 167 if (segment_header.p_type == SHT_PROGBITS && |
| 168 segment_header.p_offset == 0 && data) { |
| 169 MappingInfo* mapping = static_cast<MappingInfo*>(data); |
| 170 |
| 171 // Make sure the fields in the ELF header and MappingInfo have the |
| 172 // same size. |
| 173 static_assert(sizeof(mapping->addr) == sizeof(shared_object->dlpi_addr), |
| 174 "Integer size mismatch between MappingInfo::addr and " |
| 175 "dl_phdr_info::dlpi_addr."); |
| 176 static_assert(sizeof(mapping->size) == sizeof(segment_header.p_offset), |
| 177 "Integer size mismatch between MappingInfo::size and " |
| 178 "ElfW(Phdr)::p_memsz."); |
| 179 |
| 180 mapping->addr = shared_object->dlpi_addr + segment_header.p_offset; |
| 181 mapping->size = segment_header.p_memsz; |
| 182 if (g_dump_leak_analysis) { |
| 183 LOG(ERROR) << "Chrome mapped from " << std::hex |
| 184 << mapping->addr << " to " |
| 185 << mapping->addr + mapping->size; |
| 186 } |
| 187 return 1; |
| 188 } |
| 189 } |
| 190 return 0; |
| 191 } |
| 192 |
| 193 } // namespace |
| 194 |
| 195 // static |
| 196 void LeakDetector::Initialize() { |
| 197 // If the sampling factor is too low, don't bother enabling the leak detector. |
| 198 if (g_sampling_factor < 1) { |
| 199 LOG(ERROR) << "Not enabling leak detector because g_sampling_factor=" |
| 200 << g_sampling_factor; |
| 201 return; |
| 202 } |
| 203 |
| 204 if (IsInitialized()) |
| 205 return; |
| 206 |
| 207 // Locate the Chrome binary mapping before doing anything else. |
| 208 dl_iterate_phdr(IterateLoadedObjects, &chrome_mapping); |
| 209 |
| 210 // This should be done before the hooks are set up, since it should |
| 211 // call new, and we want that to be accounted for correctly. |
| 212 MallocExtension::Initialize(); |
| 213 |
| 214 if (CustomAllocator::IsInitialized()) { |
| 215 LOG(ERROR) << "Custom allocator can only be initialized once!"; |
| 216 return; |
| 217 } |
| 218 CustomAllocator::Initialize(); |
| 219 |
| 220 g_heap_lock = new(CustomAllocator::Allocate(sizeof(SpinLockWrapper))) |
| 221 SpinLockWrapper; |
| 222 |
| 223 ScopedSpinLockHolder lock(g_heap_lock); |
| 224 if (g_leak_detector) |
| 225 return; |
| 226 |
| 227 LOG(ERROR) << "%d: Starting leak detector. Sampling factor: " |
| 228 << g_sampling_factor; |
| 229 |
| 230 g_leak_detector = new(CustomAllocator::Allocate(sizeof(LeakDetectorImpl))) |
| 231 LeakDetectorImpl(chrome_mapping.addr, |
| 232 chrome_mapping.size, |
| 233 g_size_suspicion_threshold, |
| 234 g_call_stack_suspicion_threshold, |
| 235 g_dump_leak_analysis); |
| 236 |
| 237 // Now set the hooks that capture new/delete and malloc/free. |
| 238 CHECK_EQ(MallocHook::SetNewHook(&NewHook), nullptr); |
| 239 CHECK_EQ(MallocHook::SetDeleteHook(&DeleteHook), nullptr); |
| 240 } |
| 241 |
| 242 // static |
| 243 void LeakDetector::Shutdown() { |
| 244 { |
| 245 ScopedSpinLockHolder lock(g_heap_lock); |
| 246 |
| 247 if (!g_leak_detector) |
| 248 return; |
| 249 |
| 250 // Unset our new/delete hooks, checking they were previously set. |
| 251 CHECK_EQ(MallocHook::SetNewHook(nullptr), &NewHook); |
| 252 CHECK_EQ(MallocHook::SetDeleteHook(nullptr), &DeleteHook); |
| 253 |
| 254 g_leak_detector->~LeakDetectorImpl(); |
| 255 CustomAllocator::Free(g_leak_detector, sizeof(LeakDetectorImpl)); |
| 256 g_leak_detector = nullptr; |
| 257 } |
| 258 |
| 259 g_heap_lock->~SpinLockWrapper(); |
| 260 CustomAllocator::Free(g_heap_lock, sizeof(*g_heap_lock)); |
| 261 |
| 262 if (!CustomAllocator::Shutdown()) |
| 263 LOG(ERROR) << "Memory leak in LeakDetector, allocated objects remain."; |
| 264 |
| 265 LOG(ERROR) << "Stopped leak detector."; |
| 266 } |
| 267 |
| 268 // static |
| 269 bool LeakDetector::IsInitialized() { |
| 270 return g_leak_detector; |
| 271 } |
| 272 |
| 273 } // namespace leak_detector |
OLD | NEW |