Source-Changes-HG archive
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index][Old Index]
[src/trunk]: src/common/lib/libc/string Switch to the suggested constant-time...
details: https://anonhg.NetBSD.org/src/rev/4af4a4274ffd
branches: trunk
changeset: 336775:4af4a4274ffd
user: riastradh <riastradh%NetBSD.org@localhost>
date: Wed Mar 18 20:11:35 2015 +0000
description:
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.
diffstat:
common/lib/libc/string/consttime_memequal.c | 22 +++++++++++-----------
1 files changed, 11 insertions(+), 11 deletions(-)
diffs (40 lines):
diff -r 2393c02bfc7c -r 4af4a4274ffd common/lib/libc/string/consttime_memequal.c
--- a/common/lib/libc/string/consttime_memequal.c Wed Mar 18 17:43:20 2015 +0000
+++ b/common/lib/libc/string/consttime_memequal.c Wed Mar 18 20:11:35 2015 +0000
@@ -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 <drochner%NetBSD.org@localhost>.
@@ -18,20 +18,20 @@
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));
}
Home |
Main Index |
Thread Index |
Old Index