safebfuns.c (1335B)
1 /* Public domain */ 2 3 #include <string.h> 4 5 #if __clang__ 6 /* 7 * http://clang.llvm.org/docs/LanguageExtensions.html#feature-checking-macros 8 * http://lists.cs.uiuc.edu/pipermail/cfe-dev/2014-December/040627.html 9 */ 10 #if __has_attribute( noinline ) /* && __has_attribute( optnone ) */ 11 #define NOOPT /* __attribute__ (( optnone )) */ 12 #define NOINLINE __attribute__ (( noinline )) 13 #else 14 #error "require clang with noinline and optnone attributes" 15 #endif 16 #elif __GNUC__ 17 /* 18 * http://gcc.gnu.org/onlinedocs/gcc/Function-Specific-Option-Pragmas.html 19 * http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html 20 */ 21 #if __GNUC__ > 4 || ( __GNUC__ == 4 && __GNUC_MINOR__ >= 4 ) 22 #define NOOPT __attribute__ (( optimize( 0 ) )) 23 #define NOINLINE __attribute__ (( noinline )) 24 #else 25 #error "require gcc >= 4.4" 26 #endif 27 #else 28 #error "unrecognised compiler" 29 explode 30 #endif 31 32 NOOPT NOINLINE void explicit_bzero( void * const buf, const size_t n ) { 33 size_t i; 34 unsigned char * p = buf; 35 36 for( i = 0; i < n; i++ ) { 37 p[ i ] = 0; 38 } 39 } 40 41 NOOPT NOINLINE int timingsafe_bcmp( const void * const b1, const void * const b2, const size_t n ) { 42 size_t i; 43 const unsigned char * const p1 = b1; 44 const unsigned char * const p2 = b2; 45 int result = 0; 46 47 for( i = 0; i < n; i++ ) { 48 result |= p1[ i ] ^ p2[ i ]; 49 } 50 51 return result != 0; 52 }