• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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(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.
__cpuid(int cpu_info[4],int info_type)46 static 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 
58 extern "C" unsigned long getauxval(unsigned long type);  // NOLINT(runtime/int)
59 
GetAuxval(uint32_t hwcap_type)60 static 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 
GetAuxval(uint32_t hwcap_type)75 static 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 
97 namespace absl {
98 ABSL_NAMESPACE_BEGIN
99 namespace random_internal {
100 
101 // The default return at the end of the function might be unreachable depending
102 // on the configuration. Ignore that warning.
103 #if defined(__clang__)
104 #pragma clang diagnostic push
105 #pragma clang diagnostic ignored "-Wunreachable-code-return"
106 #endif
107 
108 // CPUSupportsRandenHwAes returns whether the CPU is a microarchitecture
109 // which supports the crpyto/aes instructions or extensions necessary to use the
110 // accelerated RandenHwAes implementation.
111 //
112 // 1. For x86 it is sufficient to use the CPUID instruction to detect whether
113 //    the cpu supports AES instructions. Done.
114 //
115 // Fon non-x86 it is much more complicated.
116 //
117 // 2. When ABSL_INTERNAL_USE_GETAUXVAL is defined, use getauxval() (either
118 //    the direct c-library version, or the android probing version which loads
119 //    libc), and read the hardware capability bits.
120 //    This is based on the technique used by boringssl uses to detect
121 //    cpu capabilities, and should allow us to enable crypto in the android
122 //    builds where it is supported.
123 //
124 // 3. Use the default for the compiler architecture.
125 //
126 
CPUSupportsRandenHwAes()127 bool CPUSupportsRandenHwAes() {
128 #if defined(ABSL_INTERNAL_USE_X86_CPUID)
129   // 1. For x86: Use CPUID to detect the required AES instruction set.
130   int regs[4];
131   __cpuid(reinterpret_cast<int*>(regs), 1);
132   return regs[2] & (1 << 25);  // AES
133 
134 #elif defined(ABSL_INTERNAL_USE_GETAUXVAL)
135   // 2. Use getauxval() to read the hardware bits and determine
136   // cpu capabilities.
137 
138 #define AT_HWCAP 16
139 #define AT_HWCAP2 26
140 #if defined(ABSL_ARCH_PPC)
141   // For Power / PPC: Expect that the cpu supports VCRYPTO
142   // See https://members.openpowerfoundation.org/document/dl/576
143   // VCRYPTO should be present in POWER8 >= 2.07.
144   // Uses Linux kernel constants from arch/powerpc/include/uapi/asm/cputable.h
145   static const uint32_t kVCRYPTO = 0x02000000;
146   const uint32_t hwcap = GetAuxval(AT_HWCAP2);
147   return (hwcap & kVCRYPTO) != 0;
148 
149 #elif defined(ABSL_ARCH_ARM)
150   // For ARM: Require crypto+neon
151   // http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.ddi0500f/CIHBIBBA.html
152   // Uses Linux kernel constants from arch/arm64/include/asm/hwcap.h
153   static const uint32_t kNEON = 1 << 12;
154   uint32_t hwcap = GetAuxval(AT_HWCAP);
155   if ((hwcap & kNEON) == 0) {
156     return false;
157   }
158 
159   // And use it again to detect AES.
160   static const uint32_t kAES = 1 << 0;
161   const uint32_t hwcap2 = GetAuxval(AT_HWCAP2);
162   return (hwcap2 & kAES) != 0;
163 
164 #elif defined(ABSL_ARCH_AARCH64)
165   // For AARCH64: Require crypto+neon
166   // http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.ddi0500f/CIHBIBBA.html
167   static const uint32_t kNEON = 1 << 1;
168   static const uint32_t kAES = 1 << 3;
169   const uint32_t hwcap = GetAuxval(AT_HWCAP);
170   return ((hwcap & kNEON) != 0) && ((hwcap & kAES) != 0);
171 #endif
172 
173 #else  // ABSL_INTERNAL_USE_GETAUXVAL
174   // 3. By default, assume that the compiler default.
175   return ABSL_HAVE_ACCELERATED_AES ? true : false;
176 
177 #endif
178   // NOTE: There are some other techniques that may be worth trying:
179   //
180   // * Use an environment variable: ABSL_RANDOM_USE_HWAES
181   //
182   // * Rely on compiler-generated target-based dispatch.
183   // Using x86/gcc it might look something like this:
184   //
185   // int __attribute__((target("aes"))) HasAes() { return 1; }
186   // int __attribute__((target("default"))) HasAes() { return 0; }
187   //
188   // This does not work on all architecture/compiler combinations.
189   //
190   // * On Linux consider reading /proc/cpuinfo and/or /proc/self/auxv.
191   // These files have lines which are easy to parse; for ARM/AARCH64 it is quite
192   // easy to find the Features: line and extract aes / neon. Likewise for
193   // PPC.
194   //
195   // * Fork a process and test for SIGILL:
196   //
197   // * Many architectures have instructions to read the ISA. Unfortunately
198   //   most of those require that the code is running in ring 0 /
199   //   protected-mode.
200   //
201   //   There are several examples. e.g. Valgrind detects PPC ISA 2.07:
202   //   https://github.com/lu-zero/valgrind/blob/master/none/tests/ppc64/test_isa_2_07_part1.c
203   //
204   //   MRS <Xt>, ID_AA64ISAR0_EL1 ; Read ID_AA64ISAR0_EL1 into Xt
205   //
206   //   uint64_t val;
207   //   __asm __volatile("mrs %0, id_aa64isar0_el1" :"=&r" (val));
208   //
209   // * Use a CPUID-style heuristic database.
210   //
211   // * On Apple (__APPLE__), AES is available on Arm v8.
212   //   https://stackoverflow.com/questions/45637888/how-to-determine-armv8-features-at-runtime-on-ios
213 }
214 
215 #if defined(__clang__)
216 #pragma clang diagnostic pop
217 #endif
218 
219 }  // namespace random_internal
220 ABSL_NAMESPACE_END
221 }  // namespace absl
222