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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
|
/*
* (C) 2018,2019 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include <botan/internal/mem_pool.h>
#include <botan/mem_ops.h>
#include <algorithm>
#if defined(BOTAN_MEM_POOL_USE_MMU_PROTECTIONS)
#include <botan/internal/os_utils.h>
#endif
namespace Botan {
/*
* Memory pool theory of operation
*
* This allocator is not useful for general purpose but works well within the
* context of allocating cryptographic keys. It makes several assumptions which
* don't work for implementing malloc but simplify and speed up the implementation:
*
* - There is some set of pages, which cannot be expanded later. These are pages
* which were allocated, mlocked and passed to the Memory_Pool constructor.
*
* - The allocator is allowed to return null anytime it feels like not servicing
* a request, in which case the request will be sent to calloc instead. In
* particular, requests which are too small or too large are rejected.
*
* - Most allocations are powers of 2, the remainder are usually a multiple of 8
*
* - Free requests include the size of the allocation, so there is no need to
* track this within the pool.
*
* - Alignment is important to the caller. For this allocator, any allocation of
* size N is aligned evenly at N bytes.
*
* Initially each page is in the free page list. Each page is used for just one
* size of allocation, with requests bucketed into a small number of common
* sizes. If the allocation would be too big or too small it is rejected by the pool.
*
* The free list is maintained by a bitmap, one per page/Bucket. Since each
* Bucket only maintains objects of a single size, each bit set or clear
* indicates the status of one object.
*
* An allocation walks the list of buckets and asks each in turn if there is
* space. If a Bucket does not have any space, it sets a boolean flag m_is_full
* so that it does not need to rescan when asked again. The flag is cleared on
* first free from that bucket. If no bucket has space, but there are some free
* pages left, a free page is claimed as a new Bucket for that size. In this case
* it is pushed to the front of the list so it is first in line to service new
* requests.
*
* A deallocation also walks the list of buckets for the size and asks each
* Bucket in turn if it recognizes the pointer. When a Bucket becomes empty as a
* result of a deallocation, it is recycled back into the free pool. When this
* happens, the Buckets page goes to the end of the free list. All pages on the
* free list are marked in the MMU as noaccess, so anything touching them will
* immediately crash. They are only marked R/W once placed into a new bucket.
* Making the free list FIFO maximizes the time between the last free of a bucket
* and that page being writable again, maximizing chances of crashing after a
* use-after-free.
*
* Future work
* -------------
*
* The allocator is protected by a global lock. It would be good to break this
* up, since almost all of the work can actually be done in parallel especially
* when allocating objects of different sizes (which can't possibly share a
* bucket).
*
* It may be worthwhile to optimize deallocation by storing the Buckets in order
* (by pointer value) which would allow binary search to find the owning bucket.
*
* A useful addition would be to randomize the allocations. Memory_Pool would be
* changed to receive also a RandomNumberGenerator& object (presumably the system
* RNG, or maybe a ChaCha_RNG seeded with system RNG). Then the bucket to use and
* the offset within the bucket would be chosen randomly, instead of using first fit.
*
* Right now we don't make any provision for threading, so if two threads both
* allocate 32 byte values one after the other, the two allocations will likely
* share a cache line. Ensuring that distinct threads will (tend to) use distinct
* buckets would reduce this.
*
* Supporting a realloc-style API may be useful.
*/
namespace {
size_t choose_bucket(size_t n)
{
const size_t MINIMUM_ALLOCATION = 16;
const size_t MAXIMUM_ALLOCATION = 256;
if(n < MINIMUM_ALLOCATION || n > MAXIMUM_ALLOCATION)
return 0;
// Need to tune these
const size_t buckets[] = {
16, 24, 32, 48, 64, 80, 96, 112, 128, 160, 192, 256, 0,
};
for(size_t i = 0; buckets[i]; ++i)
{
if(n <= buckets[i])
{
return buckets[i];
}
}
return 0;
}
inline bool ptr_in_pool(const void* pool_ptr, size_t poolsize,
const void* buf_ptr, size_t bufsize)
{
const uintptr_t pool = reinterpret_cast<uintptr_t>(pool_ptr);
const uintptr_t buf = reinterpret_cast<uintptr_t>(buf_ptr);
return (buf >= pool) && (buf + bufsize <= pool + poolsize);
}
// return index of first set bit
template<typename T>
size_t find_set_bit(T b)
{
size_t s = 8*sizeof(T) / 2;
size_t bit = 0;
// In this context we don't need to be const-time
while(s > 0)
{
const T mask = (static_cast<T>(1) << s) - 1;
if((b & mask) == 0)
{
bit += s;
b >>= s;
}
s /= 2;
}
return bit;
}
class BitMap final
{
public:
BitMap(size_t bits) : m_len(bits)
{
m_bits.resize((bits + BITMASK_BITS - 1) / BITMASK_BITS);
m_main_mask = static_cast<bitmask_type>(~0);
m_last_mask = m_main_mask;
if(bits % BITMASK_BITS != 0)
m_last_mask = (static_cast<bitmask_type>(1) << (bits % BITMASK_BITS)) - 1;
}
bool find_free(size_t* bit);
void free(size_t bit)
{
BOTAN_ASSERT_NOMSG(bit <= m_len);
const size_t w = bit / BITMASK_BITS;
BOTAN_ASSERT_NOMSG(w < m_bits.size());
const bitmask_type mask = static_cast<bitmask_type>(1) << (bit % BITMASK_BITS);
m_bits[w] = m_bits[w] & (~mask);
}
bool empty() const
{
for(auto bitset : m_bits)
{
if(bitset != 0)
{
return false;
}
}
return true;
}
private:
#if defined(BOTAN_ENABLE_DEBUG_ASSERTS)
typedef uint8_t bitmask_type;
enum { BITMASK_BITS = 8 };
#else
typedef word bitmask_type;
enum { BITMASK_BITS = BOTAN_MP_WORD_BITS };
#endif
size_t m_len;
bitmask_type m_main_mask;
bitmask_type m_last_mask;
std::vector<bitmask_type> m_bits;
};
bool BitMap::find_free(size_t* bit)
{
for(size_t i = 0; i != m_bits.size(); ++i)
{
const bitmask_type mask = (i == m_bits.size() - 1) ? m_last_mask : m_main_mask;
if((m_bits[i] & mask) != mask)
{
const size_t free_bit = find_set_bit(~m_bits[i]);
const bitmask_type bmask = static_cast<bitmask_type>(1) << (free_bit % BITMASK_BITS);
BOTAN_ASSERT_NOMSG((m_bits[i] & bmask) == 0);
m_bits[i] |= bmask;
*bit = BITMASK_BITS*i + free_bit;
return true;
}
}
return false;
}
}
class Bucket final
{
public:
Bucket(uint8_t* mem, size_t mem_size, size_t item_size) :
m_item_size(item_size),
m_page_size(mem_size),
m_range(mem),
m_bitmap(mem_size / item_size),
m_is_full(false)
{
}
uint8_t* alloc()
{
if(m_is_full)
{
// I know I am full
return nullptr;
}
size_t offset;
if(!m_bitmap.find_free(&offset))
{
// I just found out I am full
m_is_full = true;
return nullptr;
}
BOTAN_ASSERT(offset * m_item_size < m_page_size, "Offset is in range");
return m_range + m_item_size*offset;
}
bool free(void* p)
{
if(!in_this_bucket(p))
return false;
/*
Zero also any trailing bytes, which should not have been written to,
but maybe the user was bad and wrote past the end.
*/
std::memset(p, 0, m_item_size);
const size_t offset = (reinterpret_cast<uintptr_t>(p) - reinterpret_cast<uintptr_t>(m_range)) / m_item_size;
m_bitmap.free(offset);
m_is_full = false;
return true;
}
bool in_this_bucket(void* p) const
{
return ptr_in_pool(m_range, m_page_size, p, m_item_size);
}
bool empty() const
{
return m_bitmap.empty();
}
uint8_t* ptr() const
{
return m_range;
}
private:
size_t m_item_size;
size_t m_page_size;
uint8_t* m_range;
BitMap m_bitmap;
bool m_is_full;
};
Memory_Pool::Memory_Pool(const std::vector<void*>& pages, size_t page_size) :
m_page_size(page_size)
{
m_min_page_ptr = ~static_cast<uintptr_t>(0);
m_max_page_ptr = 0;
for(auto page : pages)
{
const uintptr_t p = reinterpret_cast<uintptr_t>(page);
m_min_page_ptr = std::min(p, m_min_page_ptr);
m_max_page_ptr = std::max(p, m_max_page_ptr);
clear_bytes(page, m_page_size);
#if defined(BOTAN_MEM_POOL_USE_MMU_PROTECTIONS)
OS::page_prohibit_access(pages[i]);
#endif
m_free_pages.push_back(static_cast<uint8_t*>(page));
}
/*
Right now this points to the start of the last page, adjust it to instead
point to the first byte of the following page
*/
m_max_page_ptr += page_size;
}
Memory_Pool::~Memory_Pool()
{
#if defined(BOTAN_MEM_POOL_USE_MMU_PROTECTIONS)
for(size_t i = 0; i != m_free_pages.size(); ++i)
{
OS::page_allow_access(m_free_pages[i]);
}
#endif
}
void* Memory_Pool::allocate(size_t n)
{
if(n > m_page_size)
return nullptr;
const size_t n_bucket = choose_bucket(n);
if(n_bucket > 0)
{
lock_guard_type<mutex_type> lock(m_mutex);
std::deque<Bucket>& buckets = m_buckets_for[n_bucket];
/*
It would be optimal to pick the bucket with the most usage,
since a bucket with say 1 item allocated out of it has a high
chance of becoming later freed and then the whole page can be
recycled.
*/
for(auto& bucket : buckets)
{
if(uint8_t* p = bucket.alloc())
return p;
// If the bucket is full, maybe move it to the end of the list?
// Otoh bucket search should be very fast
}
if(!m_free_pages.empty())
{
uint8_t* ptr = m_free_pages[0];
m_free_pages.pop_front();
#if defined(BOTAN_MEM_POOL_USE_MMU_PROTECTIONS)
OS::page_allow_access(ptr);
#endif
buckets.push_front(Bucket(ptr, m_page_size, n_bucket));
void* p = buckets[0].alloc();
BOTAN_ASSERT_NOMSG(p != nullptr);
return p;
}
}
// out of room
return nullptr;
}
bool Memory_Pool::deallocate(void* p, size_t len) noexcept
{
// Do a fast range check first, before taking the lock
const uintptr_t p_val = reinterpret_cast<uintptr_t>(p);
if(p_val < m_min_page_ptr || p_val > m_max_page_ptr)
return false;
const size_t n_bucket = choose_bucket(len);
if(n_bucket != 0)
{
try
{
lock_guard_type<mutex_type> lock(m_mutex);
std::deque<Bucket>& buckets = m_buckets_for[n_bucket];
for(size_t i = 0; i != buckets.size(); ++i)
{
Bucket& bucket = buckets[i];
if(bucket.free(p))
{
if(bucket.empty())
{
#if defined(BOTAN_MEM_POOL_USE_MMU_PROTECTIONS)
OS::page_prohibit_access(bucket.ptr());
#endif
m_free_pages.push_back(bucket.ptr());
if(i != buckets.size() - 1)
std::swap(buckets.back(), buckets[i]);
buckets.pop_back();
}
return true;
}
}
}
catch(...)
{
/*
* The only exception throws that can occur in the above code are from
* either the STL or BOTAN_ASSERT failures. In either case, such an
* error indicates a logic error or data corruption in the memory
* allocator such that it is no longer safe to continue executing.
*
* Since this function is noexcept, simply letting the exception escape
* is sufficient for terminate to be called. However in this scenario
* it is implementation defined if any stack unwinding is performed.
* Since stack unwinding could cause further memory deallocations this
* could result in further corruption in this allocator state. To prevent
* this, call terminate directly.
*/
std::terminate();
}
}
return false;
}
}
|