cpufeatures-0.2.16/.cargo_vcs_info.json0000644000000001510000000000100134450ustar { "git": { "sha1": "b0d1a8a149392c041f1b8ae4355b00996d81b2da" }, "path_in_vcs": "cpufeatures" }cpufeatures-0.2.16/CHANGELOG.md000064400000000000000000000105601046102023000140530ustar 00000000000000# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## 0.2.16 (2024-11-22) ### Fixed - `cfg` for freestanding x86 targets ([#1137]) [#1137]: https://github.com/RustCrypto/utils/pull/1137 ## 0.2.15 (2024-11-11) ### Fixed - Relax XSAVE checks ([#1130]) [#1130]: https://github.com/RustCrypto/utils/pull/1130 ## 0.2.14 (2024-09-05) ### Added - Support for detecting Data Independent Timing (DIT) on AArch64 ([#1100], [#1101]) [#1100]: https://github.com/RustCrypto/utils/pull/1100 [#1101]: https://github.com/RustCrypto/utils/pull/1101 ## 0.2.13 (2024-08-12) ### Changed - Use `#[cold]` for initialization code ([#1096]) [#1096]: https://github.com/RustCrypto/utils/pull/1096 ## 0.2.12 (2024-01-04) ### Added - Support for x86-64 AVX-512 target features: `gfni`, `vaes`, `vpclmulqdq`, `avx512bitalg`, `avx512vpopcntdq` ([#1035]) [#1035]: https://github.com/RustCrypto/utils/pull/1035 ## 0.2.11 (2023-10-26) ### Added - Support for AArch64's `sm4` target feature ([#972]) [#972]: https://github.com/RustCrypto/utils/pull/972 ## 0.2.10 (2023-10-20) ### Added - LoongArch64 target support ([#955]) [#955]: https://github.com/RustCrypto/utils/pull/955 ## 0.2.9 (2023-07-05) ### Added - Support for `avx512vbmi` and `avx512vbmi2` target features ([#926]) [#926]: https://github.com/RustCrypto/utils/pull/926 ## 0.2.8 (2023-06-15) ### Fixed - Check OS register support on x86 targets ([#919]) [#919]: https://github.com/RustCrypto/utils/issues/919 ## 0.2.7 (2023-04-20) ### Added - Support freestanding/UEFI `x86` targets ([#821]) [#821]: https://github.com/RustCrypto/utils/issues/821 ## 0.2.6 (2023-03-24) ### Added - Support dynamic feature detection on iOS and derivative platforms ([#848]) - Support for detecting AVX-512 target features ([#862]) [#848]: https://github.com/RustCrypto/utils/issues/848 [#862]: https://github.com/RustCrypto/utils/pull/862 ## 0.2.5 (2022-09-04) ### Fixed - Add workaround for [CPUID bug] in `std` ([#800]) [CPUID bug]: https://github.com/rust-lang/rust/issues/101346 [#800]: https://github.com/RustCrypto/utils/pull/800 ## 0.2.4 (2022-08-22) [YANKED] - Re-release v0.2.3 without any changes to fix [#795] ([#796]) [#795]: https://github.com/RustCrypto/utils/issues/795 [#796]: https://github.com/RustCrypto/utils/pull/796 ## 0.2.3 (2022-08-18) [YANKED] ### Changed - Update `libc` version to v0.2.95 ([#789]) - Disable all target features under MIRI ([#779]) - Check AVX availability when detecting AVX2 and FMA ([#792]) [#779]: https://github.com/RustCrypto/utils/pull/779 [#789]: https://github.com/RustCrypto/utils/pull/789 [#792]: https://github.com/RustCrypto/utils/pull/792 ## 0.2.2 (2022-03-18) [YANKED] ### Added - Support for Android on `aarch64` ([#752]) ### Removed - Vestigial code around `crypto` target feature ([#600]) [#600]: https://github.com/RustCrypto/utils/pull/600 [#752]: https://github.com/RustCrypto/utils/pull/752 ## 0.2.1 (2021-08-26) [YANKED] ### Changed - Revert [#583] "Use from_bytes_with_nul for string check" ([#597]) [#583]: https://github.com/RustCrypto/utils/pull/583 [#597]: https://github.com/RustCrypto/utils/pull/597 ## 0.2.0 (2021-08-26) [YANKED] ### Removed - AArch64 `crypto` target feature ([#594]) [#594]: https://github.com/RustCrypto/utils/pull/594 ## 0.1.5 (2021-06-21) ### Added - iOS support ([#435], [#501]) ### Changed - Map `aarch64` HWCAPs to target features; add `crypto` ([#456]) [#435]: https://github.com/RustCrypto/utils/pull/435 [#456]: https://github.com/RustCrypto/utils/pull/456 [#501]: https://github.com/RustCrypto/utils/pull/501 ## 0.1.4 (2021-05-14) ### Added - Support compiling on non-Linux/macOS aarch64 targets ([#408]) [#408]: https://github.com/RustCrypto/utils/pull/408 ## 0.1.3 (2021-05-13) ### Removed - `neon` on `aarch64` targets: already enabled by default ([#406]) [#406]: https://github.com/RustCrypto/utils/pull/406 ## 0.1.2 (2021-05-13) [YANKED] ### Added - `neon` feature detection on `aarch64` targets ([#403]) ### Fixed - Support for `musl`-based targets ([#403]) [#403]: https://github.com/RustCrypto/utils/pull/403 ## 0.1.1 (2021-05-06) ### Added - `aarch64` support for Linux and macOS/M4 targets ([#393]) [#393]: https://github.com/RustCrypto/utils/pull/393 ## 0.1.0 (2021-04-29) - Initial release cpufeatures-0.2.16/Cargo.lock0000644000000005660000000000100114320ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "cpufeatures" version = "0.2.16" dependencies = [ "libc", ] [[package]] name = "libc" version = "0.2.159" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "561d97a539a36e26a9a5fad1ea11a3039a67714694aaa379433e580854bc3dc5" cpufeatures-0.2.16/Cargo.toml0000644000000033100000000000100114430ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2018" name = "cpufeatures" version = "0.2.16" authors = ["RustCrypto Developers"] build = false autolib = false autobins = false autoexamples = false autotests = false autobenches = false description = """ Lightweight runtime CPU feature detection for aarch64, loongarch64, and x86/x86_64 targets, with no_std support and support for mobile targets including Android and iOS """ documentation = "https://docs.rs/cpufeatures" readme = "README.md" keywords = [ "cpuid", "target-feature", ] categories = [ "hardware-support", "no-std", ] license = "MIT OR Apache-2.0" repository = "https://github.com/RustCrypto/utils" resolver = "2" [lib] name = "cpufeatures" path = "src/lib.rs" [[test]] name = "aarch64" path = "tests/aarch64.rs" [[test]] name = "loongarch64" path = "tests/loongarch64.rs" [[test]] name = "x86" path = "tests/x86.rs" [target.aarch64-linux-android.dependencies.libc] version = "0.2.155" [target.'cfg(all(target_arch = "aarch64", target_os = "linux"))'.dependencies.libc] version = "0.2.155" [target.'cfg(all(target_arch = "aarch64", target_vendor = "apple"))'.dependencies.libc] version = "0.2.155" [target.'cfg(all(target_arch = "loongarch64", target_os = "linux"))'.dependencies.libc] version = "0.2.155" cpufeatures-0.2.16/Cargo.toml.orig000064400000000000000000000015671046102023000151400ustar 00000000000000[package] name = "cpufeatures" version = "0.2.16" description = """ Lightweight runtime CPU feature detection for aarch64, loongarch64, and x86/x86_64 targets, with no_std support and support for mobile targets including Android and iOS """ authors = ["RustCrypto Developers"] license = "MIT OR Apache-2.0" documentation = "https://docs.rs/cpufeatures" repository = "https://github.com/RustCrypto/utils" keywords = ["cpuid", "target-feature"] categories = ["hardware-support", "no-std"] edition = "2018" readme = "README.md" [target.'cfg(all(target_arch = "aarch64", target_vendor = "apple"))'.dependencies] libc = "0.2.155" [target.'cfg(all(target_arch = "aarch64", target_os = "linux"))'.dependencies] libc = "0.2.155" [target.'cfg(all(target_arch = "loongarch64", target_os = "linux"))'.dependencies] libc = "0.2.155" [target.aarch64-linux-android.dependencies] libc = "0.2.155" cpufeatures-0.2.16/LICENSE-APACHE000064400000000000000000000251411046102023000141670ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. cpufeatures-0.2.16/LICENSE-MIT000064400000000000000000000020651046102023000136770ustar 00000000000000Copyright (c) 2020 The RustCrypto Project Developers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. cpufeatures-0.2.16/README.md000064400000000000000000000060351046102023000135230ustar 00000000000000# [RustCrypto]: CPU Feature Detection [![crate][crate-image]][crate-link] [![Docs][docs-image]][docs-link] ![Apache2/MIT licensed][license-image] ![Rust Version][rustc-image] [![Project Chat][chat-image]][chat-link] [![Build Status][build-image]][build-link] Lightweight and efficient runtime CPU feature detection for `aarch64`, `loongarch64`, and `x86`/`x86_64` targets. Supports `no_std` as well as mobile targets including iOS and Android, providing an alternative to the `std`-dependent `is_x86_feature_detected!` macro. [Documentation][docs-link] # Supported target architectures *NOTE: target features with an asterisk are unstable (nightly-only) and subject to change to match upstream name changes in the Rust standard library. ## `aarch64` Linux, iOS, and macOS/ARM only (ARM64 does not support OS-independent feature detection) Target features: - `aes`* - `sha2`* - `sha3`* ## `loongarch64` Linux only (LoongArch64 does not support OS-independent feature detection) Target features: - `lam`* - `ual`* - `fpu`* - `lsx`* - `lasx`* - `crc32`* - `complex`* - `crypto`* - `lvz`* - `lbt.x86`* - `lbt.arm`* - `lbt.mips`* - `ptw`* ## `x86`/`x86_64` OS independent and `no_std`-friendly Target features: - `adx` - `aes` - `avx` - `avx2` - `avx512bw`* - `avx512cd`* - `avx512dq`* - `avx512er`* - `avx512f`* - `avx512ifma`* - `avx512pf`* - `avx512vl`* - `avx512vbmi`* - `avx512vbmi2`* - `bmi1` - `bmi2` - `fma`, - `mmx` - `pclmulqdq` - `popcnt` - `rdrand` - `rdseed` - `sgx` - `sha` - `sse` - `sse2` - `sse3` - `sse4.1` - `sse4.2` - `ssse3` If you would like detection support for a target feature which is not on this list, please [open a GitHub issue]. ## License Licensed under either of: * [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0) * [MIT license](http://opensource.org/licenses/MIT) at your option. ### Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. [//]: # (badges) [crate-image]: https://img.shields.io/crates/v/cpufeatures.svg [crate-link]: https://crates.io/crates/cpufeatures [docs-image]: https://docs.rs/cpufeatures/badge.svg [docs-link]: https://docs.rs/cpufeatures/ [license-image]: https://img.shields.io/badge/license-Apache2.0/MIT-blue.svg [rustc-image]: https://img.shields.io/badge/rustc-1.40+-blue.svg [chat-image]: https://img.shields.io/badge/zulip-join_chat-blue.svg [chat-link]: https://rustcrypto.zulipchat.com/#narrow/stream/260052-utils [build-image]: https://github.com/RustCrypto/utils/workflows/cpufeatures/badge.svg?branch=master&event=push [build-link]: https://github.com/RustCrypto/utils/actions/workflows/cpufeatures.yml [//]: # (general links) [RustCrypto]: https://github.com/rustcrypto [RustCrypto/utils#378]: https://github.com/RustCrypto/utils/issues/378 [open a GitHub issue]: https://github.com/RustCrypto/utils/issues/new?title=cpufeatures:%20requesting%20support%20for%20CHANGEME%20target%20feature cpufeatures-0.2.16/src/aarch64.rs000064400000000000000000000121131046102023000146230ustar 00000000000000//! ARM64 CPU feature detection support. //! //! Unfortunately ARM instructions to detect CPU features cannot be called from //! unprivileged userspace code, so this implementation relies on OS-specific //! APIs for feature detection. // Evaluate the given `$body` expression any of the supplied target features // are not enabled. Otherwise returns true. #[macro_export] #[doc(hidden)] macro_rules! __unless_target_features { ($($tf:tt),+ => $body:expr ) => { { #[cfg(not(all($(target_feature=$tf,)*)))] $body #[cfg(all($(target_feature=$tf,)*))] true } }; } // Linux runtime detection of target CPU features using `getauxval`. #[cfg(any(target_os = "linux", target_os = "android"))] #[macro_export] #[doc(hidden)] macro_rules! __detect_target_features { ($($tf:tt),+) => {{ let hwcaps = $crate::aarch64::getauxval_hwcap(); $($crate::check!(hwcaps, $tf) & )+ true }}; } /// Linux helper function for calling `getauxval` to get `AT_HWCAP`. #[cfg(any(target_os = "linux", target_os = "android"))] pub fn getauxval_hwcap() -> u64 { unsafe { libc::getauxval(libc::AT_HWCAP) } } // Apple platform's runtime detection of target CPU features using `sysctlbyname`. #[cfg(target_vendor = "apple")] #[macro_export] #[doc(hidden)] macro_rules! __detect_target_features { ($($tf:tt),+) => {{ $($crate::check!($tf) & )+ true }}; } // Linux `expand_check_macro` #[cfg(any(target_os = "linux", target_os = "android"))] macro_rules! __expand_check_macro { ($(($name:tt, $hwcap:ident)),* $(,)?) => { #[macro_export] #[doc(hidden)] macro_rules! check { $( ($hwcaps:expr, $name) => { (($hwcaps & $crate::aarch64::hwcaps::$hwcap) != 0) }; )* } }; } // Linux `expand_check_macro` #[cfg(any(target_os = "linux", target_os = "android"))] __expand_check_macro! { ("aes", AES), // Enable AES support. ("dit", DIT), // Enable DIT support. ("sha2", SHA2), // Enable SHA1 and SHA256 support. ("sha3", SHA3), // Enable SHA512 and SHA3 support. ("sm4", SM4), // Enable SM3 and SM4 support. } /// Linux hardware capabilities mapped to target features. /// /// Note that LLVM target features are coarser grained than what Linux supports /// and imply more capabilities under each feature. This module attempts to /// provide that mapping accordingly. /// /// See this issue for more info: #[cfg(any(target_os = "linux", target_os = "android"))] pub mod hwcaps { use libc::c_ulong; pub const AES: c_ulong = libc::HWCAP_AES | libc::HWCAP_PMULL; pub const DIT: c_ulong = libc::HWCAP_DIT; pub const SHA2: c_ulong = libc::HWCAP_SHA2; pub const SHA3: c_ulong = libc::HWCAP_SHA3 | libc::HWCAP_SHA512; pub const SM4: c_ulong = libc::HWCAP_SM3 | libc::HWCAP_SM4; } // Apple OS (macOS, iOS, watchOS, and tvOS) `check!` macro. // // NOTE: several of these instructions (e.g. `aes`, `sha2`) can be assumed to // be present on all Apple ARM64 hardware. // // Newer CPU instructions now have nodes within sysctl's `hw.optional` // namespace, however the ones that do not can safely be assumed to be // present on all Apple ARM64 devices, now and for the foreseeable future. // // See discussion on this issue for more information: // #[cfg(target_vendor = "apple")] #[macro_export] #[doc(hidden)] macro_rules! check { ("aes") => { true }; ("dit") => { // https://developer.apple.com/documentation/xcode/writing-arm64-code-for-apple-platforms#Enable-DIT-for-constant-time-cryptographic-operations unsafe { $crate::aarch64::sysctlbyname(b"hw.optional.arm.FEAT_DIT\0") } }; ("sha2") => { true }; ("sha3") => { unsafe { // `sha3` target feature implies SHA-512 as well $crate::aarch64::sysctlbyname(b"hw.optional.armv8_2_sha512\0") && $crate::aarch64::sysctlbyname(b"hw.optional.armv8_2_sha3\0") } }; ("sm4") => { false }; } /// Apple helper function for calling `sysctlbyname`. #[cfg(target_vendor = "apple")] pub unsafe fn sysctlbyname(name: &[u8]) -> bool { assert_eq!( name.last().cloned(), Some(0), "name is not NUL terminated: {:?}", name ); let mut value: u32 = 0; let mut size = core::mem::size_of::(); let rc = libc::sysctlbyname( name.as_ptr() as *const i8, &mut value as *mut _ as *mut libc::c_void, &mut size, core::ptr::null_mut(), 0, ); assert_eq!(size, 4, "unexpected sysctlbyname(3) result size"); assert_eq!(rc, 0, "sysctlbyname returned error code: {}", rc); value != 0 } // On other targets, runtime CPU feature detection is unavailable #[cfg(not(any(target_vendor = "apple", target_os = "linux", target_os = "android",)))] #[macro_export] #[doc(hidden)] macro_rules! __detect_target_features { ($($tf:tt),+) => { false }; } cpufeatures-0.2.16/src/lib.rs000064400000000000000000000137251046102023000141530ustar 00000000000000//! This crate provides macros for runtime CPU feature detection. It's intended //! as a stopgap until Rust [RFC 2725] adding first-class target feature detection //! macros to `libcore` is implemented. //! //! # Supported target architectures //! //! *NOTE: target features with an asterisk are unstable (nightly-only) and //! subject to change to match upstream name changes in the Rust standard //! library. //! //! ## `aarch64` //! //! Linux, iOS, and macOS/ARM only (ARM64 does not support OS-independent feature detection) //! //! Target features: //! //! - `aes`* //! - `sha2`* //! - `sha3`* //! //! Linux only //! //! - `sm4`* //! //! ## `loongarch64` //! //! Linux only (LoongArch64 does not support OS-independent feature detection) //! //! Target features: //! //! - `lam`* //! - `ual`* //! - `fpu`* //! - `lsx`* //! - `lasx`* //! - `crc32`* //! - `complex`* //! - `crypto`* //! - `lvz`* //! - `lbt.x86`* //! - `lbt.arm`* //! - `lbt.mips`* //! - `ptw`* //! //! ## `x86`/`x86_64` //! //! OS independent and `no_std`-friendly //! //! Target features: //! //! - `adx` //! - `aes` //! - `avx` //! - `avx2` //! - `avx512bw`* //! - `avx512cd`* //! - `avx512dq`* //! - `avx512er`* //! - `avx512f`* //! - `avx512ifma`* //! - `avx512pf`* //! - `avx512vl`* //! - `bmi1` //! - `bmi2` //! - `fma`, //! - `mmx` //! - `pclmulqdq` //! - `popcnt` //! - `rdrand` //! - `rdseed` //! - `sgx` //! - `sha` //! - `sse` //! - `sse2` //! - `sse3` //! - `sse4.1` //! - `sse4.2` //! - `ssse3` //! //! If you would like detection support for a target feature which is not on //! this list, please [open a GitHub issue][gh]. //! //! # Example //! ``` //! # #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] //! # { //! // This macro creates `cpuid_aes_sha` module //! cpufeatures::new!(cpuid_aes_sha, "aes", "sha"); //! //! // `token` is a Zero Sized Type (ZST) value, which guarantees //! // that underlying static storage got properly initialized, //! // which allows to omit initialization branch //! let token: cpuid_aes_sha::InitToken = cpuid_aes_sha::init(); //! //! if token.get() { //! println!("CPU supports both SHA and AES extensions"); //! } else { //! println!("SHA and AES extensions are not supported"); //! } //! //! // If stored value needed only once you can get stored value //! // omitting the token //! let val = cpuid_aes_sha::get(); //! assert_eq!(val, token.get()); //! //! // Additionally you can get both token and value //! let (token, val) = cpuid_aes_sha::init_get(); //! assert_eq!(val, token.get()); //! # } //! ``` //! //! Note that if all tested target features are enabled via compiler options //! (e.g. by using `RUSTFLAGS`), the `get` method will always return `true` //! and `init` will not use CPUID instruction. Such behavior allows //! compiler to completely eliminate fallback code. //! //! After first call macro caches result and returns it in subsequent //! calls, thus runtime overhead for them is minimal. //! //! [RFC 2725]: https://github.com/rust-lang/rfcs/pull/2725 //! [gh]: https://github.com/RustCrypto/utils/issues/new?title=cpufeatures:%20requesting%20support%20for%20CHANGEME%20target%20feature #![no_std] #![doc( html_logo_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg", html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg" )] #[cfg(not(miri))] #[cfg(target_arch = "aarch64")] #[doc(hidden)] pub mod aarch64; #[cfg(not(miri))] #[cfg(target_arch = "loongarch64")] #[doc(hidden)] pub mod loongarch64; #[cfg(not(miri))] #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] mod x86; #[cfg(miri)] mod miri; #[cfg(not(any( target_arch = "aarch64", target_arch = "loongarch64", target_arch = "x86", target_arch = "x86_64" )))] compile_error!("This crate works only on `aarch64`, `loongarch64`, `x86`, and `x86-64` targets."); /// Create module with CPU feature detection code. #[macro_export] macro_rules! new { ($mod_name:ident, $($tf:tt),+ $(,)?) => { mod $mod_name { use core::sync::atomic::{AtomicU8, Ordering::Relaxed}; const UNINIT: u8 = u8::max_value(); static STORAGE: AtomicU8 = AtomicU8::new(UNINIT); /// Initialization token #[derive(Copy, Clone, Debug)] pub struct InitToken(()); impl InitToken { /// Get initialized value #[inline(always)] pub fn get(&self) -> bool { $crate::__unless_target_features! { $($tf),+ => { STORAGE.load(Relaxed) == 1 } } } } /// Get stored value and initialization token, /// initializing underlying storage if needed. #[inline] pub fn init_get() -> (InitToken, bool) { let res = $crate::__unless_target_features! { $($tf),+ => { #[cold] fn init_inner() -> bool { let res = $crate::__detect_target_features!($($tf),+); STORAGE.store(res as u8, Relaxed); res } // Relaxed ordering is fine, as we only have a single atomic variable. let val = STORAGE.load(Relaxed); if val == UNINIT { init_inner() } else { val == 1 } } }; (InitToken(()), res) } /// Initialize underlying storage if needed and get initialization token. #[inline] pub fn init() -> InitToken { init_get().0 } /// Initialize underlying storage if needed and get stored value. #[inline] pub fn get() -> bool { init_get().1 } } }; } cpufeatures-0.2.16/src/loongarch64.rs000064400000000000000000000070541046102023000155310ustar 00000000000000//! LoongArch64 CPU feature detection support. //! //! This implementation relies on OS-specific APIs for feature detection. // Evaluate the given `$body` expression any of the supplied target features // are not enabled. Otherwise returns true. #[macro_export] #[doc(hidden)] macro_rules! __unless_target_features { ($($tf:tt),+ => $body:expr ) => { { #[cfg(not(all($(target_feature=$tf,)*)))] $body #[cfg(all($(target_feature=$tf,)*))] true } }; } // Linux runtime detection of target CPU features using `getauxval`. #[cfg(target_os = "linux")] #[macro_export] #[doc(hidden)] macro_rules! __detect_target_features { ($($tf:tt),+) => {{ let hwcaps = $crate::loongarch64::getauxval_hwcap(); $($crate::check!(hwcaps, $tf) & )+ true }}; } /// Linux helper function for calling `getauxval` to get `AT_HWCAP`. #[cfg(target_os = "linux")] pub fn getauxval_hwcap() -> u64 { unsafe { libc::getauxval(libc::AT_HWCAP) } } // Linux `expand_check_macro` #[cfg(target_os = "linux")] macro_rules! __expand_check_macro { ($(($name:tt, $hwcap:ident)),* $(,)?) => { #[macro_export] #[doc(hidden)] macro_rules! check { $( ($hwcaps:expr, $name) => { (($hwcaps & $crate::loongarch64::hwcaps::$hwcap) != 0) }; )* } }; } // Linux `expand_check_macro` #[cfg(target_os = "linux")] __expand_check_macro! { ("cpucfg", CPUCFG), // Enable CPUCFG support. ("lam", LAM), // Enable LAM support. ("ual", UAL), // Enable UAL support. ("fpu", FPU), // Enable FPU support. ("lsx", LSX), // Enable LSX support. ("lasx", LASX), // Enable LASX support. ("crc32", CRC32), // Enable CRC32 support. ("complex", COMPLEX), // Enable COMPLEX support. ("crypto", CRYPTO), // Enable CRYPTO support. ("lvz", LVZ), // Enable LVZ support. ("lbt.x86", LBT_X86), // Enable LBT_X86 support. ("lbt.arm", LBT_ARM), // Enable LBT_ARM support. ("lbt.mips", LBT_MIPS), // Enable LBT_MIPS support. ("ptw", PTW), // Enable PTW support. } /// Linux hardware capabilities mapped to target features. /// /// Note that LLVM target features are coarser grained than what Linux supports /// and imply more capabilities under each feature. This module attempts to /// provide that mapping accordingly. #[cfg(target_os = "linux")] pub mod hwcaps { use libc::c_ulong; pub const CPUCFG: c_ulong = libc::HWCAP_LOONGARCH_CPUCFG; pub const LAM: c_ulong = libc::HWCAP_LOONGARCH_LAM; pub const UAL: c_ulong = libc::HWCAP_LOONGARCH_UAL; pub const FPU: c_ulong = libc::HWCAP_LOONGARCH_FPU; pub const LSX: c_ulong = libc::HWCAP_LOONGARCH_LSX; pub const LASX: c_ulong = libc::HWCAP_LOONGARCH_LASX; pub const CRC32: c_ulong = libc::HWCAP_LOONGARCH_CRC32; pub const COMPLEX: c_ulong = libc::HWCAP_LOONGARCH_COMPLEX; pub const CRYPTO: c_ulong = libc::HWCAP_LOONGARCH_CRYPTO; pub const LVZ: c_ulong = libc::HWCAP_LOONGARCH_LVZ; pub const LBT_X86: c_ulong = libc::HWCAP_LOONGARCH_LBT_X86; pub const LBT_ARM: c_ulong = libc::HWCAP_LOONGARCH_LBT_ARM; pub const LBT_MIPS: c_ulong = libc::HWCAP_LOONGARCH_LBT_MIPS; pub const PTW: c_ulong = libc::HWCAP_LOONGARCH_PTW; } // On other targets, runtime CPU feature detection is unavailable #[cfg(not(target_os = "linux"))] #[macro_export] #[doc(hidden)] macro_rules! __detect_target_features { ($($tf:tt),+) => { false }; } cpufeatures-0.2.16/src/miri.rs000064400000000000000000000006201046102023000143330ustar 00000000000000//! Minimal miri support. //! //! Miri is an interpreter, and though it tries to emulate the target CPU //! it does not support any target features. #[macro_export] #[doc(hidden)] macro_rules! __unless_target_features { ($($tf:tt),+ => $body:expr ) => { false }; } #[macro_export] #[doc(hidden)] macro_rules! __detect_target_features { ($($tf:tt),+) => { false }; } cpufeatures-0.2.16/src/x86.rs000064400000000000000000000114531046102023000140260ustar 00000000000000//! x86/x86-64 CPU feature detection support. //! //! Portable, `no_std`-friendly implementation that relies on the x86 `CPUID` //! instruction for feature detection. /// Evaluate the given `$body` expression any of the supplied target features /// are not enabled. Otherwise returns true. /// /// The `$body` expression is not evaluated on SGX targets, and returns false /// on these targets unless *all* supplied target features are enabled. #[macro_export] #[doc(hidden)] macro_rules! __unless_target_features { ($($tf:tt),+ => $body:expr ) => {{ #[cfg(not(all($(target_feature=$tf,)*)))] { #[cfg(not(any(target_env = "sgx", target_os = "none", target_os = "uefi")))] $body // CPUID is not available on SGX. Freestanding and UEFI targets // do not support SIMD features with default compilation flags. #[cfg(any(target_env = "sgx", target_os = "none", target_os = "uefi"))] false } #[cfg(all($(target_feature=$tf,)*))] true }}; } /// Use CPUID to detect the presence of all supplied target features. #[macro_export] #[doc(hidden)] macro_rules! __detect_target_features { ($($tf:tt),+) => {{ #[cfg(target_arch = "x86")] use core::arch::x86::{__cpuid, __cpuid_count, CpuidResult}; #[cfg(target_arch = "x86_64")] use core::arch::x86_64::{__cpuid, __cpuid_count, CpuidResult}; // These wrappers are workarounds around // https://github.com/rust-lang/rust/issues/101346 // // DO NOT remove it until MSRV is bumped to a version // with the issue fix (at least 1.64). #[inline(never)] unsafe fn cpuid(leaf: u32) -> CpuidResult { __cpuid(leaf) } #[inline(never)] unsafe fn cpuid_count(leaf: u32, sub_leaf: u32) -> CpuidResult { __cpuid_count(leaf, sub_leaf) } let cr = unsafe { [cpuid(1), cpuid_count(7, 0)] }; $($crate::check!(cr, $tf) & )+ true }}; } /// Check that OS supports required SIMD registers #[macro_export] #[doc(hidden)] macro_rules! __xgetbv { ($cr:expr, $mask:expr) => {{ #[cfg(target_arch = "x86")] use core::arch::x86 as arch; #[cfg(target_arch = "x86_64")] use core::arch::x86_64 as arch; // Check bits 26 and 27 let xmask = 0b11 << 26; let xsave = $cr[0].ecx & xmask == xmask; if xsave { let xcr0 = unsafe { arch::_xgetbv(arch::_XCR_XFEATURE_ENABLED_MASK) }; (xcr0 & $mask) == $mask } else { false } }}; } macro_rules! __expand_check_macro { ($(($name:tt, $reg_cap:tt $(, $i:expr, $reg:ident, $offset:expr)*)),* $(,)?) => { #[macro_export] #[doc(hidden)] macro_rules! check { $( ($cr:expr, $name) => {{ // Register bits are listed here: // https://wiki.osdev.org/CPU_Registers_x86#Extended_Control_Registers let reg_cap = match $reg_cap { // Bit 1 "xmm" => $crate::__xgetbv!($cr, 0b10), // Bits 1 and 2 "ymm" => $crate::__xgetbv!($cr, 0b110), // Bits 1, 2, 5, 6, and 7 "zmm" => $crate::__xgetbv!($cr, 0b1110_0110), _ => true, }; reg_cap $( & ($cr[$i].$reg & (1 << $offset) != 0) )* }}; )* } }; } __expand_check_macro! { ("sse3", "", 0, ecx, 0), ("pclmulqdq", "", 0, ecx, 1), ("ssse3", "", 0, ecx, 9), ("fma", "ymm", 0, ecx, 12, 0, ecx, 28), ("sse4.1", "", 0, ecx, 19), ("sse4.2", "", 0, ecx, 20), ("popcnt", "", 0, ecx, 23), ("aes", "", 0, ecx, 25), ("avx", "xmm", 0, ecx, 28), ("rdrand", "", 0, ecx, 30), ("mmx", "", 0, edx, 23), ("sse", "", 0, edx, 25), ("sse2", "", 0, edx, 26), ("sgx", "", 1, ebx, 2), ("bmi1", "", 1, ebx, 3), ("bmi2", "", 1, ebx, 8), ("avx2", "ymm", 1, ebx, 5, 0, ecx, 28), ("avx512f", "zmm", 1, ebx, 16), ("avx512dq", "zmm", 1, ebx, 17), ("rdseed", "", 1, ebx, 18), ("adx", "", 1, ebx, 19), ("avx512ifma", "zmm", 1, ebx, 21), ("avx512pf", "zmm", 1, ebx, 26), ("avx512er", "zmm", 1, ebx, 27), ("avx512cd", "zmm", 1, ebx, 28), ("sha", "", 1, ebx, 29), ("avx512bw", "zmm", 1, ebx, 30), ("avx512vl", "zmm", 1, ebx, 31), ("avx512vbmi", "zmm", 1, ecx, 1), ("avx512vbmi2", "zmm", 1, ecx, 6), ("gfni", "zmm", 1, ecx, 8), ("vaes", "zmm", 1, ecx, 9), ("vpclmulqdq", "zmm", 1, ecx, 10), ("avx512bitalg", "zmm", 1, ecx, 12), ("avx512vpopcntdq", "zmm", 1, ecx, 14), } cpufeatures-0.2.16/tests/aarch64.rs000064400000000000000000000005171046102023000152030ustar 00000000000000//! ARM64 tests #![cfg(target_arch = "aarch64")] cpufeatures::new!(armcaps, "aes", "sha2", "sha3", "sm4"); #[test] fn init() { let token: armcaps::InitToken = armcaps::init(); assert_eq!(token.get(), armcaps::get()); } #[test] fn init_get() { let (token, val) = armcaps::init_get(); assert_eq!(val, token.get()); } cpufeatures-0.2.16/tests/loongarch64.rs000064400000000000000000000006741046102023000161050ustar 00000000000000//! LoongArch64 tests #![cfg(target_arch = "loongarch64")] cpufeatures::new!( lacaps, "cpucfg", "lam", "ual", "fpu", "lsx", "lasx", "crc32", "complex", "crypto", "lvz", "lbt.x86", "lbt.arm", "lbt.mips", "ptw" ); #[test] fn init() { let token: lacaps::InitToken = lacaps::init(); assert_eq!(token.get(), lacaps::get()); } #[test] fn init_get() { let (token, val) = lacaps::init_get(); assert_eq!(val, token.get()); } cpufeatures-0.2.16/tests/x86.rs000064400000000000000000000005231046102023000143750ustar 00000000000000//! x86/x86_64 tests #![cfg(any(target_arch = "x86", target_arch = "x86_64"))] cpufeatures::new!(cpuid, "aes", "sha"); #[test] fn init() { let token: cpuid::InitToken = cpuid::init(); assert_eq!(token.get(), cpuid::get()); } #[test] fn init_get() { let (token, val) = cpuid::init_get(); assert_eq!(val, token.get()); }