blob: 8ee032b0a752010a8a60c74bcb0aa6095fca4def [file] [log] [blame]
Andres Moralesac808182015-02-26 14:11:04 -08001/*
2 * Copyright 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 *
16 */
Andres Morales7d0f0402015-03-19 18:02:55 -070017#ifndef GOOGLE_GATEKEEPER_UTILS_H_
18#define GOOGLE_GATEKEEPER_UTILS_H_
Andres Moralesac808182015-02-26 14:11:04 -080019
20#include <string.h>
21
Andres Morales7d0f0402015-03-19 18:02:55 -070022namespace gatekeeper {
Andres Moralesac808182015-02-26 14:11:04 -080023/**
24 * Variant of memset() that uses GCC-specific pragmas to disable optimizations, so effect is not
25 * optimized away. This is important because we often need to wipe blocks of sensitive data from
26 * memory. As an additional convenience, this implementation avoids writing to NULL pointers.
27 */
28#ifdef __clang__
29#define OPTNONE __attribute__((optnone))
30#else // not __clang__
31#define OPTNONE __attribute__((optimize("O0")))
32#endif // not __clang__
33inline OPTNONE void* memset_s(void* s, int c, size_t n) {
34 if (!s)
35 return s;
36 return memset(s, c, n);
37}
38#undef OPTNONE
39
40/**
41 * Return the number of elements in array \p a.
42 */
43template <typename T, size_t N> inline size_t array_length(const T (&)[N]) {
44 return N;
45}
46
Chih-Hung Hsieh8aceb8f2015-05-06 14:52:23 -070047static inline int memcmp_s(const void* p1, const void* p2, size_t length) {
Andres Moralesac808182015-02-26 14:11:04 -080048 const uint8_t* s1 = static_cast<const uint8_t*>(p1);
49 const uint8_t* s2 = static_cast<const uint8_t*>(p2);
50 uint8_t result = 0;
51 while (length-- > 0)
52 result |= *s1++ ^ *s2++;
53 return result == 0 ? 0 : 1;
54}
55
56};
Andres Morales7d0f0402015-03-19 18:02:55 -070057#endif //GOOGLE_GATEKEEPER_UTILS_H_