xref: /netbsd-src/common/lib/libc/string/consttime_memequal.c (revision aad9773e38ed2370a628a6416e098f9008fc10a7)
1 /* $NetBSD: consttime_memequal.c,v 1.5 2014/06/24 16:39:39 drochner Exp $ */
2 
3 /*
4  * Written by Matthias Drochner <drochner@NetBSD.org>.
5  * Public domain.
6  */
7 
8 #if !defined(_KERNEL) && !defined(_STANDALONE)
9 #include "namespace.h"
10 #include <string.h>
11 #ifdef __weak_alias
12 __weak_alias(consttime_memequal,_consttime_memequal)
13 #endif
14 #else
15 #include <lib/libkern/libkern.h>
16 #endif
17 
18 int
19 consttime_memequal(const void *b1, const void *b2, size_t len)
20 {
21 	const char *c1 = b1, *c2 = b2;
22 	int res = 0;
23 
24 	while (len --)
25 		res |= *c1++ ^ *c2++;
26 
27 	/*
28 	 * If the compiler for your favourite architecture generates a
29 	 * conditional branch for `!res', it will be a data-dependent
30 	 * branch, in which case this should be replaced by
31 	 *
32 	 *	return (1 - (1 & ((res - 1) >> 8)));
33 	 *
34 	 * or rewritten in assembly.
35 	 */
36 	return !res;
37 }
38