about summary refs log tree commit diff homepage
path: root/include/klee/KDAlloc/allocator.h
blob: c4461b7936ee6a9e12bce75558335cd28589dbce (plain) (blame)
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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
//===-- allocator.h ---------------------------------------------*- C++ -*-===//
//
//                     The KLEE Symbolic Virtual Machine
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#ifndef KDALLOC_ALLOCATOR_H
#define KDALLOC_ALLOCATOR_H

#include "define.h"
#include "location_info.h"
#include "mapping.h"
#include "suballocators/loh.h"
#include "suballocators/slot_allocator.h"
#include "tagged_logger.h"

#include "klee/ADT/Bits.h"
#include "klee/ADT/Ref.h"

#include <array>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <limits>
#include <ostream>
#include <type_traits>

namespace klee::kdalloc {
/// Wraps a mapping and delegates allocation to one of 8 sized-bin slot
/// allocators (size < 4096) or a large object allocator (size >= 4096).
class Allocator final : public TaggedLogger<Allocator> {
public:
  class Control final {
    friend class Allocator;
    friend class AllocatorFactory;

    static constexpr const std::uint32_t unlimitedQuarantine =
        static_cast<std::uint32_t>(-1);

    /// @todo This should really be a data member `static constexpr const
    /// std::array meta = { ... }`.
    static inline const std::array<std::size_t, 8> &getMeta() noexcept {
      static const std::array<std::size_t, 8> meta = {
          1u,    // bool
          4u,    // int
          8u,    // pointer size
          16u,   // double
          32u,   // compound types #1
          64u,   // compound types #2
          256u,  // compound types #3
          2048u, // reasonable buffers
      };
      return meta;
    }

    [[nodiscard]] static inline int
    convertSizeToBinIndex(std::size_t const size) noexcept {
      for (std::size_t i = 0; i < getMeta().size(); ++i) {
        if (getMeta()[i] >= size) {
          return i;
        }
      }
      return getMeta().size();
    }

  public:
    mutable class klee::ReferenceCounter _refCount;

  private:
    Mapping mapping;
    std::array<suballocators::SlotAllocator::Control,
               std::tuple_size<std::decay_t<decltype(getMeta())>>::value>
        sizedBins;
    suballocators::LargeObjectAllocator::Control largeObjectBin;

  public:
    Control() = delete;
    Control(Control const &) = delete;
    Control &operator=(Control const &) = delete;
    Control(Control &&) = delete;
    Control &operator=(Control &&) = delete;

  private:
    Control(Mapping &&mapping) : mapping(std::move(mapping)) {}
  };

  static constexpr const auto unlimitedQuarantine =
      Control::unlimitedQuarantine;

private:
  klee::ref<Control> control;

  std::array<suballocators::SlotAllocator,
             std::tuple_size<std::decay_t<decltype(Control::getMeta())>>::value>
      sizedBins;
  suballocators::LargeObjectAllocator largeObjectBin;

public:
  std::ostream &logTag(std::ostream &out) const noexcept {
    return out << "[alloc] ";
  }

  Allocator() = default;
  Allocator(Allocator const &rhs) = default;
  Allocator &operator=(Allocator const &rhs) = default;
  Allocator(Allocator &&) = default;
  Allocator &operator=(Allocator &&) = default;

  Allocator(klee::ref<Control> control) : control(std::move(control)) {}

  explicit operator bool() const noexcept { return !control.isNull(); }

  auto const &getSizedBinInfo() const noexcept { return Control::getMeta(); }

  [[nodiscard]] void *allocate(std::size_t size) {
    assert(*this && "Invalid allocator");

    auto const bin = Control::convertSizeToBinIndex(size);
    traceLine("Allocating ", size, " bytes in bin ", bin);

    void *result = nullptr;
    if (bin < static_cast<int>(sizedBins.size())) {
      result = sizedBins[bin].allocate(control->sizedBins[bin]);
    } else {
      result = largeObjectBin.allocate(control->largeObjectBin, size);
    }
    traceLine("Allocated ", result);
    return result;
  }

  void free(void *ptr, std::size_t size) {
    assert(*this && "Invalid allocator");
    assert(ptr && "Freeing nullptrs is not supported"); // we are not ::free!

    auto const bin = Control::convertSizeToBinIndex(size);
    traceLine("Freeing ", ptr, " of size ", size, " in bin ", bin);

    if (bin < static_cast<int>(sizedBins.size())) {
      return sizedBins[bin].deallocate(control->sizedBins[bin], ptr);
    } else {
      return largeObjectBin.deallocate(control->largeObjectBin, ptr, size);
    }
  }

