randen_detect.cc 7.9 KB

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