summaryrefslogtreecommitdiff
path: root/missing/explicit_bzero.c
blob: 99b2e2758cf6cfcc66a15b960f99061a3899dd7d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include "ruby/missing.h"
#include <string.h>

#ifdef _WIN32
#include <windows.h>
#endif

/*
 *BSD have explicit_bzero().
 Windows, OS-X have memset_s().
 Linux has none. *Sigh*
*/

/*
 * Following URL explain why memset_s is added to the standard.
 * http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1381.pdf
 */

#ifndef FUNC_UNOPTIMIZED
# define FUNC_UNOPTIMIZED(x) x
#endif

#ifndef HAVE_EXPLICIT_BZERO
/* Similar to bzero(), but have a guarantee not to be eliminated from compiler
   optimization. */

#ifndef HAVE_MEMSET_S
FUNC_UNOPTIMIZED(void explicit_bzero(void *b, size_t len));
#endif
#undef explicit_bzero

void
explicit_bzero(void *b, size_t len)
{
#ifdef HAVE_MEMSET_S
    memset_s(b, len, 0, len);
#elif defined SecureZeroMemory
    SecureZeroMemory(b, len);
#else
    {
	/*
	 * TODO: volatile is not enough if compiler have a LTO (link time
	 * optimization)
	 */
	volatile char* p = (volatile char*)b;

	while(len) {
	    *p = 0;
	    p++;
	    len--;
	}
    }
#endif
}
#endif