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