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