Module Name:    src
Committed By:   riastradh
Date:           Wed Mar 18 20:11:35 UTC 2015

Modified Files:
        src/common/lib/libc/string: consttime_memequal.c

Log Message:
Switch to the suggested constant-time result conversion.

Not hard to find CPU/compiler combinations with branches for `!res'.

While here, make everything unsigned for good measure.


To generate a diff of this commit:
cvs rdiff -u -r1.5 -r1.6 src/common/lib/libc/string/consttime_memequal.c

Please note that diffs are not public domain; they are subject to the
copyright notices on the relevant files.

Modified files:

Index: src/common/lib/libc/string/consttime_memequal.c
diff -u src/common/lib/libc/string/consttime_memequal.c:1.5 src/common/lib/libc/string/consttime_memequal.c:1.6
--- src/common/lib/libc/string/consttime_memequal.c:1.5	Tue Jun 24 16:39:39 2014
+++ src/common/lib/libc/string/consttime_memequal.c	Wed Mar 18 20:11:35 2015
@@ -1,4 +1,4 @@
-/* $NetBSD: consttime_memequal.c,v 1.5 2014/06/24 16:39:39 drochner Exp $ */
+/* $NetBSD: consttime_memequal.c,v 1.6 2015/03/18 20:11:35 riastradh Exp $ */
 
 /*
  * Written by Matthias Drochner <[email protected]>.
@@ -18,20 +18,20 @@ __weak_alias(consttime_memequal,_constti
 int
 consttime_memequal(const void *b1, const void *b2, size_t len)
 {
-	const char *c1 = b1, *c2 = b2;
-	int res = 0;
+	const unsigned char *c1 = b1, *c2 = b2;
+	unsigned int res = 0;
 
-	while (len --)
+	while (len--)
 		res |= *c1++ ^ *c2++;
 
 	/*
-	 * If the compiler for your favourite architecture generates a
-	 * conditional branch for `!res', it will be a data-dependent
-	 * branch, in which case this should be replaced by
+	 * Map 0 to 1 and [1, 256) to 0 using only constant-time
+	 * arithmetic.
 	 *
-	 *	return (1 - (1 & ((res - 1) >> 8)));
-	 *
-	 * or rewritten in assembly.
+	 * This is not simply `!res' because although many CPUs support
+	 * branchless conditional moves and many compilers will take
+	 * advantage of them, certain compilers generate branches on
+	 * certain CPUs for `!res'.
 	 */
-	return !res;
+	return (1 & ((res - 1) >> 8));
 }

Reply via email to