OLD | NEW |
1 // Copyright 2016 The Chromium Authors. All rights reserved. | 1 // Copyright 2016 The Chromium Authors. All rights reserved. |
2 // Use of this source code is governed by a BSD-style license that can be | 2 // Use of this source code is governed by a BSD-style license that can be |
3 // found in the LICENSE file. | 3 // found in the LICENSE file. |
4 | 4 |
5 #include "components/metrics/leak_detector/leak_detector.h" | 5 #include "components/metrics/leak_detector/leak_detector.h" |
6 | 6 |
| 7 #include <stdint.h> |
| 8 |
| 9 #include "base/allocator/allocator_extension.h" |
| 10 #include "base/bind.h" |
| 11 #include "base/lazy_instance.h" |
| 12 #include "base/logging.h" |
| 13 #include "base/numerics/safe_conversions.h" |
| 14 #include "base/threading/thread_local.h" |
| 15 #include "components/metrics/leak_detector/custom_allocator.h" |
| 16 #include "components/metrics/leak_detector/leak_detector_impl.h" |
7 #include "content/public/browser/browser_thread.h" | 17 #include "content/public/browser/browser_thread.h" |
8 | 18 |
| 19 #if defined(OS_CHROMEOS) |
| 20 #include <link.h> // for dl_iterate_phdr |
| 21 #else |
| 22 #error "Getting binary mapping info is not supported on this platform." |
| 23 #endif // defined(OS_CHROMEOS) |
| 24 |
9 namespace metrics { | 25 namespace metrics { |
10 | 26 |
| 27 using LeakReport = LeakDetector::LeakReport; |
| 28 using InternalLeakReport = leak_detector::LeakDetectorImpl::LeakReport; |
| 29 template <typename T> |
| 30 using InternalVector = leak_detector::LeakDetectorImpl::InternalVector<T>; |
| 31 |
| 32 namespace { |
| 33 |
| 34 #if defined(OS_CHROMEOS) |
| 35 // For storing the address range of the Chrome binary in memory. |
| 36 struct MappingInfo { |
| 37 uintptr_t addr; |
| 38 size_t size; |
| 39 }; |
| 40 |
| 41 // Callback for dl_iterate_phdr() to find the Chrome binary mapping. |
| 42 int IterateLoadedObjects(struct dl_phdr_info* shared_object, |
| 43 size_t /* size */, |
| 44 void* data) { |
| 45 for (int i = 0; i < shared_object->dlpi_phnum; i++) { |
| 46 // Find the ELF segment header that contains the actual code of the Chrome |
| 47 // binary. |
| 48 const ElfW(Phdr)& segment_header = shared_object->dlpi_phdr[i]; |
| 49 if (segment_header.p_type == SHT_PROGBITS && segment_header.p_offset == 0 && |
| 50 data) { |
| 51 MappingInfo* mapping = reinterpret_cast<MappingInfo*>(data); |
| 52 |
| 53 // Make sure the fields in the ELF header and MappingInfo have the |
| 54 // same size. |
| 55 static_assert(sizeof(mapping->addr) == sizeof(shared_object->dlpi_addr), |
| 56 "Integer size mismatch between MappingInfo::addr and " |
| 57 "dl_phdr_info::dlpi_addr."); |
| 58 static_assert(sizeof(mapping->size) == sizeof(segment_header.p_offset), |
| 59 "Integer size mismatch between MappingInfo::size and " |
| 60 "ElfW(Phdr)::p_memsz."); |
| 61 |
| 62 mapping->addr = shared_object->dlpi_addr + segment_header.p_offset; |
| 63 mapping->size = segment_header.p_memsz; |
| 64 return 1; |
| 65 } |
| 66 } |
| 67 return 0; |
| 68 } |
| 69 #endif // defined(OS_CHROMEOS) |
| 70 |
| 71 // Convert a pointer to a hash value. Returns only the upper eight bits. |
| 72 inline uint64_t PointerToHash(const void* ptr) { |
| 73 // The input data is the pointer address, not the location in memory pointed |
| 74 // to by the pointer. |
| 75 // The multiplier is taken from Farmhash code: |
| 76 // https://github.com/google/farmhash/blob/master/src/farmhash.cc |
| 77 const uint64_t kMultiplier = 0x9ddfea08eb382d69ULL; |
| 78 return reinterpret_cast<uint64_t>(ptr) * kMultiplier; |
| 79 } |
| 80 |
| 81 // Converts a vector of leak reports generated by LeakDetectorImpl |
| 82 // (InternalLeakReport) to a vector of leak reports suitable for sending to |
| 83 // LeakDetector's observers (LeakReport). |
| 84 void GetReportsForObservers( |
| 85 const InternalVector<InternalLeakReport>& leak_reports, |
| 86 std::vector<LeakReport>* reports_for_observers) { |
| 87 reports_for_observers->clear(); |
| 88 reports_for_observers->resize(leak_reports.size()); |
| 89 for (const InternalLeakReport& report : leak_reports) { |
| 90 reports_for_observers->push_back(LeakReport()); |
| 91 LeakReport* new_report = &reports_for_observers->back(); |
| 92 |
| 93 new_report->alloc_size_bytes = report.alloc_size_bytes(); |
| 94 if (!report.call_stack().empty()) { |
| 95 new_report->call_stack.resize(report.call_stack().size()); |
| 96 memcpy(new_report->call_stack.data(), report.call_stack().data(), |
| 97 report.call_stack().size() * sizeof(report.call_stack()[0])); |
| 98 } |
| 99 } |
| 100 } |
| 101 |
| 102 // The only instance of LeakDetector that should be used. |
| 103 base::LazyInstance<LeakDetector>::Leaky g_instance = LAZY_INSTANCE_INITIALIZER; |
| 104 |
| 105 // Thread-specific flag indicating that one of the alloc hooks have already been |
| 106 // entered. Used to handle recursive hook calls. Anything allocated when this |
| 107 // flag is set should also be freed when this flag is set. |
| 108 base::LazyInstance<base::ThreadLocalBoolean>::Leaky g_entered_hook_tls; |
| 109 |
| 110 } // namespace |
| 111 |
11 LeakDetector::LeakReport::LeakReport() {} | 112 LeakDetector::LeakReport::LeakReport() {} |
12 | 113 |
13 LeakDetector::LeakReport::~LeakReport() {} | 114 LeakDetector::LeakReport::~LeakReport() {} |
14 | 115 |
15 LeakDetector::LeakDetector(float sampling_rate, | 116 // static |
16 size_t max_call_stack_unwind_depth, | 117 LeakDetector* LeakDetector::GetInstance() { |
17 uint64_t analysis_interval_bytes, | 118 return g_instance.Pointer(); |
18 uint32_t size_suspicion_threshold, | 119 } |
19 uint32_t call_stack_suspicion_threshold) | 120 |
20 : weak_factory_(this) { | 121 void LeakDetector::Init(float sampling_rate, |
21 // TODO(sque): Connect this class to LeakDetectorImpl and base::allocator. | 122 size_t max_call_stack_unwind_depth, |
22 } | 123 uint64_t analysis_interval_bytes, |
| 124 uint32_t size_suspicion_threshold, |
| 125 uint32_t call_stack_suspicion_threshold) { |
| 126 DCHECK(thread_checker_.CalledOnValidThread()); |
| 127 DCHECK(sampling_rate > 0) << "Sampling rate cannot be zero or negative."; |
| 128 |
| 129 sampling_factor_ = base::saturated_cast<uint64_t>(sampling_rate * UINT64_MAX); |
| 130 |
| 131 analysis_interval_bytes_ = analysis_interval_bytes; |
| 132 max_call_stack_unwind_depth_ = max_call_stack_unwind_depth; |
| 133 |
| 134 MappingInfo mapping = {0}; |
| 135 #if defined(OS_CHROMEOS) |
| 136 // Locate the Chrome binary mapping info. |
| 137 dl_iterate_phdr(IterateLoadedObjects, &mapping); |
| 138 #endif // defined(OS_CHROMEOS) |
| 139 |
| 140 // CustomAllocator can use the default allocator, as long as the hook |
| 141 // functions can handle recursive calls. |
| 142 leak_detector::CustomAllocator::Initialize(); |
| 143 |
| 144 // The initialization should be done only once. Check for this by examining |
| 145 // whether |impl_| has already been initialized. |
| 146 CHECK(!impl_.get()) << "Cannot initialize LeakDetector more than once!"; |
| 147 impl_.reset(new leak_detector::LeakDetectorImpl( |
| 148 mapping.addr, mapping.size, size_suspicion_threshold, |
| 149 call_stack_suspicion_threshold)); |
| 150 |
| 151 // Register allocator hook functions. |
| 152 base::allocator::SetHooks(&AllocHook, &FreeHook); |
| 153 } |
| 154 |
| 155 void LeakDetector::AddObserver(Observer* observer) { |
| 156 base::AutoLock lock(observers_lock_); |
| 157 observers_.AddObserver(observer); |
| 158 } |
| 159 |
| 160 void LeakDetector::RemoveObserver(Observer* observer) { |
| 161 base::AutoLock lock(observers_lock_); |
| 162 observers_.RemoveObserver(observer); |
| 163 } |
| 164 |
| 165 LeakDetector::LeakDetector() |
| 166 : total_alloc_size_(0), |
| 167 last_analysis_alloc_size_(0), |
| 168 analysis_interval_bytes_(0), |
| 169 max_call_stack_unwind_depth_(0), |
| 170 sampling_factor_(0) {} |
23 | 171 |
24 LeakDetector::~LeakDetector() {} | 172 LeakDetector::~LeakDetector() {} |
25 | 173 |
26 void LeakDetector::AddObserver(Observer* observer) { | 174 // static |
27 DCHECK(thread_checker_.CalledOnValidThread()); | 175 void LeakDetector::AllocHook(const void* ptr, size_t size) { |
28 observers_.AddObserver(observer); | 176 base::ThreadLocalBoolean& entered_hook = g_entered_hook_tls.Get(); |
29 } | 177 if (entered_hook.Get()) |
30 | 178 return; |
31 void LeakDetector::RemoveObserver(Observer* observer) { | 179 |
32 DCHECK(thread_checker_.CalledOnValidThread()); | 180 LeakDetector* detector = GetInstance(); |
33 observers_.RemoveObserver(observer); | 181 |
| 182 // Add the allocation size to the total size across all threads. This should |
| 183 // be done before sampling because it is more accurate than attempting to |
| 184 // extrapolate it from the post-sampling total size. |
| 185 { |
| 186 base::AutoLock lock(detector->recording_lock_); |
| 187 detector->total_alloc_size_ += size; |
| 188 } |
| 189 |
| 190 if (!detector->ShouldSample(ptr)) |
| 191 return; |
| 192 |
| 193 entered_hook.Set(true); |
| 194 |
| 195 // Get stack trace if necessary. |
| 196 std::vector<void*> stack; |
| 197 int depth = 0; |
| 198 if (detector->impl_->ShouldGetStackTraceForSize(size)) { |
| 199 stack.resize(detector->max_call_stack_unwind_depth_); |
| 200 depth = base::allocator::GetCallStack(stack.data(), stack.size()); |
| 201 } |
| 202 |
| 203 { |
| 204 base::AutoLock lock(detector->recording_lock_); |
| 205 detector->impl_->RecordAlloc(ptr, size, depth, stack.data()); |
| 206 |
| 207 // Check for leaks after |analysis_interval_bytes_| bytes have been |
| 208 // allocated since the last time that was done. |
| 209 const auto& total_alloc_size = detector->total_alloc_size_; |
| 210 const auto& analysis_interval_bytes = detector->analysis_interval_bytes_; |
| 211 if (total_alloc_size > |
| 212 detector->last_analysis_alloc_size_ + analysis_interval_bytes) { |
| 213 // Try to maintain regular intervals of size |analysis_interval_bytes_|. |
| 214 detector->last_analysis_alloc_size_ = |
| 215 total_alloc_size - total_alloc_size % analysis_interval_bytes; |
| 216 |
| 217 InternalVector<InternalLeakReport> leak_reports; |
| 218 detector->impl_->TestForLeaks(&leak_reports); |
| 219 |
| 220 // Pass leak reports to observers. |
| 221 std::vector<LeakReport> leak_reports_for_observers; |
| 222 GetReportsForObservers(leak_reports, &leak_reports_for_observers); |
| 223 detector->NotifyObservers(leak_reports_for_observers); |
| 224 } |
| 225 } |
| 226 |
| 227 { |
| 228 // The internal memory of |stack| should be freed before setting |
| 229 // |entered_hook| to false at the end of this function. Free it here by |
| 230 // moving the internal memory to a temporary variable that will go out of |
| 231 // scope. |
| 232 std::vector<void*> dummy_stack; |
| 233 dummy_stack.swap(stack); |
| 234 } |
| 235 |
| 236 entered_hook.Set(false); |
| 237 } |
| 238 |
| 239 // static |
| 240 void LeakDetector::FreeHook(const void* ptr) { |
| 241 LeakDetector* detector = GetInstance(); |
| 242 if (!detector->ShouldSample(ptr)) |
| 243 return; |
| 244 |
| 245 base::ThreadLocalBoolean& entered_hook = g_entered_hook_tls.Get(); |
| 246 if (entered_hook.Get()) |
| 247 return; |
| 248 |
| 249 entered_hook.Set(true); |
| 250 |
| 251 { |
| 252 base::AutoLock lock(detector->recording_lock_); |
| 253 detector->impl_->RecordFree(ptr); |
| 254 } |
| 255 |
| 256 entered_hook.Set(false); |
| 257 } |
| 258 |
| 259 inline bool LeakDetector::ShouldSample(const void* ptr) const { |
| 260 return PointerToHash(ptr) < sampling_factor_; |
34 } | 261 } |
35 | 262 |
36 void LeakDetector::NotifyObservers(const std::vector<LeakReport>& reports) { | 263 void LeakDetector::NotifyObservers(const std::vector<LeakReport>& reports) { |
| 264 if (reports.empty()) |
| 265 return; |
| 266 |
37 if (!content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)) { | 267 if (!content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)) { |
38 content::BrowserThread::PostTask( | 268 content::BrowserThread::PostTask( |
39 content::BrowserThread::UI, FROM_HERE, | 269 content::BrowserThread::UI, FROM_HERE, |
40 base::Bind(&LeakDetector::NotifyObservers, weak_factory_.GetWeakPtr(), | 270 base::Bind(&LeakDetector::NotifyObservers, base::Unretained(this), |
41 reports)); | 271 reports)); |
42 return; | 272 return; |
43 } | 273 } |
44 | 274 |
45 for (const LeakReport& report : reports) { | 275 for (const LeakReport& report : reports) { |
| 276 base::AutoLock lock(observers_lock_); |
46 FOR_EACH_OBSERVER(Observer, observers_, OnLeakFound(report)); | 277 FOR_EACH_OBSERVER(Observer, observers_, OnLeakFound(report)); |
47 } | 278 } |
48 } | 279 } |
49 | 280 |
50 } // namespace metrics | 281 } // namespace metrics |
OLD | NEW |