Botan 3.7.1
Crypto and TLS for C&
mem_utils.cpp
Go to the documentation of this file.
1/*
2* (C) 2025 Jack Lloyd
3*
4* Botan is released under the Simplified BSD License (see license.txt)
5*/
6
7#include <botan/mem_ops.h>
8
9#include <cstring>
10
11#if defined(BOTAN_TARGET_OS_HAS_RTLSECUREZEROMEMORY)
12 #define NOMINMAX 1
13 #define _WINSOCKAPI_ // stop windows.h including winsock.h
14 #include <windows.h>
15#endif
16
17namespace Botan {
18
19void secure_scrub_memory(void* ptr, size_t n) {
20#if defined(BOTAN_TARGET_OS_HAS_RTLSECUREZEROMEMORY)
21 ::RtlSecureZeroMemory(ptr, n);
22
23#elif defined(BOTAN_TARGET_OS_HAS_EXPLICIT_BZERO)
24 ::explicit_bzero(ptr, n);
25
26#elif defined(BOTAN_TARGET_OS_HAS_EXPLICIT_MEMSET)
27 (void)::explicit_memset(ptr, 0, n);
28
29#elif defined(BOTAN_USE_VOLATILE_MEMSET_FOR_ZERO) && (BOTAN_USE_VOLATILE_MEMSET_FOR_ZERO == 1)
30 /*
31 Call memset through a static volatile pointer, which the compiler
32 should not elide. This construct should be safe in conforming
33 compilers, but who knows. I did confirm that on x86-64 GCC 6.1 and
34 Clang 3.8 both create code that saves the memset address in the
35 data segment and unconditionally loads and jumps to that address.
36 */
37 static void* (*const volatile memset_ptr)(void*, int, size_t) = std::memset;
38 (memset_ptr)(ptr, 0, n);
39#else
40
41 volatile uint8_t* p = reinterpret_cast<volatile uint8_t*>(ptr);
42
43 for(size_t i = 0; i != n; ++i)
44 p[i] = 0;
45#endif
46}
47
48} // namespace Botan
void secure_scrub_memory(void *ptr, size_t n)
Definition mem_utils.cpp:19