1304106Sdelphij/*	$OpenBSD: timingsafe_memcmp.c,v 1.2 2015/08/31 02:53:57 guenther Exp $	*/
2304106Sdelphij/*
3304106Sdelphij * Copyright (c) 2014 Google Inc.
4304106Sdelphij *
5304106Sdelphij * Permission to use, copy, modify, and distribute this software for any
6304106Sdelphij * purpose with or without fee is hereby granted, provided that the above
7304106Sdelphij * copyright notice and this permission notice appear in all copies.
8304106Sdelphij *
9304106Sdelphij * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10304106Sdelphij * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11304106Sdelphij * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12304106Sdelphij * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13304106Sdelphij * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14304106Sdelphij * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15304106Sdelphij * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16304106Sdelphij */
17304106Sdelphij
18304106Sdelphij#include <sys/cdefs.h>
19304106Sdelphij__FBSDID("$FreeBSD: stable/11/lib/libc/string/timingsafe_memcmp.c 319292 2017-05-31 06:47:56Z delphij $");
20304106Sdelphij
21304106Sdelphij#include <limits.h>
22304106Sdelphij#include <string.h>
23304106Sdelphij
24304106Sdelphijint __timingsafe_memcmp(const void *, const void *, size_t);
25304106Sdelphij
26304106Sdelphijint
27304106Sdelphij__timingsafe_memcmp(const void *b1, const void *b2, size_t len)
28304106Sdelphij{
29304106Sdelphij        const unsigned char *p1 = b1, *p2 = b2;
30304106Sdelphij        size_t i;
31304106Sdelphij        int res = 0, done = 0;
32304106Sdelphij
33304106Sdelphij        for (i = 0; i < len; i++) {
34304106Sdelphij                /* lt is -1 if p1[i] < p2[i]; else 0. */
35304106Sdelphij                int lt = (p1[i] - p2[i]) >> CHAR_BIT;
36304106Sdelphij
37304106Sdelphij                /* gt is -1 if p1[i] > p2[i]; else 0. */
38304106Sdelphij                int gt = (p2[i] - p1[i]) >> CHAR_BIT;
39304106Sdelphij
40304106Sdelphij                /* cmp is 1 if p1[i] > p2[i]; -1 if p1[i] < p2[i]; else 0. */
41304106Sdelphij                int cmp = lt - gt;
42304106Sdelphij
43304106Sdelphij                /* set res = cmp if !done. */
44304106Sdelphij                res |= cmp & ~done;
45304106Sdelphij
46304106Sdelphij                /* set done if p1[i] != p2[i]. */
47304106Sdelphij                done |= lt | gt;
48304106Sdelphij        }
49304106Sdelphij
50304106Sdelphij        return (res);
51304106Sdelphij}
52304106Sdelphij
53304106Sdelphij__weak_reference(__timingsafe_memcmp, timingsafe_memcmp);
54