xref: /OK3568_Linux_fs/external/xserver/os/timingsafe_memcmp.c (revision 4882a59341e53eb6f0b4789bf948001014eff981)
1*4882a593Smuzhiyun /*
2*4882a593Smuzhiyun  * Copyright (c) 2014 Google Inc.
3*4882a593Smuzhiyun  *
4*4882a593Smuzhiyun  * Permission to use, copy, modify, and distribute this software for any
5*4882a593Smuzhiyun  * purpose with or without fee is hereby granted, provided that the above
6*4882a593Smuzhiyun  * copyright notice and this permission notice appear in all copies.
7*4882a593Smuzhiyun  *
8*4882a593Smuzhiyun  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9*4882a593Smuzhiyun  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10*4882a593Smuzhiyun  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11*4882a593Smuzhiyun  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12*4882a593Smuzhiyun  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13*4882a593Smuzhiyun  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14*4882a593Smuzhiyun  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15*4882a593Smuzhiyun  */
16*4882a593Smuzhiyun 
17*4882a593Smuzhiyun #include <dix-config.h>
18*4882a593Smuzhiyun #include <limits.h>
19*4882a593Smuzhiyun #include <string.h>
20*4882a593Smuzhiyun #include <X11/Xfuncproto.h>
21*4882a593Smuzhiyun #include "os.h"
22*4882a593Smuzhiyun 
23*4882a593Smuzhiyun int
timingsafe_memcmp(const void * b1,const void * b2,size_t len)24*4882a593Smuzhiyun timingsafe_memcmp(const void *b1, const void *b2, size_t len)
25*4882a593Smuzhiyun {
26*4882a593Smuzhiyun         const unsigned char *p1 = b1, *p2 = b2;
27*4882a593Smuzhiyun         size_t i;
28*4882a593Smuzhiyun         int res = 0, done = 0;
29*4882a593Smuzhiyun 
30*4882a593Smuzhiyun         for (i = 0; i < len; i++) {
31*4882a593Smuzhiyun                 /* lt is -1 if p1[i] < p2[i]; else 0. */
32*4882a593Smuzhiyun                 int lt = (p1[i] - p2[i]) >> CHAR_BIT;
33*4882a593Smuzhiyun 
34*4882a593Smuzhiyun                 /* gt is -1 if p1[i] > p2[i]; else 0. */
35*4882a593Smuzhiyun                 int gt = (p2[i] - p1[i]) >> CHAR_BIT;
36*4882a593Smuzhiyun 
37*4882a593Smuzhiyun                 /* cmp is 1 if p1[i] > p2[i]; -1 if p1[i] < p2[i]; else 0. */
38*4882a593Smuzhiyun                 int cmp = lt - gt;
39*4882a593Smuzhiyun 
40*4882a593Smuzhiyun                 /* set res = cmp if !done. */
41*4882a593Smuzhiyun                 res |= cmp & ~done;
42*4882a593Smuzhiyun 
43*4882a593Smuzhiyun                 /* set done if p1[i] != p2[i]. */
44*4882a593Smuzhiyun                 done |= lt | gt;
45*4882a593Smuzhiyun         }
46*4882a593Smuzhiyun 
47*4882a593Smuzhiyun         return (res);
48*4882a593Smuzhiyun }
49