| 1 |
/* Erase sensitive data from memory. |
| 2 |
Copyright 2022-2026 Free Software Foundation, Inc. |
| 3 |
|
| 4 |
This file is free software: you can redistribute it and/or modify |
| 5 |
it under the terms of the GNU Lesser General Public License as |
| 6 |
published by the Free Software Foundation; either version 2.1 of the |
| 7 |
License, or (at your option) any later version. |
| 8 |
|
| 9 |
This file is distributed in the hope that it will be useful, |
| 10 |
but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 |
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 |
GNU Lesser General Public License for more details. |
| 13 |
|
| 14 |
You should have received a copy of the GNU Lesser General Public License |
| 15 |
along with this program. If not, see <https://www.gnu.org/licenses/>. */ |
| 16 |
|
| 17 |
#include <config.h> |
| 18 |
|
| 19 |
/* Specification. */ |
| 20 |
#include <string.h> |
| 21 |
|
| 22 |
/* Set S's bytes to C, where S has LEN bytes. The compiler will not |
| 23 |
optimize effects away, even if S is dead after the call. */ |
| 24 |
void * |
| 25 |
memset_explicit (void *s, int c, size_t len) |
| 26 |
{ |
| 27 |
#if HAVE_EXPLICIT_MEMSET |
| 28 |
return explicit_memset (s, c, len); |
| 29 |
#elif HAVE_MEMSET_S |
| 30 |
# if !HAVE_MEMSET_S_SUPPORTS_ZERO |
| 31 |
if (len > 0) |
| 32 |
# endif |
| 33 |
(void) memset_s (s, len, c, len); |
| 34 |
return s; |
| 35 |
#elif defined __GNUC__ && !defined __clang__ |
| 36 |
memset (s, c, len); |
| 37 |
/* Compiler barrier. */ |
| 38 |
__asm__ volatile ("" ::: "memory"); |
| 39 |
return s; |
| 40 |
#elif defined __clang__ |
| 41 |
memset (s, c, len); |
| 42 |
/* Compiler barrier. */ |
| 43 |
/* With asm ("" ::: "memory") LLVM analyzes uses of 's' and finds that the |
| 44 |
whole thing is dead and eliminates it. Use 'g' to work around this |
| 45 |
problem. See <https://bugs.llvm.org/show_bug.cgi?id=15495#c11>. */ |
| 46 |
__asm__ volatile ("" : : "g"(s) : "memory"); |
| 47 |
return s; |
| 48 |
#else |
| 49 |
/* Invoke memset through a volatile function pointer. This defeats compiler |
| 50 |
optimizations. */ |
| 51 |
void * (* const volatile volatile_memset) (void *, int, size_t) = memset; |
| 52 |
return volatile_memset (s, c, len); |
| 53 |
#endif |
| 54 |
} |