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