xref: /php-src/main/safe_bcmp.c (revision 2ebef11e)
1 /*
2   +----------------------------------------------------------------------+
3   | Copyright (c) The PHP Group                                          |
4   +----------------------------------------------------------------------+
5   | This source file is subject to version 3.01 of the PHP license,      |
6   | that is bundled with this package in the file LICENSE, and is        |
7   | available through the world-wide-web at the following url:           |
8   | https://www.php.net/license/3_01.txt                                 |
9   | If you did not receive a copy of the PHP license and are unable to   |
10   | obtain it through the world-wide-web, please send a note to          |
11   | license@php.net so we can mail you a copy immediately.               |
12   +----------------------------------------------------------------------+
13   | Author: David Carlier <devnexen@gmail.com>                           |
14   +----------------------------------------------------------------------+
15 */
16 
17 #include "php.h"
18 
19 #include <string.h>
20 
21 /*
22  * Returns 0 if both inputs match, non-zero if they don't.
23  * Returns -1 early if inputs do not have the same lengths.
24  *
25  */
php_safe_bcmp(const zend_string * a,const zend_string * b)26 PHPAPI int php_safe_bcmp(const zend_string *a, const zend_string *b)
27 {
28 	const volatile unsigned char *ua = (const volatile unsigned char *)ZSTR_VAL(a);
29 	const volatile unsigned char *ub = (const volatile unsigned char *)ZSTR_VAL(b);
30 	size_t i = 0;
31 	int r = 0;
32 
33 	if (ZSTR_LEN(a) != ZSTR_LEN(b)) {
34 		return -1;
35 	}
36 
37 	/* This is security sensitive code. Do not optimize this for speed. */
38 	while (i < ZSTR_LEN(a)) {
39 		r |= ua[i] ^ ub[i];
40 		++i;
41 	}
42 
43 	return r;
44 }
45