  LocationInfo location_info(void const *const ptr,
                             std::size_t const size) const noexcept {
    assert(*this && "Invalid allocator");

    if (!ptr || reinterpret_cast<std::uintptr_t>(ptr) < 4096) {
      return LocationInfo::LI_NullPage;
    }

    // the following is technically UB if `ptr` does not actually point inside
    // the mapping at all
    for (std::size_t i = 0; i < Allocator::Control::getMeta().size(); ++i) {
      if (control->sizedBins[i].mapping_begin() <= ptr &&
          ptr < control->sizedBins[i].mapping_end()) {
        if (reinterpret_cast<char const *>(ptr) + size <=
            control->sizedBins[i].mapping_end()) {
          return sizedBins[i].getLocationInfo(control->sizedBins[i], ptr, size);
        } else {
          return LocationInfo::LI_SpansSuballocators;
        }
      }
    }
    if (control->largeObjectBin.mapping_begin() <= ptr &&
        ptr < control->largeObjectBin.mapping_end()) {
      if (reinterpret_cast<char const *>(ptr) + size <=
          control->largeObjectBin.mapping_end()) {
        return largeObjectBin.getLocationInfo(control->largeObjectBin, ptr,
                                              size);
      } else {
        // the loh is the suballocator using the largest addresses, therefore
        // its mapping is not followed by that of another suballocator, but
        // rather the end of the mapping
        return LocationInfo::LI_NonNullOutsideMapping;
      }
    }

    return LocationInfo::LI_NonNullOutsideMapping;
  }
};

class AllocatorFactory {
public:
  static constexpr const auto unlimitedQuarantine =
      Allocator::Control::unlimitedQuarantine;

private:
  klee::ref<Allocator::Control> control;

public:
  AllocatorFactory() = default;

  AllocatorFactory(std::size_t const size, std::uint32_t const quarantineSize)
      : AllocatorFactory(Mapping{0, size}, quarantineSize) {}

  AllocatorFactory(std::uintptr_t const address, std::size_t const size,
                   std::uint32_t const quarantineSize)
      : AllocatorFactory(Mapping{address, size}, quarantineSize) {}

  AllocatorFactory(Mapping &&mapping, std::uint32_t const quarantineSize) {
    assert(mapping && "Invalid mapping");
    assert(mapping.getSize() >
               Allocator::Control::getMeta().size() * 4096 + 3 * 4096 &&
           "Mapping is *far* to small");

    control = new Allocator::Control(std::move(mapping));
    auto const binSize =
        static_cast<std::size_t>(1)
        << (std::numeric_limits<std::size_t>::digits - 1 -
            countLeadingZeroes(control->mapping.getSize() /
                               (Allocator::Control::getMeta().size() + 1)));
    char *const base = static_cast<char *>(control->mapping.getBaseAddress());
    std::size_t totalSize = 0;
    for (std::size_t i = 0; i < Allocator::Control::getMeta().size(); ++i) {
      control->sizedBins[i].initialize(
          base + totalSize, binSize, Allocator::Control::getMeta()[i],
          quarantineSize == unlimitedQuarantine,
          quarantineSize == unlimitedQuarantine ? 0 : quarantineSize);

      totalSize += binSize;
      assert(totalSize <= control->mapping.getSize() && "Mapping too small");
    }

    auto largeObjectBinSize = control->mapping.getSize() - totalSize;
    assert(largeObjectBinSize > 0);
    control->largeObjectBin.initialize(
        base + totalSize, largeObjectBinSize,
        quarantineSize == unlimitedQuarantine,
        quarantineSize == unlimitedQuarantine ? 0 : quarantineSize);
  }

  explicit operator bool() const noexcept { return !control.isNull(); }

  Mapping &getMapping() noexcept {
    assert(!!*this && "Cannot get mapping of uninitialized factory.");
    return control->mapping;
  }

  Mapping const &getMapping() const noexcept {
    assert(!!*this && "Cannot get mapping of uninitialized factory.");
    return control->mapping;
  }

  Allocator makeAllocator() const {
    assert(!!*this &&
           "Can only create an allocator from an initialized factory.");

    return Allocator{control};
  }

  explicit operator Allocator() && {
    assert(!!*this &&
           "Can only create an allocator from an initialized factory.");

    return Allocator{std::move(control)};
  }
};
} // namespace klee::kdalloc

#endif