explicit_bzero.c 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. #include "includes.h"
  8. #include <string.h>
  9. /*
  10. * explicit_bzero - don't let the compiler optimize away bzero
  11. */
  12. #ifndef HAVE_EXPLICIT_BZERO
  13. #ifdef HAVE_EXPLICIT_MEMSET
  14. void
  15. explicit_bzero(void *p, size_t n)
  16. {
  17. (void)explicit_memset(p, 0, n);
  18. }
  19. #elif defined(HAVE_MEMSET_S)
  20. void
  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. #else /* HAVE_MEMSET_S */
  28. /*
  29. * Indirect bzero through a volatile pointer to hopefully avoid
  30. * dead-store optimisation eliminating the call.
  31. */
  32. static void (* volatile ssh_bzero)(void *, size_t) = bzero;
  33. void
  34. explicit_bzero(void *p, size_t n)
  35. {
  36. if (n == 0)
  37. return;
  38. /*
  39. * clang -fsanitize=memory needs to intercept memset-like functions
  40. * to correctly detect memory initialisation. Make sure one is called
  41. * directly since our indirection trick above successfully confuses it.
  42. */
  43. #if defined(__has_feature)
  44. # if __has_feature(memory_sanitizer)
  45. memset(p, 0, n);
  46. # endif
  47. #endif
  48. ssh_bzero(p, n);
  49. }
  50. #endif /* HAVE_MEMSET_S */
  51. #endif /* HAVE_EXPLICIT_BZERO */