diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-07 09:22:09 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-07 09:22:09 +0000 |
commit | 43a97878ce14b72f0981164f87f2e35e14151312 (patch) | |
tree | 620249daf56c0258faa40cbdcf9cfba06de2a846 /third_party/rust/cpufeatures | |
parent | Initial commit. (diff) | |
download | firefox-upstream.tar.xz firefox-upstream.zip |
Adding upstream version 110.0.1.upstream/110.0.1upstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'third_party/rust/cpufeatures')
-rw-r--r-- | third_party/rust/cpufeatures/.cargo-checksum.json | 1 | ||||
-rw-r--r-- | third_party/rust/cpufeatures/CHANGELOG.md | 93 | ||||
-rw-r--r-- | third_party/rust/cpufeatures/Cargo.toml | 38 | ||||
-rw-r--r-- | third_party/rust/cpufeatures/LICENSE-APACHE | 201 | ||||
-rw-r--r-- | third_party/rust/cpufeatures/LICENSE-MIT | 25 | ||||
-rw-r--r-- | third_party/rust/cpufeatures/README.md | 90 | ||||
-rw-r--r-- | third_party/rust/cpufeatures/src/aarch64.rs | 182 | ||||
-rw-r--r-- | third_party/rust/cpufeatures/src/lib.rs | 140 | ||||
-rw-r--r-- | third_party/rust/cpufeatures/src/miri.rs | 20 | ||||
-rw-r--r-- | third_party/rust/cpufeatures/src/x86.rs | 105 | ||||
-rw-r--r-- | third_party/rust/cpufeatures/tests/aarch64.rs | 17 | ||||
-rw-r--r-- | third_party/rust/cpufeatures/tests/x86.rs | 17 |
12 files changed, 929 insertions, 0 deletions
diff --git a/third_party/rust/cpufeatures/.cargo-checksum.json b/third_party/rust/cpufeatures/.cargo-checksum.json new file mode 100644 index 0000000000..9e4f2df3a4 --- /dev/null +++ b/third_party/rust/cpufeatures/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"CHANGELOG.md":"b451593f0440f2bbc63cd2e98535614151e9ab12f877dd8bd9f60dd3ca2b9a36","Cargo.toml":"2b7510bf73cf20e993411333b2301574d72dd6d6ce3a1c558b5c458b12d8cd33","LICENSE-APACHE":"a9040321c3712d8fd0b09cf52b17445de04a23a10165049ae187cd39e5c86be5","LICENSE-MIT":"904801faf3f1850328af8e1aa1047b9190cc22ed40df5c87f2d93d17f847ef67","README.md":"c991281c8d1525279b90dffd452bd731116eebc456ee3a23b9c997df402e8bf7","src/aarch64.rs":"697e8048929cbee0248657da956e8cc627d59ee3fc96729068fec6e7b089b7b6","src/lib.rs":"5b2e7c89dab1d2bed08a4fe09aaf9c5f17ccaa8316d31d5af545b86e7d6a6947","src/miri.rs":"acf1a7e7ae31a1de07941084c6b589a2d4c6ea5f87012c811592c865d04c02cb","src/x86.rs":"380575e3383ece930fea661c6f54201b04c23e4753154dab96031290f398709b","tests/aarch64.rs":"bdabbe67316c128b57003ba5faa07707b5f339b1f3e984da4bc383cc93c2bedd","tests/x86.rs":"fcf476ca6ebd0845ab547cea4fe40c2ba2a2324c024264d9a86f666586f3a480"},"package":"28d997bd5e24a5928dd43e46dc529867e207907fe0b239c3477d924f7f2ca320"}
\ No newline at end of file diff --git a/third_party/rust/cpufeatures/CHANGELOG.md b/third_party/rust/cpufeatures/CHANGELOG.md new file mode 100644 index 0000000000..dae3dd11a3 --- /dev/null +++ b/third_party/rust/cpufeatures/CHANGELOG.md @@ -0,0 +1,93 @@ +# 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.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) +- 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) +### 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) +### 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) +### 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 diff --git a/third_party/rust/cpufeatures/Cargo.toml b/third_party/rust/cpufeatures/Cargo.toml new file mode 100644 index 0000000000..f9fea81359 --- /dev/null +++ b/third_party/rust/cpufeatures/Cargo.toml @@ -0,0 +1,38 @@ +# 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.5" +authors = ["RustCrypto Developers"] +description = """ +Lightweight runtime CPU feature detection for x86/x86_64 and aarch64 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 = ["no-std"] +license = "MIT OR Apache-2.0" +repository = "https://github.com/RustCrypto/utils" + +[target.aarch64-apple-darwin.dependencies.libc] +version = "0.2.95" + +[target.aarch64-linux-android.dependencies.libc] +version = "0.2.95" + +[target."cfg(all(target_arch = \"aarch64\", target_os = \"linux\"))".dependencies.libc] +version = "0.2.95" diff --git a/third_party/rust/cpufeatures/LICENSE-APACHE b/third_party/rust/cpufeatures/LICENSE-APACHE new file mode 100644 index 0000000000..78173fa2e7 --- /dev/null +++ b/third_party/rust/cpufeatures/LICENSE-APACHE @@ -0,0 +1,201 @@ + 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. diff --git a/third_party/rust/cpufeatures/LICENSE-MIT b/third_party/rust/cpufeatures/LICENSE-MIT new file mode 100644 index 0000000000..2726e14a40 --- /dev/null +++ b/third_party/rust/cpufeatures/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (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. diff --git a/third_party/rust/cpufeatures/README.md b/third_party/rust/cpufeatures/README.md new file mode 100644 index 0000000000..5a5bb40632 --- /dev/null +++ b/third_party/rust/cpufeatures/README.md @@ -0,0 +1,90 @@ +# [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` 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 architectures + +### `aarch64`: Android, iOS, Linux, and macOS/M4 only + +Note: ARM64 does not support OS-independent feature detection, so support must +be implemented on an OS-by-OS basis. + +Target features: + +- `aes` +- `sha2` +- `sha3` + +Note: please open a GitHub Issue to request support for additional features. + +### `x86`/`x86_64`: OS independent and `no_std`-friendly + +Target features: + +- `adx` +- `aes` +- `avx` +- `avx2` +- `bmi1` +- `bmi2` +- `fma` +- `mmx` +- `pclmulqdq` +- `popcnt` +- `rdrand` +- `rdseed` +- `sgx` +- `sha` +- `sse` +- `sse2` +- `sse3` +- `sse4.1` +- `sse4.2` +- `ssse3` + +## 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 diff --git a/third_party/rust/cpufeatures/src/aarch64.rs b/third_party/rust/cpufeatures/src/aarch64.rs new file mode 100644 index 0000000000..6efdde1af4 --- /dev/null +++ b/third_party/rust/cpufeatures/src/aarch64.rs @@ -0,0 +1,182 @@ +//! 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) } +} + +// MacOS runtime detection of target CPU features using `sysctlbyname`. +#[cfg(target_os = "macos")] +#[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. + ("sha2", SHA2), // Enable SHA1 and SHA256 support. + ("sha3", SHA3), // Enable SHA512 and SHA3 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: <https://github.com/RustCrypto/utils/issues/395> +#[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 SHA2: c_ulong = libc::HWCAP_SHA2; + pub const SHA3: c_ulong = libc::HWCAP_SHA3 | libc::HWCAP_SHA512; +} + +// macOS `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: +// <https://github.com/RustCrypto/utils/issues/378> +#[cfg(target_os = "macos")] +#[macro_export] +#[doc(hidden)] +macro_rules! check { + ("aes") => { + true + }; + ("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") + } + }; +} + +/// macOS helper function for calling `sysctlbyname`. +#[cfg(target_os = "macos")] +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::<u32>(); + + 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 +} + +// iOS `check!` macro. +// +// Unfortunately iOS does not provide access to the `sysctl(3)` API which means +// we can only return static values for CPU features which can be assumed to +// be present on all Apple ARM64 hardware. +// +// See discussion on this issue for more information: +// <https://github.com/RustCrypto/utils/issues/378> +#[cfg(target_os = "ios")] +#[macro_export] +#[doc(hidden)] +macro_rules! check { + ("aes") => { + true + }; + ("sha2") => { + true + }; + ("sha3") => { + false + }; +} + +// On other targets, runtime CPU feature detection is unavailable +#[cfg(not(any( + target_os = "ios", + target_os = "linux", + target_os = "android", + target_os = "macos" +)))] +#[macro_export] +#[doc(hidden)] +macro_rules! __detect_target_features { + ($($tf:tt),+) => { + false + }; +} diff --git a/third_party/rust/cpufeatures/src/lib.rs b/third_party/rust/cpufeatures/src/lib.rs new file mode 100644 index 0000000000..b6c7c10b24 --- /dev/null +++ b/third_party/rust/cpufeatures/src/lib.rs @@ -0,0 +1,140 @@ +//! 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: +//! - `aarch64`: Linux and macOS/M4 only (ARM64 does not support OS-independent feature detection) +//! - Target features: `aes`, `sha2`, `sha3` +//! - `x86`/`x86_64`: OS independent and `no_std`-friendly +//! - Target features: `adx`, `aes`, `avx`, `avx2`, `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(all(target_arch = "aarch64"))] +#[doc(hidden)] +pub mod aarch64; + +#[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 = "x86", target_arch = "x86_64")))] +compile_error!("This crate works only on `aarch64`, `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 + } + } + } + } + + /// Initialize underlying storage if needed and get + /// stored value and initialization token. + #[inline] + pub fn init_get() -> (InitToken, bool) { + let res = $crate::__unless_target_features! { + $($tf),+ => { + // Relaxed ordering is fine, as we only have a single atomic variable. + let val = STORAGE.load(Relaxed); + + if val == UNINIT { + let res = $crate::__detect_target_features!($($tf),+); + STORAGE.store(res as u8, Relaxed); + res + } 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 + } + } + }; +} diff --git a/third_party/rust/cpufeatures/src/miri.rs b/third_party/rust/cpufeatures/src/miri.rs new file mode 100644 index 0000000000..8dff21c13e --- /dev/null +++ b/third_party/rust/cpufeatures/src/miri.rs @@ -0,0 +1,20 @@ +//! 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 + }; +} diff --git a/third_party/rust/cpufeatures/src/x86.rs b/third_party/rust/cpufeatures/src/x86.rs new file mode 100644 index 0000000000..c973b7446b --- /dev/null +++ b/third_party/rust/cpufeatures/src/x86.rs @@ -0,0 +1,105 @@ +//! 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(target_env = "sgx"))] + $body + + // CPUID is not available on SGX targets + #[cfg(target_env = "sgx")] + 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 + }}; +} + +macro_rules! __expand_check_macro { + ($(($name:tt $(, $i:expr, $reg:ident, $offset:expr)*)),* $(,)?) => { + #[macro_export] + #[doc(hidden)] + macro_rules! check { + $( + ($cr:expr, $name) => { + true + $( + & ($cr[$i].$reg & (1 << $offset) != 0) + )* + }; + )* + } + }; +} + +// Note that according to the [Intel manual][0] AVX2 and FMA require +// that we check availability of AVX before using them. +// +// [0]: https://www.intel.com/content/dam/develop/external/us/en/documents/36945 +__expand_check_macro! { + ("mmx", 0, edx, 23), + ("sse", 0, edx, 25), + ("sse2", 0, edx, 26), + ("sse3", 0, ecx, 0), + ("pclmulqdq", 0, ecx, 1), + ("ssse3", 0, ecx, 9), + ("fma", 0, ecx, 28, 0, ecx, 12), + ("sse4.1", 0, ecx, 19), + ("sse4.2", 0, ecx, 20), + ("popcnt", 0, ecx, 23), + ("aes", 0, ecx, 25), + ("avx", 0, ecx, 28), + ("rdrand", 0, ecx, 30), + ("sgx", 1, ebx, 2), + ("bmi1", 1, ebx, 3), + ("avx2", 0, ecx, 28, 1, ebx, 5), + ("bmi2", 1, ebx, 8), + ("rdseed", 1, ebx, 18), + ("adx", 1, ebx, 19), + ("sha", 1, ebx, 29), +} diff --git a/third_party/rust/cpufeatures/tests/aarch64.rs b/third_party/rust/cpufeatures/tests/aarch64.rs new file mode 100644 index 0000000000..949669bed0 --- /dev/null +++ b/third_party/rust/cpufeatures/tests/aarch64.rs @@ -0,0 +1,17 @@ +//! ARM64 tests + +#![cfg(target_arch = "aarch64")] + +cpufeatures::new!(armcaps, "aes", "sha2", "sha3"); + +#[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()); +} diff --git a/third_party/rust/cpufeatures/tests/x86.rs b/third_party/rust/cpufeatures/tests/x86.rs new file mode 100644 index 0000000000..0d81242389 --- /dev/null +++ b/third_party/rust/cpufeatures/tests/x86.rs @@ -0,0 +1,17 @@ +//! 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()); +} |