1 // Copyright 2012 The Chromium Authors
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 "base/metrics/sparse_histogram.h"
6
7 #include <utility>
8
9 #include "base/logging.h"
10 #include "base/memory/ptr_util.h"
11 #include "base/metrics/dummy_histogram.h"
12 #include "base/metrics/histogram_functions.h"
13 #include "base/metrics/metrics_hashes.h"
14 #include "base/metrics/persistent_histogram_allocator.h"
15 #include "base/metrics/persistent_sample_map.h"
16 #include "base/metrics/sample_map.h"
17 #include "base/metrics/statistics_recorder.h"
18 #include "base/notreached.h"
19 #include "base/pickle.h"
20 #include "base/strings/utf_string_conversions.h"
21 #include "base/synchronization/lock.h"
22 #include "base/values.h"
23
24 namespace base {
25
26 typedef HistogramBase::Count Count;
27 typedef HistogramBase::Sample Sample;
28
29 // static
FactoryGet(std::string_view name,int32_t flags)30 HistogramBase* SparseHistogram::FactoryGet(std::string_view name,
31 int32_t flags) {
32 HistogramBase* histogram = StatisticsRecorder::FindHistogram(name);
33 if (!histogram) {
34 bool should_record =
35 StatisticsRecorder::ShouldRecordHistogram(HashMetricNameAs32Bits(name));
36 if (!should_record) {
37 return DummyHistogram::GetInstance();
38 }
39 // Try to create the histogram using a "persistent" allocator. If the
40 // allocator doesn't exist or if allocating from it fails, code below will
41 // allocate the histogram from the process heap.
42 PersistentMemoryAllocator::Reference histogram_ref = 0;
43 std::unique_ptr<HistogramBase> tentative_histogram;
44 PersistentHistogramAllocator* allocator = GlobalHistogramAllocator::Get();
45 if (allocator) {
46 tentative_histogram = allocator->AllocateHistogram(
47 SPARSE_HISTOGRAM, name, 0, 0, nullptr, flags, &histogram_ref);
48 }
49
50 // Handle the case where no persistent allocator is present or the
51 // persistent allocation fails (perhaps because it is full).
52 if (!tentative_histogram) {
53 DCHECK(!histogram_ref); // Should never have been set.
54 flags &= ~HistogramBase::kIsPersistent;
55 tentative_histogram.reset(new SparseHistogram(GetPermanentName(name)));
56 tentative_histogram->SetFlags(flags);
57 }
58
59 // Register this histogram with the StatisticsRecorder. Keep a copy of
60 // the pointer value to tell later whether the locally created histogram
61 // was registered or deleted. The type is "void" because it could point
62 // to released memory after the following line.
63 const void* tentative_histogram_ptr = tentative_histogram.get();
64 histogram = StatisticsRecorder::RegisterOrDeleteDuplicate(
65 tentative_histogram.release());
66
67 // Persistent histograms need some follow-up processing.
68 if (histogram_ref) {
69 allocator->FinalizeHistogram(histogram_ref,
70 histogram == tentative_histogram_ptr);
71 }
72 }
73
74 if (histogram->GetHistogramType() != SPARSE_HISTOGRAM) {
75 // The type does not match the existing histogram. This can come about if an
76 // extension updates in the middle of a Chrome run or simply by bad code
77 // within Chrome itself. We can't return null since calling code does not
78 // expect it, so return a dummy instance and log the name hash.
79 //
80 // Note: Theoretically the below line could be re-entrant if something has
81 // gone very wrong, but crashing w/ an infinite recursion seems OK then.
82 UmaHistogramSparse("Histogram.MismatchedConstructionArguments",
83 static_cast<Sample>(HashMetricName(name)));
84 DLOG(ERROR) << "Histogram " << name << " has a mismatched type";
85 return DummyHistogram::GetInstance();
86 }
87 return histogram;
88 }
89
90 // static
PersistentCreate(PersistentHistogramAllocator * allocator,const char * name,HistogramSamples::Metadata * meta,HistogramSamples::Metadata * logged_meta)91 std::unique_ptr<HistogramBase> SparseHistogram::PersistentCreate(
92 PersistentHistogramAllocator* allocator,
93 const char* name,
94 HistogramSamples::Metadata* meta,
95 HistogramSamples::Metadata* logged_meta) {
96 return WrapUnique(new SparseHistogram(allocator, name, meta, logged_meta));
97 }
98
99 SparseHistogram::~SparseHistogram() = default;
100
name_hash() const101 uint64_t SparseHistogram::name_hash() const {
102 return unlogged_samples_->id();
103 }
104
GetHistogramType() const105 HistogramType SparseHistogram::GetHistogramType() const {
106 return SPARSE_HISTOGRAM;
107 }
108
HasConstructionArguments(Sample expected_minimum,Sample expected_maximum,size_t expected_bucket_count) const109 bool SparseHistogram::HasConstructionArguments(
110 Sample expected_minimum,
111 Sample expected_maximum,
112 size_t expected_bucket_count) const {
113 // SparseHistogram never has min/max/bucket_count limit.
114 return false;
115 }
116
Add(Sample value)117 void SparseHistogram::Add(Sample value) {
118 AddCount(value, 1);
119 }
120
AddCount(Sample value,int count)121 void SparseHistogram::AddCount(Sample value, int count) {
122 if (count <= 0) {
123 NOTREACHED();
124 }
125 {
126 base::AutoLock auto_lock(lock_);
127 unlogged_samples_->Accumulate(value, count);
128 }
129
130 if (StatisticsRecorder::have_active_callbacks()) [[unlikely]] {
131 FindAndRunCallbacks(value);
132 }
133 }
134
SnapshotSamples() const135 std::unique_ptr<HistogramSamples> SparseHistogram::SnapshotSamples() const {
136 std::unique_ptr<SampleMap> snapshot(new SampleMap(name_hash()));
137
138 base::AutoLock auto_lock(lock_);
139 snapshot->Add(*unlogged_samples_);
140 snapshot->Add(*logged_samples_);
141 return std::move(snapshot);
142 }
143
SnapshotUnloggedSamples() const144 std::unique_ptr<HistogramSamples> SparseHistogram::SnapshotUnloggedSamples()
145 const {
146 std::unique_ptr<SampleMap> snapshot(new SampleMap(name_hash()));
147
148 base::AutoLock auto_lock(lock_);
149 snapshot->Add(*unlogged_samples_);
150
151 return std::move(snapshot);
152 }
153
MarkSamplesAsLogged(const HistogramSamples & samples)154 void SparseHistogram::MarkSamplesAsLogged(const HistogramSamples& samples) {
155 DCHECK(!final_delta_created_);
156
157 base::AutoLock auto_lock(lock_);
158 unlogged_samples_->Subtract(samples);
159 logged_samples_->Add(samples);
160 }
161
SnapshotDelta()162 std::unique_ptr<HistogramSamples> SparseHistogram::SnapshotDelta() {
163 DCHECK(!final_delta_created_);
164
165 std::unique_ptr<SampleMap> snapshot =
166 std::make_unique<SampleMap>(name_hash());
167 base::AutoLock auto_lock(lock_);
168 snapshot->Extract(*unlogged_samples_);
169 logged_samples_->Add(*snapshot);
170 return std::move(snapshot);
171 }
172
SnapshotFinalDelta() const173 std::unique_ptr<HistogramSamples> SparseHistogram::SnapshotFinalDelta() const {
174 DCHECK(!final_delta_created_);
175 final_delta_created_ = true;
176
177 std::unique_ptr<SampleMap> snapshot(new SampleMap(name_hash()));
178 base::AutoLock auto_lock(lock_);
179 snapshot->Add(*unlogged_samples_);
180
181 return std::move(snapshot);
182 }
183
AddSamples(const HistogramSamples & samples)184 bool SparseHistogram::AddSamples(const HistogramSamples& samples) {
185 base::AutoLock auto_lock(lock_);
186 return unlogged_samples_->Add(samples);
187 }
188
AddSamplesFromPickle(PickleIterator * iter)189 bool SparseHistogram::AddSamplesFromPickle(PickleIterator* iter) {
190 base::AutoLock auto_lock(lock_);
191 return unlogged_samples_->AddFromPickle(iter);
192 }
193
ToGraphDict() const194 base::Value::Dict SparseHistogram::ToGraphDict() const {
195 std::unique_ptr<HistogramSamples> snapshot = SnapshotSamples();
196 return snapshot->ToGraphDict(histogram_name(), flags());
197 }
198
SerializeInfoImpl(Pickle * pickle) const199 void SparseHistogram::SerializeInfoImpl(Pickle* pickle) const {
200 pickle->WriteString(histogram_name());
201 pickle->WriteInt(flags());
202 }
203
SparseHistogram(const char * name)204 SparseHistogram::SparseHistogram(const char* name)
205 : HistogramBase(name),
206 unlogged_samples_(new SampleMap(HashMetricName(name))),
207 logged_samples_(new SampleMap(unlogged_samples_->id())) {}
208
SparseHistogram(PersistentHistogramAllocator * allocator,const char * name,HistogramSamples::Metadata * meta,HistogramSamples::Metadata * logged_meta)209 SparseHistogram::SparseHistogram(PersistentHistogramAllocator* allocator,
210 const char* name,
211 HistogramSamples::Metadata* meta,
212 HistogramSamples::Metadata* logged_meta)
213 : HistogramBase(name),
214 // While other histogram types maintain a static vector of values with
215 // sufficient space for both "active" and "logged" samples, with each
216 // SampleVector being given the appropriate half, sparse histograms
217 // have no such initial allocation. Each sample has its own record
218 // attached to a single PersistentSampleMap by a common 64-bit identifier.
219 // Since a sparse histogram has two sample maps (active and logged),
220 // there must be two sets of sample records with diffent IDs. The
221 // "active" samples use, for convenience purposes, an ID matching
222 // that of the histogram while the "logged" samples use that number
223 // plus 1.
224 unlogged_samples_(
225 new PersistentSampleMap(HashMetricName(name), allocator, meta)),
226 logged_samples_(new PersistentSampleMap(unlogged_samples_->id() + 1,
227 allocator,
228 logged_meta)) {}
229
DeserializeInfoImpl(PickleIterator * iter)230 HistogramBase* SparseHistogram::DeserializeInfoImpl(PickleIterator* iter) {
231 std::string histogram_name;
232 int flags;
233 if (!iter->ReadString(&histogram_name) || !iter->ReadInt(&flags)) {
234 DLOG(ERROR) << "Pickle error decoding Histogram: " << histogram_name;
235 return nullptr;
236 }
237
238 flags &= ~HistogramBase::kIPCSerializationSourceFlag;
239
240 return SparseHistogram::FactoryGet(histogram_name, flags);
241 }
242
GetParameters() const243 Value::Dict SparseHistogram::GetParameters() const {
244 // Unlike Histogram::GetParameters, only set the type here, and no other
245 // params. The other params do not make sense for sparse histograms.
246 Value::Dict params;
247 params.Set("type", HistogramTypeToString(GetHistogramType()));
248 return params;
249 }
250
251 } // namespace base
252