Branch data Line data Source code
# 1 : : // Copyright (c) 2009-2010 Satoshi Nakamoto # 2 : : // Copyright (c) 2009-2021 The Bitcoin Core developers # 3 : : // Distributed under the MIT software license, see the accompanying # 4 : : // file COPYING or http://www.opensource.org/licenses/mit-license.php. # 5 : : # 6 : : #ifndef BITCOIN_SUPPORT_ALLOCATORS_SECURE_H # 7 : : #define BITCOIN_SUPPORT_ALLOCATORS_SECURE_H # 8 : : # 9 : : #include <support/lockedpool.h> # 10 : : #include <support/cleanse.h> # 11 : : # 12 : : #include <memory> # 13 : : #include <string> # 14 : : # 15 : : // # 16 : : // Allocator that locks its contents from being paged # 17 : : // out of memory and clears its contents before deletion. # 18 : : // # 19 : : template <typename T> # 20 : : struct secure_allocator : public std::allocator<T> { # 21 : : using base = std::allocator<T>; # 22 : : using traits = std::allocator_traits<base>; # 23 : : using size_type = typename traits::size_type; # 24 : : using difference_type = typename traits::difference_type; # 25 : : using pointer = typename traits::pointer; # 26 : : using const_pointer = typename traits::const_pointer; # 27 : : using value_type = typename traits::value_type; # 28 : 1618559 : secure_allocator() noexcept {} # 29 : 214295 : secure_allocator(const secure_allocator& a) noexcept : base(a) {} # 30 : : template <typename U> # 31 : : secure_allocator(const secure_allocator<U>& a) noexcept : base(a) # 32 : : { # 33 : : } # 34 : 1832070 : ~secure_allocator() noexcept {} # 35 : : template <typename _Other> # 36 : : struct rebind { # 37 : : typedef secure_allocator<_Other> other; # 38 : : }; # 39 : : # 40 : : T* allocate(std::size_t n, const void* hint = 0) # 41 : 1718473 : { # 42 : 1718473 : T* allocation = static_cast<T*>(LockedPoolManager::Instance().alloc(sizeof(T) * n)); # 43 [ - + ][ - + ]: 1718473 : if (!allocation) { # [ - + ] # 44 : 0 : throw std::bad_alloc(); # 45 : 0 : } # 46 : 1718473 : return allocation; # 47 : 1718473 : } # 48 : : # 49 : : void deallocate(T* p, std::size_t n) # 50 : 1717645 : { # 51 [ + - ][ + - ]: 1717645 : if (p != nullptr) { # [ + - ] # 52 : 1717645 : memory_cleanse(p, sizeof(T) * n); # 53 : 1717645 : } # 54 : 1717645 : LockedPoolManager::Instance().free(p); # 55 : 1717645 : } # 56 : : }; # 57 : : # 58 : : // This is exactly like std::string, but with a custom allocator. # 59 : : typedef std::basic_string<char, std::char_traits<char>, secure_allocator<char> > SecureString; # 60 : : # 61 : : #endif // BITCOIN_SUPPORT_ALLOCATORS_SECURE_H