1298691Sdelphij/* 2298691Sdelphij * Copyright (C) 2004-2007, 2011, 2012 Internet Systems Consortium, Inc. ("ISC") 3298691Sdelphij * Copyright (C) 1999-2001, 2003 Internet Software Consortium. 4298691Sdelphij * 5298691Sdelphij * Permission to use, copy, modify, and/or distribute this software for any 6298691Sdelphij * purpose with or without fee is hereby granted, provided that the above 7298691Sdelphij * copyright notice and this permission notice appear in all copies. 8298691Sdelphij * 9298691Sdelphij * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH 10298691Sdelphij * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY 11298691Sdelphij * AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT, 12298691Sdelphij * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM 13298691Sdelphij * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE 14298691Sdelphij * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR 15298691Sdelphij * PERFORMANCE OF THIS SOFTWARE. 16298691Sdelphij */ 17298691Sdelphij 18298691Sdelphij/* $Id$ */ 19298691Sdelphij 20298691Sdelphij/*! \file */ 21298691Sdelphij 22298691Sdelphij#include <config.h> 23298691Sdelphij#include <limits.h> 24298691Sdelphij#include <isc/string.h> 25298691Sdelphij 26298691Sdelphij/* Making a portable memcmp that has no internal branches and loops always 27298691Sdelphij * once for every byte without early-out shortcut has a few challenges. 28298691Sdelphij * 29298691Sdelphij * Inspired by 'timingsafe_memcmp()' from the BSD system and 30298691Sdelphij * https://github.com/libressl-portable/openbsd/blob/master/src/lib/libc/string/timingsafe_memcmp.c 31298691Sdelphij * 32298691Sdelphij * Sadly, that one is not portable C: It makes assumptions on the representation 33298691Sdelphij * of negative integers and assumes sign-preserving right-shift of negative 34298691Sdelphij * signed values. This is a rewrite from scratch that should not suffer from 35298691Sdelphij * such issues. 36298691Sdelphij * 37298691Sdelphij * 2015-12-12, J. Perlinger (perlinger-at-ntp-dot-org) 38298691Sdelphij */ 39298691Sdelphijint 40298691Sdelphijisc_tsmemcmp(const void *p1, const void *p2, size_t nb) { 41298691Sdelphij const unsigned char *ucp1 = p1; 42298691Sdelphij const unsigned char *ucp2 = p2; 43298691Sdelphij unsigned int isLT = 0u; 44298691Sdelphij unsigned int isGT = 0u; 45298691Sdelphij volatile unsigned int mask = (1u << CHAR_BIT); 46298691Sdelphij 47298691Sdelphij for (/*NOP*/; 0 != nb; --nb, ++ucp1, ++ucp2) { 48298691Sdelphij isLT |= mask & 49298691Sdelphij ((unsigned int)*ucp1 - (unsigned int)*ucp2); 50298691Sdelphij isGT |= mask & 51298691Sdelphij ((unsigned int)*ucp2 - (unsigned int)*ucp1); 52298691Sdelphij mask &= ~(isLT | isGT); 53298691Sdelphij } 54298691Sdelphij return (int)(isGT >> CHAR_BIT) - (int)(isLT >> CHAR_BIT); 55298691Sdelphij} 56