2015-01-20 21:23:25 -03:00
|
|
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
|
2018-07-26 18:36:45 -04:00
|
|
|
// Copyright (c) 2009-2018 The Bitcoin Core developers
|
2015-01-20 21:23:25 -03:00
|
|
|
// Distributed under the MIT software license, see the accompanying
|
|
|
|
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
|
|
|
|
2017-11-09 21:57:53 -03:00
|
|
|
#include <support/cleanse.h>
|
2015-01-20 21:23:25 -03:00
|
|
|
|
2017-08-30 02:26:12 -03:00
|
|
|
#include <cstring>
|
2015-01-20 21:23:25 -03:00
|
|
|
|
2017-11-09 17:06:49 -03:00
|
|
|
#if defined(_MSC_VER)
|
|
|
|
#include <Windows.h> // For SecureZeroMemory.
|
|
|
|
#endif
|
|
|
|
|
2015-01-20 21:23:25 -03:00
|
|
|
void memory_cleanse(void *ptr, size_t len)
|
|
|
|
{
|
2019-06-05 16:43:28 -04:00
|
|
|
#if defined(_MSC_VER)
|
2019-06-05 16:44:04 -04:00
|
|
|
/* SecureZeroMemory is guaranteed not to be optimized out by MSVC. */
|
2019-06-05 16:43:28 -04:00
|
|
|
SecureZeroMemory(ptr, len);
|
|
|
|
#else
|
2017-08-30 02:26:12 -03:00
|
|
|
std::memset(ptr, 0, len);
|
|
|
|
|
2019-06-05 16:44:04 -04:00
|
|
|
/* Memory barrier that scares the compiler away from optimizing out the memset.
|
|
|
|
*
|
|
|
|
* Quoting Adam Langley <agl@google.com> in commit ad1907fe73334d6c696c8539646c21b11178f20f
|
|
|
|
* in BoringSSL (ISC License):
|
|
|
|
* As best as we can tell, this is sufficient to break any optimisations that
|
|
|
|
* might try to eliminate "superfluous" memsets.
|
|
|
|
* This method is used in memzero_explicit() the Linux kernel, too. Its advantage is that it
|
|
|
|
* is pretty efficient because the compiler can still implement the memset() efficiently,
|
|
|
|
* just not remove it entirely. See "Dead Store Elimination (Still) Considered Harmful" by
|
|
|
|
* Yang et al. (USENIX Security 2017) for more background.
|
|
|
|
*/
|
2017-08-30 02:26:12 -03:00
|
|
|
__asm__ __volatile__("" : : "r"(ptr) : "memory");
|
|
|
|
#endif
|
2015-01-20 21:23:25 -03:00
|
|
|
}
|