1 /* Copyright (c) 2021, Google Inc.
2 *
3 * Permission to use, copy, modify, and/or distribute this software for any
4 * purpose with or without fee is hereby granted, provided that the above
5 * copyright notice and this permission notice appear in all copies.
6 *
7 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
10 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12 * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
14
15 #include "internal.h"
16
17 #if defined(OPENSSL_AARCH64) && defined(OPENSSL_APPLE) && \
18 !defined(OPENSSL_STATIC_ARMCAP)
19
20 #include <sys/sysctl.h>
21 #include <sys/types.h>
22
23 #include <openssl/arm_arch.h>
24
25
26 extern uint32_t OPENSSL_armcap_P;
27
has_hw_feature(const char * name)28 static int has_hw_feature(const char *name) {
29 int value;
30 size_t len = sizeof(value);
31 if (sysctlbyname(name, &value, &len, NULL, 0) != 0) {
32 return 0;
33 }
34 if (len != sizeof(int)) {
35 // This should not happen. All the values queried should be integer-valued.
36 assert(0);
37 return 0;
38 }
39
40 // Per sys/sysctl.h:
41 //
42 // Selectors that return errors are not support on the system. Supported
43 // features will return 1 if they are recommended or 0 if they are supported
44 // but are not expected to help performance. Future versions of these
45 // selectors may return larger values as necessary so it is best to test for
46 // non zero.
47 return value != 0;
48 }
49
OPENSSL_cpuid_setup(void)50 void OPENSSL_cpuid_setup(void) {
51 // Apple ARM64 platforms have NEON and cryptography extensions available
52 // statically, so we do not need to query them. In particular, there sometimes
53 // are no sysctls corresponding to such features. See below.
54 #if !defined(__ARM_NEON) || !defined(__ARM_FEATURE_AES) || \
55 !defined(__ARM_FEATURE_SHA2)
56 #error "NEON and crypto extensions should be statically available."
57 #endif
58 OPENSSL_armcap_P =
59 ARMV7_NEON | ARMV8_AES | ARMV8_PMULL | ARMV8_SHA1 | ARMV8_SHA256;
60
61 // macOS has sysctls named both like "hw.optional.arm.FEAT_SHA512" and like
62 // "hw.optional.armv8_2_sha512". There does not appear to be documentation on
63 // which to use. The "armv8_2_sha512" style omits statically-available
64 // features, while the "FEAT_SHA512" style includes them. However, the
65 // "FEAT_SHA512" style was added in macOS 12, so we use the older style for
66 // better compatibility and handle static features above.
67 if (has_hw_feature("hw.optional.armv8_2_sha512")) {
68 OPENSSL_armcap_P |= ARMV8_SHA512;
69 }
70 }
71
72 #endif // OPENSSL_AARCH64 && OPENSSL_APPLE && !OPENSSL_STATIC_ARMCAP
73