blob: 6ef9825a9ad34985ad7eefc1d3ef4ea7e63e199b [file] [log] [blame]
Damien Miller1d2c4562014-02-04 11:18:20 +11001/* 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
Damien Miller74433a12016-08-16 13:28:23 +100010#include <string.h>
11
Damien Miller1d2c4562014-02-04 11:18:20 +110012/*
13 * explicit_bzero - don't let the compiler optimize away bzero
14 */
Damien Miller3d673d12014-08-27 06:32:01 +100015
16#ifndef HAVE_EXPLICIT_BZERO
17
18#ifdef HAVE_MEMSET_S
19
Damien Miller1d2c4562014-02-04 11:18:20 +110020void
21explicit_bzero(void *p, size_t n)
22{
Damien Miller738c73d2017-07-14 14:26:36 +100023 if (n == 0)
24 return;
Damien Miller3d673d12014-08-27 06:32:01 +100025 (void)memset_s(p, n, 0, n);
Damien Miller1d2c4562014-02-04 11:18:20 +110026}
Damien Miller3d673d12014-08-27 06:32:01 +100027
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 */
34static void (* volatile ssh_bzero)(void *, size_t) = bzero;
35
36void
37explicit_bzero(void *p, size_t n)
38{
Damien Miller738c73d2017-07-14 14:26:36 +100039 if (n == 0)
40 return;
Damien Miller74433a12016-08-16 13:28:23 +100041 /*
42 * clang -fsanitize=memory needs to intercept memset-like functions
43 * to correctly detect memory initialisation. Make sure one is called
Damien Miller10479cc2018-04-10 10:19:02 +100044 * directly since our indirection trick above successfully confuses it.
Damien Miller74433a12016-08-16 13:28:23 +100045 */
46#if defined(__has_feature)
47# if __has_feature(memory_sanitizer)
48 memset(p, 0, n);
49# endif
50#endif
51
Damien Miller3d673d12014-08-27 06:32:01 +100052 ssh_bzero(p, n);
53}
54
55#endif /* HAVE_MEMSET_S */
56
57#endif /* HAVE_EXPLICIT_BZERO */