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