You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

secure.h 2.0KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // Copyright (c) 2009-2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2013 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. #ifndef BITCOIN_SUPPORT_ALLOCATORS_SECURE_H
  6. #define BITCOIN_SUPPORT_ALLOCATORS_SECURE_H
  7. #include "support/pagelocker.h"
  8. #include <string>
  9. //
  10. // Allocator that locks its contents from being paged
  11. // out of memory and clears its contents before deletion.
  12. //
  13. template <typename T>
  14. struct secure_allocator : public std::allocator<T> {
  15. // MSVC8 default copy constructor is broken
  16. typedef std::allocator<T> base;
  17. typedef typename base::size_type size_type;
  18. typedef typename base::difference_type difference_type;
  19. typedef typename base::pointer pointer;
  20. typedef typename base::const_pointer const_pointer;
  21. typedef typename base::reference reference;
  22. typedef typename base::const_reference const_reference;
  23. typedef typename base::value_type value_type;
  24. secure_allocator() throw() {}
  25. secure_allocator(const secure_allocator& a) throw() : base(a) {}
  26. template <typename U>
  27. secure_allocator(const secure_allocator<U>& a) throw() : base(a)
  28. {
  29. }
  30. ~secure_allocator() throw() {}
  31. template <typename _Other>
  32. struct rebind {
  33. typedef secure_allocator<_Other> other;
  34. };
  35. T* allocate(std::size_t n, const void* hint = 0)
  36. {
  37. T* p;
  38. p = std::allocator<T>::allocate(n, hint);
  39. if (p != NULL)
  40. LockedPageManager::Instance().LockRange(p, sizeof(T) * n);
  41. return p;
  42. }
  43. void deallocate(T* p, std::size_t n)
  44. {
  45. if (p != NULL) {
  46. memory_cleanse(p, sizeof(T) * n);
  47. LockedPageManager::Instance().UnlockRange(p, sizeof(T) * n);
  48. }
  49. std::allocator<T>::deallocate(p, n);
  50. }
  51. };
  52. // This is exactly like std::string, but with a custom allocator.
  53. typedef std::basic_string<char, std::char_traits<char>, secure_allocator<char> > SecureString;
  54. #endif // BITCOIN_SUPPORT_ALLOCATORS_SECURE_H