Line data Source code
1 : // Copyright (c) 2009-2010 Satoshi Nakamoto 2 : // Copyright (c) 2009-2015 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 : #include "cleanse.h" 7 : 8 : #include <cstring> 9 : 10 : /* Compilers have a bad habit of removing "superfluous" memset calls that 11 : * are trying to zero memory. For example, when memset()ing a buffer and 12 : * then free()ing it, the compiler might decide that the memset is 13 : * unobservable and thus can be removed. 14 : * 15 : * Previously we used OpenSSL which tried to stop this by a) implementing 16 : * memset in assembly on x86 and b) putting the function in its own file 17 : * for other platforms. 18 : * 19 : * This change removes those tricks in favour of using asm directives to 20 : * scare the compiler away. As best as our compiler folks can tell, this is 21 : * sufficient and will continue to be so. 22 : * 23 : * Adam Langley <agl@google.com> 24 : * Commit: ad1907fe73334d6c696c8539646c21b11178f20f 25 : * BoringSSL (LICENSE: ISC) 26 : */ 27 31199250 : void memory_cleanse(void *ptr, size_t len) 28 : { 29 31199250 : std::memset(ptr, 0, len); 30 : 31 : /* As best as we can tell, this is sufficient to break any optimisations that 32 : might try to eliminate "superfluous" memsets. If there's an easy way to 33 : detect memset_s, it would be better to use that. */ 34 : #if defined(_MSC_VER) 35 : __asm; 36 : #else 37 31199250 : __asm__ __volatile__("" : : "r"(ptr) : "memory"); 38 : #endif 39 31199250 : }