Blame compat/timingsafe_memcmp.c

Ørjan Malde 24d238
/*	$OpenBSD: timingsafe_memcmp.c,v 1.2 2015/08/31 02:53:57 guenther Exp $	*/
Ørjan Malde 24d238
/*
Ørjan Malde 24d238
 * Copyright (c) 2014 Google Inc.
Ørjan Malde 24d238
 *
Ørjan Malde 24d238
 * Permission to use, copy, modify, and distribute this software for any
Ørjan Malde 24d238
 * purpose with or without fee is hereby granted, provided that the above
Ørjan Malde 24d238
 * copyright notice and this permission notice appear in all copies.
Ørjan Malde 24d238
 *
Ørjan Malde 24d238
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
Ørjan Malde 24d238
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
Ørjan Malde 24d238
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
Ørjan Malde 24d238
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
Ørjan Malde 24d238
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
Ørjan Malde 24d238
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
Ørjan Malde 24d238
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
Ørjan Malde 24d238
 */
Ørjan Malde 24d238
Ørjan Malde 24d238
#include <limits.h>
Ørjan Malde 24d238
#include <string.h>
Ørjan Malde 24d238
Ørjan Malde 24d238
int
Ørjan Malde 24d238
timingsafe_memcmp(const void *b1, const void *b2, size_t len)
Ørjan Malde 24d238
{
Ørjan Malde 24d238
        const unsigned char *p1 = b1, *p2 = b2;
Ørjan Malde 24d238
        size_t i;
Ørjan Malde 24d238
        int res = 0, done = 0;
Ørjan Malde 24d238
Ørjan Malde 24d238
        for (i = 0; i < len; i++) {
Ørjan Malde 24d238
                /* lt is -1 if p1[i] < p2[i]; else 0. */
Ørjan Malde 24d238
                int lt = (p1[i] - p2[i]) >> CHAR_BIT;
Ørjan Malde 24d238
Ørjan Malde 24d238
                /* gt is -1 if p1[i] > p2[i]; else 0. */
Ørjan Malde 24d238
                int gt = (p2[i] - p1[i]) >> CHAR_BIT;
Ørjan Malde 24d238
Ørjan Malde 24d238
                /* cmp is 1 if p1[i] > p2[i]; -1 if p1[i] < p2[i]; else 0. */
Ørjan Malde 24d238
                int cmp = lt - gt;
Ørjan Malde 24d238
Ørjan Malde 24d238
                /* set res = cmp if !done. */
Ørjan Malde 24d238
                res |= cmp & ~done;
Ørjan Malde 24d238
Ørjan Malde 24d238
                /* set done if p1[i] != p2[i]. */
Ørjan Malde 24d238
                done |= lt | gt;
Ørjan Malde 24d238
        }
Ørjan Malde 24d238
Ørjan Malde 24d238
        return (res);
Ørjan Malde 24d238
}