2
0
Эх сурвалжийг харах

A bit more optimization/cleanup.

Adam Ierymenko 5 жил өмнө
parent
commit
94c35d395e
2 өөрчлөгдсөн 10 нэмэгдсэн , 11 устгасан
  1. 7 9
      core/Utils.cpp
  2. 3 2
      core/Utils.hpp

+ 7 - 9
core/Utils.cpp

@@ -99,18 +99,16 @@ bool secureEq(const void *a, const void *b, unsigned int len) noexcept
 	return (diff == 0);
 }
 
-// Crazy hack to force memory to be securely zeroed in spite of the best efforts of optimizing compilers.
-static void _Utils_doBurn(volatile uint8_t *ptr, unsigned int len)
+void burn(volatile void *ptr, unsigned int len)
 {
-	for (unsigned int i = 0; i < len; ++i)
-		ptr[i] = 0;
+	Utils::zero((void *)ptr, len);
+	// This line is present to force the compiler not to optimize out the memory
+	// zeroing operation above, as burn() is used to erase secrets and other
+	// sensitive data.
+	if ((reinterpret_cast<volatile uint8_t *>(ptr)[0] | reinterpret_cast<volatile uint8_t *>(ptr)[len-1]) != 0)
+		throw BadAllocException;
 }
 
-static void (*volatile _Utils_doBurn_ptr)(volatile uint8_t *, unsigned int) = _Utils_doBurn;
-
-void burn(void *ptr, unsigned int len)
-{ (_Utils_doBurn_ptr)((volatile uint8_t *)ptr, len); }
-
 static unsigned long _Utils_itoa(unsigned long n, char *s)
 {
 	if (n == 0)

+ 3 - 2
core/Utils.hpp

@@ -137,12 +137,13 @@ bool secureEq(const void *a, const void *b, unsigned int len) noexcept;
 /**
  * Be absolutely sure to zero memory
  *
- * This uses some hacks to be totally sure the compiler does not optimize it out.
+ * This uses a few tricks to make sure the compiler doesn't optimize it
+ * out, including passing the memory as volatile.
  *
  * @param ptr Memory to zero
  * @param len Length of memory in bytes
  */
-void burn(void *ptr, unsigned int len);
+void burn(volatile void *ptr, unsigned int len);
 
 /**
  * @param n Number to convert