• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2016 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/persistent_sample_map.h"
6 
7 #include "base/atomicops.h"
8 #include "base/check_op.h"
9 #include "base/containers/contains.h"
10 #include "base/debug/crash_logging.h"
11 #include "base/metrics/histogram_macros.h"
12 #include "base/metrics/persistent_histogram_allocator.h"
13 #include "base/notreached.h"
14 #include "base/numerics/safe_conversions.h"
15 
16 namespace base {
17 
18 typedef HistogramBase::Count Count;
19 typedef HistogramBase::Sample Sample;
20 
21 namespace {
22 
23 // An iterator for going through a PersistentSampleMap. The logic here is
24 // identical to that of the iterator for SampleMap but with different data
25 // structures. Changes here likely need to be duplicated there.
26 template <typename T, typename I>
27 class IteratorTemplate : public SampleCountIterator {
28  public:
IteratorTemplate(T & sample_counts)29   explicit IteratorTemplate(T& sample_counts)
30       : iter_(sample_counts.begin()), end_(sample_counts.end()) {
31     SkipEmptyBuckets();
32   }
33 
34   ~IteratorTemplate() override;
35 
36   // SampleCountIterator:
Done() const37   bool Done() const override { return iter_ == end_; }
Next()38   void Next() override {
39     DCHECK(!Done());
40     ++iter_;
41     SkipEmptyBuckets();
42   }
43   void Get(HistogramBase::Sample* min,
44            int64_t* max,
45            HistogramBase::Count* count) override;
46 
47  private:
SkipEmptyBuckets()48   void SkipEmptyBuckets() {
49     while (!Done() && subtle::NoBarrier_Load(iter_->second) == 0) {
50       ++iter_;
51     }
52   }
53 
54   I iter_;
55   const I end_;
56 };
57 
58 typedef std::map<HistogramBase::Sample,
59                  raw_ptr<HistogramBase::Count, CtnExperimental>>
60     SampleToCountMap;
61 typedef IteratorTemplate<const SampleToCountMap,
62                          SampleToCountMap::const_iterator>
63     PersistentSampleMapIterator;
64 
65 template <>
66 PersistentSampleMapIterator::~IteratorTemplate() = default;
67 
68 // Get() for an iterator of a PersistentSampleMap.
69 template <>
Get(Sample * min,int64_t * max,Count * count)70 void PersistentSampleMapIterator::Get(Sample* min, int64_t* max, Count* count) {
71   DCHECK(!Done());
72   *min = iter_->first;
73   *max = strict_cast<int64_t>(iter_->first) + 1;
74   // We have to do the following atomically, because even if the caller is using
75   // a lock, a separate process (that is not aware of this lock) may
76   // concurrently modify the value (note that iter_->second is a pointer to a
77   // sample count, which may live in shared memory).
78   *count = subtle::NoBarrier_Load(iter_->second);
79 }
80 
81 typedef IteratorTemplate<SampleToCountMap, SampleToCountMap::iterator>
82     ExtractingPersistentSampleMapIterator;
83 
84 template <>
~IteratorTemplate()85 ExtractingPersistentSampleMapIterator::~IteratorTemplate() {
86   // Ensure that the user has consumed all the samples in order to ensure no
87   // samples are lost.
88   DCHECK(Done());
89 }
90 
91 // Get() for an extracting iterator of a PersistentSampleMap.
92 template <>
Get(Sample * min,int64_t * max,Count * count)93 void ExtractingPersistentSampleMapIterator::Get(Sample* min,
94                                                 int64_t* max,
95                                                 Count* count) {
96   DCHECK(!Done());
97   *min = iter_->first;
98   *max = strict_cast<int64_t>(iter_->first) + 1;
99   // We have to do the following atomically, because even if the caller is using
100   // a lock, a separate process (that is not aware of this lock) may
101   // concurrently modify the value (note that iter_->second is a pointer to a
102   // sample count, which may live in shared memory).
103   *count = subtle::NoBarrier_AtomicExchange(iter_->second, 0);
104 }
105 
106 // This structure holds an entry for a PersistentSampleMap within a persistent
107 // memory allocator. The "id" must be unique across all maps held by an
108 // allocator or they will get attached to the wrong sample map.
109 struct SampleRecord {
110   // SHA1(SampleRecord): Increment this if structure changes!
111   static constexpr uint32_t kPersistentTypeId = 0x8FE6A69F + 1;
112 
113   // Expected size for 32/64-bit check.
114   static constexpr size_t kExpectedInstanceSize = 16;
115 
116   uint64_t id;   // Unique identifier of owner.
117   Sample value;  // The value for which this record holds a count.
118   Count count;   // The count associated with the above value.
119 };
120 
121 }  // namespace
122 
PersistentSampleMap(uint64_t id,PersistentHistogramAllocator * allocator,Metadata * meta)123 PersistentSampleMap::PersistentSampleMap(
124     uint64_t id,
125     PersistentHistogramAllocator* allocator,
126     Metadata* meta)
127     : HistogramSamples(id, meta), allocator_(allocator) {}
128 
129 PersistentSampleMap::~PersistentSampleMap() = default;
130 
Accumulate(Sample value,Count count)131 void PersistentSampleMap::Accumulate(Sample value, Count count) {
132   // We have to do the following atomically, because even if the caller is using
133   // a lock, a separate process (that is not aware of this lock) may
134   // concurrently modify the value.
135   subtle::NoBarrier_AtomicIncrement(GetOrCreateSampleCountStorage(value),
136                                     count);
137   IncreaseSumAndCount(strict_cast<int64_t>(count) * value, count);
138 }
139 
GetCount(Sample value) const140 Count PersistentSampleMap::GetCount(Sample value) const {
141   // Have to override "const" to make sure all samples have been loaded before
142   // being able to know what value to return.
143   Count* count_pointer =
144       const_cast<PersistentSampleMap*>(this)->GetSampleCountStorage(value);
145   return count_pointer ? subtle::NoBarrier_Load(count_pointer) : 0;
146 }
147 
TotalCount() const148 Count PersistentSampleMap::TotalCount() const {
149   // Have to override "const" in order to make sure all samples have been
150   // loaded before trying to iterate over the map.
151   const_cast<PersistentSampleMap*>(this)->ImportSamples(
152       /*until_value=*/std::nullopt);
153 
154   Count count = 0;
155   for (const auto& entry : sample_counts_) {
156     count += subtle::NoBarrier_Load(entry.second);
157   }
158   return count;
159 }
160 
Iterator() const161 std::unique_ptr<SampleCountIterator> PersistentSampleMap::Iterator() const {
162   // Have to override "const" in order to make sure all samples have been
163   // loaded before trying to iterate over the map.
164   const_cast<PersistentSampleMap*>(this)->ImportSamples(
165       /*until_value=*/std::nullopt);
166   return std::make_unique<PersistentSampleMapIterator>(sample_counts_);
167 }
168 
ExtractingIterator()169 std::unique_ptr<SampleCountIterator> PersistentSampleMap::ExtractingIterator() {
170   // Make sure all samples have been loaded before trying to iterate over the
171   // map.
172   ImportSamples(/*until_value=*/std::nullopt);
173   return std::make_unique<ExtractingPersistentSampleMapIterator>(
174       sample_counts_);
175 }
176 
IsDefinitelyEmpty() const177 bool PersistentSampleMap::IsDefinitelyEmpty() const {
178   // Not implemented.
179   NOTREACHED();
180 }
181 
182 // static
183 PersistentMemoryAllocator::Reference
GetNextPersistentRecord(PersistentMemoryAllocator::Iterator & iterator,uint64_t * sample_map_id,Sample * value)184 PersistentSampleMap::GetNextPersistentRecord(
185     PersistentMemoryAllocator::Iterator& iterator,
186     uint64_t* sample_map_id,
187     Sample* value) {
188   const SampleRecord* record = iterator.GetNextOfObject<SampleRecord>();
189   if (!record) {
190     return 0;
191   }
192 
193   *sample_map_id = record->id;
194   *value = record->value;
195   return iterator.GetAsReference(record);
196 }
197 
198 // static
199 PersistentMemoryAllocator::Reference
CreatePersistentRecord(PersistentMemoryAllocator * allocator,uint64_t sample_map_id,Sample value)200 PersistentSampleMap::CreatePersistentRecord(
201     PersistentMemoryAllocator* allocator,
202     uint64_t sample_map_id,
203     Sample value) {
204   SampleRecord* record = allocator->New<SampleRecord>();
205   if (!record) {
206     if (!allocator->IsFull()) {
207 #if !BUILDFLAG(IS_NACL)
208       // TODO(crbug.com/40064026): Remove these. They are used to investigate
209       // unexpected failures.
210       SCOPED_CRASH_KEY_BOOL("PersistentSampleMap", "corrupted",
211                             allocator->IsCorrupt());
212 #endif  // !BUILDFLAG(IS_NACL)
213       DUMP_WILL_BE_NOTREACHED() << "corrupt=" << allocator->IsCorrupt();
214     }
215     return 0;
216   }
217 
218   record->id = sample_map_id;
219   record->value = value;
220   record->count = 0;
221 
222   PersistentMemoryAllocator::Reference ref = allocator->GetAsReference(record);
223   allocator->MakeIterable(ref);
224   return ref;
225 }
226 
AddSubtractImpl(SampleCountIterator * iter,Operator op)227 bool PersistentSampleMap::AddSubtractImpl(SampleCountIterator* iter,
228                                           Operator op) {
229   Sample min;
230   int64_t max;
231   Count count;
232   for (; !iter->Done(); iter->Next()) {
233     iter->Get(&min, &max, &count);
234     if (count == 0)
235       continue;
236     if (strict_cast<int64_t>(min) + 1 != max)
237       return false;  // SparseHistogram only supports bucket with size 1.
238 
239     // We have to do the following atomically, because even if the caller is
240     // using a lock, a separate process (that is not aware of this lock) may
241     // concurrently modify the value.
242     subtle::Barrier_AtomicIncrement(
243         GetOrCreateSampleCountStorage(min),
244         (op == HistogramSamples::ADD) ? count : -count);
245   }
246   return true;
247 }
248 
GetSampleCountStorage(Sample value)249 Count* PersistentSampleMap::GetSampleCountStorage(Sample value) {
250   // If |value| is already in the map, just return that.
251   auto it = sample_counts_.find(value);
252   if (it != sample_counts_.end())
253     return it->second;
254 
255   // Import any new samples from persistent memory looking for the value.
256   return ImportSamples(/*until_value=*/value);
257 }
258 
GetOrCreateSampleCountStorage(Sample value)259 Count* PersistentSampleMap::GetOrCreateSampleCountStorage(Sample value) {
260   // Get any existing count storage.
261   Count* count_pointer = GetSampleCountStorage(value);
262   if (count_pointer)
263     return count_pointer;
264 
265   // Create a new record in persistent memory for the value. |records_| will
266   // have been initialized by the GetSampleCountStorage() call above.
267   CHECK(records_);
268   PersistentMemoryAllocator::Reference ref = records_->CreateNew(value);
269   if (!ref) {
270     // If a new record could not be created then the underlying allocator is
271     // full or corrupt. Instead, allocate the counter from the heap. This
272     // sample will not be persistent, will not be shared, and will leak...
273     // but it's better than crashing.
274     count_pointer = new Count(0);
275     sample_counts_[value] = count_pointer;
276     return count_pointer;
277   }
278 
279   // A race condition between two independent processes (i.e. two independent
280   // histogram objects sharing the same sample data) could cause two of the
281   // above records to be created. The allocator, however, forces a strict
282   // ordering on iterable objects so use the import method to actually add the
283   // just-created record. This ensures that all PersistentSampleMap objects
284   // will always use the same record, whichever was first made iterable.
285   // Thread-safety within a process where multiple threads use the same
286   // histogram object is delegated to the controlling histogram object which,
287   // for sparse histograms, is a lock object.
288   count_pointer = ImportSamples(/*until_value=*/value);
289   DCHECK(count_pointer);
290   return count_pointer;
291 }
292 
GetRecords()293 PersistentSampleMapRecords* PersistentSampleMap::GetRecords() {
294   // The |records_| pointer is lazily fetched from the |allocator_| only on
295   // first use. Sometimes duplicate histograms are created by race conditions
296   // and if both were to grab the records object, there would be a conflict.
297   // Use of a histogram, and thus a call to this method, won't occur until
298   // after the histogram has been de-dup'd.
299   if (!records_) {
300     records_ = allocator_->CreateSampleMapRecords(id());
301   }
302   return records_.get();
303 }
304 
ImportSamples(std::optional<Sample> until_value)305 Count* PersistentSampleMap::ImportSamples(std::optional<Sample> until_value) {
306   std::vector<PersistentMemoryAllocator::Reference> refs;
307   PersistentSampleMapRecords* records = GetRecords();
308   while (!(refs = records->GetNextRecords(until_value)).empty()) {
309     // GetNextRecords() returns a list of new unseen records belonging to this
310     // map. Iterate through them all and store them internally. Note that if
311     // |until_value| was found, it will be the last element in |refs|.
312     for (auto ref : refs) {
313       SampleRecord* record = records->GetAsObject<SampleRecord>(ref);
314       if (!record) {
315         continue;
316       }
317 
318       DCHECK_EQ(id(), record->id);
319 
320       // Check if the record's value is already known.
321       if (!Contains(sample_counts_, record->value)) {
322         // No: Add it to map of known values.
323         sample_counts_[record->value] = &record->count;
324       } else {
325         // Yes: Ignore it; it's a duplicate caused by a race condition -- see
326         // code & comment in GetOrCreateSampleCountStorage() for details.
327         // Check that nothing ever operated on the duplicate record.
328         DCHECK_EQ(0, record->count);
329       }
330 
331       // Check if it's the value being searched for and, if so, stop here.
332       // Because race conditions can cause multiple records for a single value,
333       // be sure to return the first one found.
334       if (until_value.has_value() && record->value == until_value.value()) {
335         // Ensure that this was the last value in |refs|.
336         CHECK_EQ(refs.back(), ref);
337 
338         return &record->count;
339       }
340     }
341   }
342 
343   return nullptr;
344 }
345 
346 }  // namespace base
347