randen_detect.cc 7.5 KB

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