2015-01-22 15:02:44 -05:00
|
|
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
|
2021-12-30 19:36:57 +02:00
|
|
|
// Copyright (c) 2009-2021 The Bitcoin Core developers
|
2015-01-22 15:02:44 -05:00
|
|
|
// Distributed under the MIT software license, see the accompanying
|
|
|
|
|
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
|
|
|
|
|
2015-03-21 18:15:31 +01:00
|
|
|
#ifndef BITCOIN_SUPPORT_ALLOCATORS_SECURE_H
|
|
|
|
|
#define BITCOIN_SUPPORT_ALLOCATORS_SECURE_H
|
2015-01-22 15:02:44 -05:00
|
|
|
|
2017-11-10 13:57:53 +13:00
|
|
|
#include <support/lockedpool.h>
|
|
|
|
|
#include <support/cleanse.h>
|
2015-01-22 15:02:44 -05:00
|
|
|
|
2021-10-04 22:49:21 -04:00
|
|
|
#include <memory>
|
2015-01-22 15:02:44 -05:00
|
|
|
#include <string>
|
|
|
|
|
|
|
|
|
|
//
|
|
|
|
|
// Allocator that locks its contents from being paged
|
|
|
|
|
// out of memory and clears its contents before deletion.
|
|
|
|
|
//
|
|
|
|
|
template <typename T>
|
|
|
|
|
struct secure_allocator : public std::allocator<T> {
|
2021-10-04 22:49:21 -04:00
|
|
|
using base = std::allocator<T>;
|
|
|
|
|
using traits = std::allocator_traits<base>;
|
|
|
|
|
using size_type = typename traits::size_type;
|
|
|
|
|
using difference_type = typename traits::difference_type;
|
|
|
|
|
using pointer = typename traits::pointer;
|
|
|
|
|
using const_pointer = typename traits::const_pointer;
|
|
|
|
|
using value_type = typename traits::value_type;
|
2017-07-31 19:44:01 +02:00
|
|
|
secure_allocator() noexcept {}
|
|
|
|
|
secure_allocator(const secure_allocator& a) noexcept : base(a) {}
|
2015-01-22 15:02:44 -05:00
|
|
|
template <typename U>
|
2017-07-31 19:44:01 +02:00
|
|
|
secure_allocator(const secure_allocator<U>& a) noexcept : base(a)
|
2015-01-22 15:02:44 -05:00
|
|
|
{
|
|
|
|
|
}
|
2017-07-31 19:44:01 +02:00
|
|
|
~secure_allocator() noexcept {}
|
2015-01-22 15:02:44 -05:00
|
|
|
template <typename _Other>
|
|
|
|
|
struct rebind {
|
|
|
|
|
typedef secure_allocator<_Other> other;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
T* allocate(std::size_t n, const void* hint = 0)
|
|
|
|
|
{
|
2019-01-06 16:38:32 +01:00
|
|
|
T* allocation = static_cast<T*>(LockedPoolManager::Instance().alloc(sizeof(T) * n));
|
|
|
|
|
if (!allocation) {
|
|
|
|
|
throw std::bad_alloc();
|
|
|
|
|
}
|
|
|
|
|
return allocation;
|
2015-01-22 15:02:44 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
void deallocate(T* p, std::size_t n)
|
|
|
|
|
{
|
2017-08-07 07:36:37 +02:00
|
|
|
if (p != nullptr) {
|
2015-01-22 15:02:44 -05:00
|
|
|
memory_cleanse(p, sizeof(T) * n);
|
|
|
|
|
}
|
2016-09-18 09:55:14 +02:00
|
|
|
LockedPoolManager::Instance().free(p);
|
2015-01-22 15:02:44 -05:00
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
// This is exactly like std::string, but with a custom allocator.
|
|
|
|
|
typedef std::basic_string<char, std::char_traits<char>, secure_allocator<char> > SecureString;
|
|
|
|
|
|
2015-03-21 18:15:31 +01:00
|
|
|
#endif // BITCOIN_SUPPORT_ALLOCATORS_SECURE_H
|