diff options
author | Anthony Towns <aj@erisian.com.au> | 2023-09-22 09:40:45 -0400 |
---|---|---|
committer | Pieter Wuille <pieter@wuille.net> | 2023-09-27 15:05:15 -0400 |
commit | d9841a7ac634472c1a9105f81f8e7b55e4bd1a4a (patch) | |
tree | 10918a452e57bb3b290415201f2de9d55e040f7c | |
parent | c9f288244b8d183e09a917025922b99e3368ef78 (diff) |
Add make_secure_unique helper
Co-authored-by: Pieter Wuille <bitcoin-dev@wuille.net>
-rw-r--r-- | src/support/allocators/secure.h | 24 |
1 files changed, 24 insertions, 0 deletions
diff --git a/src/support/allocators/secure.h b/src/support/allocators/secure.h index 558f835f11..4395567722 100644 --- a/src/support/allocators/secure.h +++ b/src/support/allocators/secure.h @@ -57,4 +57,28 @@ struct secure_allocator { // TODO: Consider finding a way to make incoming RPC request.params[i] mlock()ed as well typedef std::basic_string<char, std::char_traits<char>, secure_allocator<char> > SecureString; +template<typename T> +struct SecureUniqueDeleter { + void operator()(T* t) noexcept { + secure_allocator<T>().deallocate(t, 1); + } +}; + +template<typename T> +using secure_unique_ptr = std::unique_ptr<T, SecureUniqueDeleter<T>>; + +template<typename T, typename... Args> +secure_unique_ptr<T> make_secure_unique(Args&&... as) +{ + T* p = secure_allocator<T>().allocate(1); + + // initialize in place, and return as secure_unique_ptr + try { + return secure_unique_ptr<T>(new (p) T(std::forward(as)...)); + } catch (...) { + secure_allocator<T>().deallocate(p, 1); + throw; + } +} + #endif // BITCOIN_SUPPORT_ALLOCATORS_SECURE_H |