File: random_eviction_quarantine.cc

package info (click to toggle)
chromium 139.0.7258.127-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,122,156 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (164 lines) | stat: -rw-r--r-- 5,837 bytes parent folder | download | duplicates (7)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
// Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/gwp_asan/client/lightweight_detector/random_eviction_quarantine.h"

#include "base/check_is_test.h"
#include "components/gwp_asan/client/thread_local_random_bit_generator.h"

namespace gwp_asan::internal::lud {

RandomEvictionQuarantineBase::RandomEvictionQuarantineBase(
    size_t max_allocation_count,
    size_t max_total_size,
    size_t total_size_high_water_mark,
    size_t total_size_low_water_mark,
    size_t eviction_chunk_size,
    size_t eviction_task_interval_ms)
    : max_allocation_count_(max_allocation_count),
      max_total_size_(max_total_size),
      total_size_high_water_mark_(total_size_high_water_mark),
      total_size_low_water_mark_(total_size_low_water_mark),
      eviction_chunk_size_(eviction_chunk_size),
      eviction_task_interval_(base::Milliseconds(eviction_task_interval_ms)),
      allocations_(max_allocation_count) {
  DCHECK_GT(total_size_low_water_mark_, 0u);
  DCHECK_GT(total_size_high_water_mark_, total_size_low_water_mark_);
  DCHECK_GT(max_total_size_, total_size_high_water_mark_);
  DCHECK_GT(max_allocation_count_, 0u);
  DCHECK_GT(eviction_chunk_size_, 0u);

  // It's safe to pass `this` and `timer_` as `Unretained()` because this
  // class's instances aren't destructible in production code, as explained in
  // the `~RandomEvictionQuarantine()` comment.
  task_runner_->PostTask(
      FROM_HERE,
      base::BindOnce(
          // Can't bind `Start` directly because it's overloaded.
          [](base::RepeatingTimer* timer, base::TimeDelta interval,
             base::RepeatingClosure closure) {
            timer->Start(FROM_HERE, interval, std::move(closure));
          },
          base::Unretained(&timer_), eviction_task_interval_,
          base::BindRepeating(&RandomEvictionQuarantineBase::PeriodicTrim,
                              base::Unretained(this))));
}

RandomEvictionQuarantineBase::~RandomEvictionQuarantineBase() = default;

bool RandomEvictionQuarantineBase::Add(const AllocationInfo& new_allocation) {
  if (new_allocation.size == 0 || new_allocation.size > kMaxAllocationSize)
      [[unlikely]] {
    return false;
  }

  // Record the deallocation event before quarantine to avoid racing with
  // trimming.
  RecordAndZap(new_allocation.address, new_allocation.size);

  // Pick an index to potentially replace before we acquire the lock.
  std::uniform_int_distribution<size_t> distribution(0,
                                                     max_allocation_count_ - 1);
  ThreadLocalRandomBitGenerator generator;
  size_t idx = distribution(generator);

  AllocationInfo evicted_allocation;
  bool update_succeeded = false;
  {
    base::AutoLock lock(lock_);

    AllocationInfo& entry = allocations_[idx];
    size_t tentative_total_size = total_size_.load(std::memory_order_relaxed) -
                                  entry.size + new_allocation.size;
    if (tentative_total_size <= max_total_size_) {
      total_size_.store(tentative_total_size, std::memory_order_relaxed);
      evicted_allocation = entry;
      entry = new_allocation;
      update_succeeded = true;
    }
  }

  if (evicted_allocation.address) {
    FinishFree(evicted_allocation);
  }

  return update_succeeded;
}

void RandomEvictionQuarantineBase::PeriodicTrim() {
  if (total_size_.load(std::memory_order_relaxed) <=
      total_size_high_water_mark_) {
    return;
  }

  std::vector<AllocationInfo> allocations_to_evict;
  allocations_to_evict.reserve(eviction_chunk_size_);

  std::uniform_int_distribution<size_t> distribution(0,
                                                     max_allocation_count_ - 1);
  ThreadLocalRandomBitGenerator generator;
  size_t evict_start_idx = distribution(generator);
  {
    base::AutoLock lock(lock_);

    // Trim even if the `total_size_` became smaller than the high watermark
    // while we were acquiring the lock. Otherwise, we'll have to trim soon
    // anyway.
    size_t new_total_size = total_size_.load(std::memory_order_relaxed);

    for (size_t i = 0; i < eviction_chunk_size_; ++i) {
      if (new_total_size <= total_size_low_water_mark_) {
        break;
      }

      size_t idx = (evict_start_idx + i) % max_allocation_count_;
      AllocationInfo& entry = allocations_[idx];

      if (!entry.address) {
        continue;
      }

      new_total_size -= entry.size;

      allocations_to_evict.push_back(entry);
      entry = AllocationInfo();
    }

    total_size_.store(new_total_size, std::memory_order_relaxed);
  }

  // TODO(glazunov): Since these allocations haven't been used for a while,
  // their memory is probably not in the CPU cache, so it might not be best to
  // keep them in the thread cache. Consider exposing the option to bypass the
  // thread cache in PartitionAlloc.
  for (auto allocation : allocations_to_evict) {
    FinishFree(allocation);
  }
}

bool RandomEvictionQuarantineBase::HasAllocationForTesting(
    void* requested_ptr) const {
  base::AutoLock lock(lock_);
  return std::any_of(
      allocations_.begin(), allocations_.end(),
      [&](const auto& entry) { return entry.address == requested_ptr; });
}

// Since the allocator hooks cannot be uninstalled, and they access an
// instance of this class, it's unsafe to ever destroy it outside unit tests.
RandomEvictionQuarantine::~RandomEvictionQuarantine() {
  CHECK_IS_TEST();
}

void RandomEvictionQuarantine::FinishFree(const AllocationInfo& info) {
  gwp_asan::internal::lud::FinishFree(info);
}

void RandomEvictionQuarantine::RecordAndZap(void* ptr, size_t size) {
  PoisonMetadataRecorder::Get()->RecordAndZap(ptr, size);
}

template class SharedState<RandomEvictionQuarantine>;

}  // namespace gwp_asan::internal::lud