Chromium Code Reviews| 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, |
| 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) { | |
| 171 DCHECK(thread_checker_.CalledOnValidThread()); | |
|
Primiano Tucci (use gerrit)
2016/03/15 11:49:24
I don't think this DCHECK can possibly be hit.
the
Simon Que
2016/03/15 18:33:42
Done.
| |
| 22 } | 172 } |
| 23 | 173 |
| 24 LeakDetector::~LeakDetector() {} | 174 LeakDetector::~LeakDetector() {} |
| 25 | 175 |
| 26 void LeakDetector::AddObserver(Observer* observer) { | 176 // static |
| 27 DCHECK(thread_checker_.CalledOnValidThread()); | 177 void LeakDetector::AllocHook(const void* ptr, size_t size) { |
| 28 observers_.AddObserver(observer); | 178 base::ThreadLocalBoolean& entered_hook = g_entered_hook_tls.Get(); |
| 29 } | 179 if (entered_hook.Get()) |
| 30 | 180 return; |
| 31 void LeakDetector::RemoveObserver(Observer* observer) { | 181 |
| 32 DCHECK(thread_checker_.CalledOnValidThread()); | 182 LeakDetector* detector = GetInstance(); |
| 33 observers_.RemoveObserver(observer); | 183 |
| 184 // Add the allocation size to the total size across all threads. This should | |
| 185 // be done before sampling because it is more accurate than attempting to | |
| 186 // extrapolate it from the post-sampling total size. | |
| 187 detector->alloc_size_lock_.Acquire(); | |
|
Primiano Tucci (use gerrit)
2016/03/15 11:49:23
Just a minor stylistic nit, I usually see this as
Simon Que
2016/03/15 18:33:42
Done.
| |
| 188 detector->total_alloc_size_ += size; | |
| 189 detector->alloc_size_lock_.Release(); | |
|
Primiano Tucci (use gerrit)
2016/03/15 11:49:24
Note that you write here the total_alloc_size_ in
Simon Que
2016/03/15 18:33:42
I'm not that concerned about it since |total_alloc
| |
| 190 | |
| 191 if (!detector->ShouldSample(ptr)) | |
| 192 return; | |
| 193 | |
| 194 entered_hook.Set(true); | |
| 195 | |
| 196 // Get stack trace if necessary. | |
| 197 std::vector<void*> stack; | |
| 198 int depth = 0; | |
| 199 if (detector->impl_->ShouldGetStackTraceForSize(size)) { | |
| 200 stack.resize(detector->max_call_stack_unwind_depth_); | |
| 201 depth = base::allocator::GetCallStack(stack.data(), stack.size()); | |
| 202 } | |
| 203 | |
| 204 detector->impl_lock_.Acquire(); | |
| 205 detector->impl_->RecordAlloc(ptr, size, depth, stack.data()); | |
| 206 detector->impl_lock_.Release(); | |
| 207 | |
| 208 { | |
| 209 // The internal memory of |stack| should be freed before setting | |
| 210 // |entered_hook| to false at the end of this function. Free it here by | |
| 211 // moving the internal memory to a temporary variable that will go out of | |
| 212 // scope. | |
| 213 std::vector<void*> dummy_stack; | |
| 214 dummy_stack.swap(stack); | |
| 215 } | |
| 216 | |
| 217 // Check for leaks after |analysis_interval_bytes_| bytes have been | |
| 218 // allocated since the last time that was done. | |
| 219 const auto& total_alloc_size = detector->total_alloc_size_; | |
| 220 const auto& analysis_interval_bytes = detector->analysis_interval_bytes_; | |
| 221 if (total_alloc_size > | |
| 222 detector->last_analysis_alloc_size_ + analysis_interval_bytes) { | |
| 223 // Try to maintain regular intervals of size |analysis_interval_bytes_|. | |
| 224 detector->alloc_size_lock_.Acquire(); | |
| 225 detector->last_analysis_alloc_size_ = | |
| 226 total_alloc_size - total_alloc_size % analysis_interval_bytes; | |
| 227 detector->alloc_size_lock_.Release(); | |
| 228 | |
| 229 InternalVector<InternalLeakReport> leak_reports; | |
| 230 detector->impl_lock_.Acquire(); | |
| 231 detector->impl_->TestForLeaks(&leak_reports); | |
| 232 detector->impl_lock_.Release(); | |
|
Primiano Tucci (use gerrit)
2016/03/15 11:49:24
You have two fine grained locks here (alloc_size_l
Simon Que
2016/03/15 18:33:42
Done.
| |
| 233 | |
| 234 // Pass leak reports to observers. | |
| 235 std::vector<LeakReport> leak_reports_for_observers; | |
| 236 GetReportsForObservers(leak_reports, &leak_reports_for_observers); | |
| 237 detector->NotifyObservers(leak_reports_for_observers); | |
| 238 } | |
| 239 | |
| 240 entered_hook.Set(false); | |
| 241 } | |
| 242 | |
| 243 // static | |
| 244 void LeakDetector::FreeHook(const void* ptr) { | |
| 245 LeakDetector* detector = GetInstance(); | |
| 246 if (!detector->ShouldSample(ptr)) | |
| 247 return; | |
| 248 | |
| 249 base::ThreadLocalBoolean& entered_hook = g_entered_hook_tls.Get(); | |
| 250 if (entered_hook.Get()) | |
| 251 return; | |
| 252 | |
| 253 entered_hook.Set(true); | |
| 254 | |
| 255 detector->impl_lock_.Acquire(); | |
| 256 detector->impl_->RecordFree(ptr); | |
| 257 detector->impl_lock_.Release(); | |
| 258 | |
| 259 entered_hook.Set(false); | |
| 260 } | |
| 261 | |
| 262 inline bool LeakDetector::ShouldSample(const void* ptr) const { | |
| 263 return PointerToHash(ptr) < sampling_factor_; | |
| 34 } | 264 } |
| 35 | 265 |
| 36 void LeakDetector::NotifyObservers(const std::vector<LeakReport>& reports) { | 266 void LeakDetector::NotifyObservers(const std::vector<LeakReport>& reports) { |
|
Primiano Tucci (use gerrit)
2016/03/15 11:49:24
Suggestion for a future improvement, observer_list
Simon Que
2016/03/15 18:33:42
Done. Added a TODO.
| |
| 267 if (reports.empty()) | |
| 268 return; | |
| 269 | |
| 37 if (!content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)) { | 270 if (!content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)) { |
| 38 content::BrowserThread::PostTask( | 271 content::BrowserThread::PostTask( |
| 39 content::BrowserThread::UI, FROM_HERE, | 272 content::BrowserThread::UI, FROM_HERE, |
| 40 base::Bind(&LeakDetector::NotifyObservers, weak_factory_.GetWeakPtr(), | 273 base::Bind(&LeakDetector::NotifyObservers, base::Unretained(this), |
| 41 reports)); | 274 reports)); |
| 42 return; | 275 return; |
| 43 } | 276 } |
| 44 | 277 |
| 45 for (const LeakReport& report : reports) { | 278 for (const LeakReport& report : reports) { |
| 279 base::AutoLock lock(observers_lock_); | |
| 46 FOR_EACH_OBSERVER(Observer, observers_, OnLeakFound(report)); | 280 FOR_EACH_OBSERVER(Observer, observers_, OnLeakFound(report)); |
| 47 } | 281 } |
| 48 } | 282 } |
| 49 | 283 |
| 50 } // namespace metrics | 284 } // namespace metrics |
| OLD | NEW |