1 /* OPENBSD ORIGINAL: lib/libc/string/explicit_bzero.c */
2 /*	$OpenBSD: explicit_bzero.c,v 1.1 2014/01/22 21:06:45 tedu Exp $ */
3 /*
4  * Public domain.
5  * Written by Ted Unangst
6  */
7 
8 #include "includes.h"
9 
10 #include <string.h>
11 
12 /*
13  * explicit_bzero - don't let the compiler optimize away bzero
14  */
15 
16 #ifndef HAVE_EXPLICIT_BZERO
17 
18 #ifdef HAVE_MEMSET_S
19 
20 void
explicit_bzero(void * p,size_t n)21 explicit_bzero(void *p, size_t n)
22 {
23 	if (n == 0)
24 		return;
25 	(void)memset_s(p, n, 0, n);
26 }
27 
28 #else /* HAVE_MEMSET_S */
29 
30 /*
31  * Indirect bzero through a volatile pointer to hopefully avoid
32  * dead-store optimisation eliminating the call.
33  */
34 #if defined(ANDROID)
35 static void (* volatile ssh_bzero)(void *, size_t) = __bionic_bzero;
36 #else
37 static void (* volatile ssh_bzero)(void *, size_t) = bzero;
38 #endif
39 
40 void
explicit_bzero(void * p,size_t n)41 explicit_bzero(void *p, size_t n)
42 {
43 	if (n == 0)
44 		return;
45 	/*
46 	 * clang -fsanitize=memory needs to intercept memset-like functions
47 	 * to correctly detect memory initialisation. Make sure one is called
48 	 * directly since our indirection trick above successfully confuses it.
49 	 */
50 #if defined(__has_feature)
51 # if __has_feature(memory_sanitizer)
52 	memset(p, 0, n);
53 # endif
54 #endif
55 
56 	ssh_bzero(p, n);
57 }
58 
59 #endif /* HAVE_MEMSET_S */
60 
61 #endif /* HAVE_EXPLICIT_BZERO */
62