Andres Morales | ac80818 | 2015-02-26 14:11:04 -0800 | [diff] [blame] | 1 | /* |
| 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 Morales | 7d0f040 | 2015-03-19 18:02:55 -0700 | [diff] [blame] | 17 | #ifndef GOOGLE_GATEKEEPER_UTILS_H_ |
| 18 | #define GOOGLE_GATEKEEPER_UTILS_H_ |
Andres Morales | ac80818 | 2015-02-26 14:11:04 -0800 | [diff] [blame] | 19 | |
| 20 | #include <string.h> |
| 21 | |
Andres Morales | 7d0f040 | 2015-03-19 18:02:55 -0700 | [diff] [blame] | 22 | namespace gatekeeper { |
Andres Morales | ac80818 | 2015-02-26 14:11:04 -0800 | [diff] [blame] | 23 | /** |
| 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__ |
| 33 | inline 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 | */ |
| 43 | template <typename T, size_t N> inline size_t array_length(const T (&)[N]) { |
| 44 | return N; |
| 45 | } |
| 46 | |
Chih-Hung Hsieh | 8aceb8f | 2015-05-06 14:52:23 -0700 | [diff] [blame] | 47 | static inline int memcmp_s(const void* p1, const void* p2, size_t length) { |
Andres Morales | ac80818 | 2015-02-26 14:11:04 -0800 | [diff] [blame] | 48 | 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 Morales | 7d0f040 | 2015-03-19 18:02:55 -0700 | [diff] [blame] | 57 | #endif //GOOGLE_GATEKEEPER_UTILS_H_ |