blob: d5946b219cc2c48763346947c42c78256db4e734 [file] [log] [blame]
Austin Schuh36244a12019-09-21 17:52:38 -07001// Copyright 2017 The Abseil Authors.
2//
3// Licensed under the Apache License, Version 2.0 (the"License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an"AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15// HERMETIC NOTE: The randen_hwaes target must not introduce duplicate
16// symbols from arbitrary system and other headers, since it may be built
17// with different flags from other targets, using different levels of
18// optimization, potentially introducing ODR violations.
19
20#include "absl/random/internal/randen_detect.h"
21
22#include <cstdint>
23#include <cstring>
24
25#include "absl/random/internal/platform.h"
26
27#if defined(ABSL_ARCH_X86_64)
28#define ABSL_INTERNAL_USE_X86_CPUID
29#elif defined(ABSL_ARCH_PPC) || defined(ABSL_ARCH_ARM) || \
30 defined(ABSL_ARCH_AARCH64)
31#if defined(__ANDROID__)
32#define ABSL_INTERNAL_USE_ANDROID_GETAUXVAL
33#define ABSL_INTERNAL_USE_GETAUXVAL
34#elif defined(__linux__)
35#define ABSL_INTERNAL_USE_LINUX_GETAUXVAL
36#define ABSL_INTERNAL_USE_GETAUXVAL
37#endif
38#endif
39
40#if defined(ABSL_INTERNAL_USE_X86_CPUID)
41#if defined(_WIN32) || defined(_WIN64)
42#include <intrin.h> // NOLINT(build/include_order)
43#pragma intrinsic(__cpuid)
44#else
45// MSVC-equivalent __cpuid intrinsic function.
46static void __cpuid(int cpu_info[4], int info_type) {
47 __asm__ volatile("cpuid \n\t"
48 : "=a"(cpu_info[0]), "=b"(cpu_info[1]), "=c"(cpu_info[2]),
49 "=d"(cpu_info[3])
50 : "a"(info_type), "c"(0));
51}
52#endif
53#endif // ABSL_INTERNAL_USE_X86_CPUID
54
55// On linux, just use the c-library getauxval call.
56#if defined(ABSL_INTERNAL_USE_LINUX_GETAUXVAL)
57
58extern "C" unsigned long getauxval(unsigned long type); // NOLINT(runtime/int)
59
60static uint32_t GetAuxval(uint32_t hwcap_type) {
61 return static_cast<uint32_t>(getauxval(hwcap_type));
62}
63
64#endif
65
66// On android, probe the system's C library for getauxval().
67// This is the same technique used by the android NDK cpu features library
68// as well as the google open-source cpu_features library.
69//
70// TODO(absl-team): Consider implementing a fallback of directly reading
71// /proc/self/auxval.
72#if defined(ABSL_INTERNAL_USE_ANDROID_GETAUXVAL)
73#include <dlfcn.h>
74
75static uint32_t GetAuxval(uint32_t hwcap_type) {
76 // NOLINTNEXTLINE(runtime/int)
77 typedef unsigned long (*getauxval_func_t)(unsigned long);
78
79 dlerror(); // Cleaning error state before calling dlopen.
80 void* libc_handle = dlopen("libc.so", RTLD_NOW);
81 if (!libc_handle) {
82 return 0;
83 }
84 uint32_t result = 0;
85 void* sym = dlsym(libc_handle, "getauxval");
86 if (sym) {
87 getauxval_func_t func;
88 memcpy(&func, &sym, sizeof(func));
89 result = static_cast<uint32_t>((*func)(hwcap_type));
90 }
91 dlclose(libc_handle);
92 return result;
93}
94
95#endif
96
97namespace absl {
98namespace random_internal {
99
100// The default return at the end of the function might be unreachable depending
101// on the configuration. Ignore that warning.
102#if defined(__clang__)
103#pragma clang diagnostic push
104#pragma clang diagnostic ignored "-Wunreachable-code-return"
105#endif
106
107// CPUSupportsRandenHwAes returns whether the CPU is a microarchitecture
108// which supports the crpyto/aes instructions or extensions necessary to use the
109// accelerated RandenHwAes implementation.
110//
111// 1. For x86 it is sufficient to use the CPUID instruction to detect whether
112// the cpu supports AES instructions. Done.
113//
114// Fon non-x86 it is much more complicated.
115//
116// 2. When ABSL_INTERNAL_USE_GETAUXVAL is defined, use getauxval() (either
117// the direct c-library version, or the android probing version which loads
118// libc), and read the hardware capability bits.
119// This is based on the technique used by boringssl uses to detect
120// cpu capabilities, and should allow us to enable crypto in the android
121// builds where it is supported.
122//
123// 3. Use the default for the compiler architecture.
124//
125
126bool CPUSupportsRandenHwAes() {
127#if defined(ABSL_INTERNAL_USE_X86_CPUID)
128 // 1. For x86: Use CPUID to detect the required AES instruction set.
129 int regs[4];
130 __cpuid(reinterpret_cast<int*>(regs), 1);
131 return regs[2] & (1 << 25); // AES
132
133#elif defined(ABSL_INTERNAL_USE_GETAUXVAL)
134 // 2. Use getauxval() to read the hardware bits and determine
135 // cpu capabilities.
136
137#define AT_HWCAP 16
138#define AT_HWCAP2 26
139#if defined(ABSL_ARCH_PPC)
140 // For Power / PPC: Expect that the cpu supports VCRYPTO
141 // See https://members.openpowerfoundation.org/document/dl/576
142 // VCRYPTO should be present in POWER8 >= 2.07.
143 // Uses Linux kernel constants from arch/powerpc/include/uapi/asm/cputable.h
144 static const uint32_t kVCRYPTO = 0x02000000;
145 const uint32_t hwcap = GetAuxval(AT_HWCAP2);
146 return (hwcap & kVCRYPTO) != 0;
147
148#elif defined(ABSL_ARCH_ARM)
149 // For ARM: Require crypto+neon
150 // http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.ddi0500f/CIHBIBBA.html
151 // Uses Linux kernel constants from arch/arm64/include/asm/hwcap.h
152 static const uint32_t kNEON = 1 << 12;
153 uint32_t hwcap = GetAuxval(AT_HWCAP);
154 if ((hwcap & kNEON) == 0) {
155 return false;
156 }
157
158 // And use it again to detect AES.
159 static const uint32_t kAES = 1 << 0;
160 const uint32_t hwcap2 = GetAuxval(AT_HWCAP2);
161 return (hwcap2 & kAES) != 0;
162
163#elif defined(ABSL_ARCH_AARCH64)
164 // For AARCH64: Require crypto+neon
165 // http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.ddi0500f/CIHBIBBA.html
166 static const uint32_t kNEON = 1 << 1;
167 static const uint32_t kAES = 1 << 3;
168 const uint32_t hwcap = GetAuxval(AT_HWCAP);
169 return ((hwcap & kNEON) != 0) && ((hwcap & kAES) != 0);
170#endif
171
172#else // ABSL_INTERNAL_USE_GETAUXVAL
173 // 3. By default, assume that the compiler default.
174 return ABSL_HAVE_ACCELERATED_AES ? true : false;
175
176#endif
177 // NOTE: There are some other techniques that may be worth trying:
178 //
179 // * Use an environment variable: ABSL_RANDOM_USE_HWAES
180 //
181 // * Rely on compiler-generated target-based dispatch.
182 // Using x86/gcc it might look something like this:
183 //
184 // int __attribute__((target("aes"))) HasAes() { return 1; }
185 // int __attribute__((target("default"))) HasAes() { return 0; }
186 //
187 // This does not work on all architecture/compiler combinations.
188 //
189 // * On Linux consider reading /proc/cpuinfo and/or /proc/self/auxv.
190 // These files have lines which are easy to parse; for ARM/AARCH64 it is quite
191 // easy to find the Features: line and extract aes / neon. Likewise for
192 // PPC.
193 //
194 // * Fork a process and test for SIGILL:
195 //
196 // * Many architectures have instructions to read the ISA. Unfortunately
197 // most of those require that the code is running in ring 0 /
198 // protected-mode.
199 //
200 // There are several examples. e.g. Valgrind detects PPC ISA 2.07:
201 // https://github.com/lu-zero/valgrind/blob/master/none/tests/ppc64/test_isa_2_07_part1.c
202 //
203 // MRS <Xt>, ID_AA64ISAR0_EL1 ; Read ID_AA64ISAR0_EL1 into Xt
204 //
205 // uint64_t val;
206 // __asm __volatile("mrs %0, id_aa64isar0_el1" :"=&r" (val));
207 //
208 // * Use a CPUID-style heuristic database.
209 //
210 // * On Apple (__APPLE__), AES is available on Arm v8.
211 // https://stackoverflow.com/questions/45637888/how-to-determine-armv8-features-at-runtime-on-ios
212}
213
214#if defined(__clang__)
215#pragma clang diagnostic pop
216#endif
217
218} // namespace random_internal
219} // namespace absl