Botan 3.11.0
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/internal/mem_utils.h>
8
9#include <botan/mem_ops.h>
10#include <botan/internal/target_info.h>
11#include <cstring>
12
13#if defined(BOTAN_TARGET_OS_HAS_EXPLICIT_BZERO)
14 #include <string.h>
15#endif
16
17#if defined(BOTAN_TARGET_OS_HAS_RTLSECUREZEROMEMORY)
18 #define NOMINMAX 1
19 #define _WINSOCKAPI_ // stop windows.h including winsock.h
20 #include <windows.h>
21#endif
22
23namespace Botan {
24
25void secure_scrub_memory(void* ptr, size_t n) {
26 return secure_zeroize_buffer(ptr, n);
27}
28
29void secure_zeroize_buffer(void* ptr, size_t n) {
30 if(n == 0) {
31 return;
32 }
33
34#if defined(BOTAN_TARGET_OS_HAS_RTLSECUREZEROMEMORY)
35 ::RtlSecureZeroMemory(ptr, n);
36
37#elif defined(BOTAN_TARGET_OS_HAS_EXPLICIT_BZERO)
38 ::explicit_bzero(ptr, n);
39
40#elif defined(BOTAN_TARGET_OS_HAS_EXPLICIT_MEMSET)
41 (void)::explicit_memset(ptr, 0, n);
42
43#else
44 /*
45 * Call memset through a static volatile pointer, which the compiler should
46 * not elide. This construct should be safe in conforming compilers, but who
47 * knows. This has been checked to generate the expected code, which saves the
48 * memset address in the data segment and unconditionally loads and jumps to
49 * that address, with the following targets:
50 *
51 * x86-64: Clang 19, GCC 6, 11, 13, 14
52 * riscv64: GCC 14
53 * aarch64: GCC 14
54 * armv7: GCC 14
55 *
56 * Actually all of them generated the expected jump even without marking the
57 * function pointer as volatile. However this seems worth including as an
58 * additional precaution.
59 */
60 static void* (*const volatile memset_ptr)(void*, int, size_t) = std::memset;
61 (memset_ptr)(ptr, 0, n);
62#endif
63}
64
65} // namespace Botan
void secure_scrub_memory(void *ptr, size_t n)
Definition mem_utils.cpp:25
void secure_zeroize_buffer(void *ptr, size_t n)
Definition mem_utils.cpp:29