Botan 3.9.0
Crypto and TLS for C&
cpuid.cpp
Go to the documentation of this file.
1/*
2* Runtime CPU detection
3* (C) 2009,2010,2013,2017,2023 Jack Lloyd
4*
5* Botan is released under the Simplified BSD License (see license.txt)
6*/
7
8#include <botan/internal/cpuid.h>
9
10#include <botan/exceptn.h>
11#include <botan/internal/parsing.h>
12
13#if defined(BOTAN_HAS_OS_UTILS)
14 #include <botan/internal/os_utils.h>
15#endif
16
17namespace Botan {
18
19#if !defined(BOTAN_HAS_CPUID_DETECTION)
20uint32_t CPUFeature::as_u32() const {
21 throw Invalid_State("CPUFeature invalid bit");
22}
23
24std::optional<CPUFeature> CPUFeature::from_string(std::string_view) {
25 return {};
26}
27
28std::string CPUFeature::to_string() const {
29 throw Invalid_State("CPUFeature invalid bit");
30}
31#endif
32
33//static
34std::string CPUID::to_string() {
35 std::vector<std::string> flags;
36
37 const uint32_t bitset = state().bitset();
38
39 for(size_t i = 0; i != 32; ++i) {
40 const uint32_t b = static_cast<uint32_t>(1) << i;
41 if((bitset & b) == b) {
42 // NOLINTNEXTLINE(clang-analyzer-optin.core.EnumCastOutOfRange)
43 flags.push_back(CPUFeature(static_cast<CPUFeature::Bit>(b)).to_string());
44 }
45 }
46
47 return string_join(flags, ' ');
48}
49
50//static
52 state() = CPUID_Data();
53}
54
55#if defined(BOTAN_HAS_CPUID_DETECTION)
56
57namespace {
58
59uint32_t cleared_cpuid_bits() {
60 uint32_t cleared = 0;
61
62 #if defined(BOTAN_HAS_OS_UTILS)
63 std::string clear_cpuid_env;
64 if(OS::read_env_variable(clear_cpuid_env, "BOTAN_CLEAR_CPUID")) {
65 for(const auto& cpuid : split_on(clear_cpuid_env, ',')) {
66 if(auto bit = CPUID::bit_from_string(cpuid)) {
67 cleared |= bit->as_u32();
68 }
69 }
70 }
71 #endif
72
73 return cleared;
74}
75
76} // namespace
77
78#endif
79
80CPUID::CPUID_Data::CPUID_Data() {
81 // NOLINTBEGIN(*-prefer-member-initializer)
82#if defined(BOTAN_HAS_CPUID_DETECTION)
83 m_processor_features = detect_cpu_features(~cleared_cpuid_bits());
84#else
85 m_processor_features = 0;
86#endif
87 // NOLINTEND(*-prefer-member-initializer)
88}
89
90std::optional<CPUFeature> CPUID::bit_from_string(std::string_view tok) {
91 return CPUFeature::from_string(tok);
92}
93
94} // namespace Botan
uint32_t as_u32() const
Definition cpuid.cpp:20
static std::optional< CPUFeature > from_string(std::string_view)
Definition cpuid.cpp:24
std::string to_string() const
Definition cpuid.cpp:28
static std::optional< CPUID::Feature > bit_from_string(std::string_view tok)
Definition cpuid.cpp:90
static std::string to_string()
Definition cpuid.cpp:34
static void initialize()
Definition cpuid.cpp:51
bool read_env_variable(std::string &value_out, std::string_view var_name)
Definition os_utils.cpp:445
std::vector< std::string > split_on(std::string_view str, char delim)
Definition parsing.cpp:111
std::string string_join(const std::vector< std::string > &strs, char delim)
Definition parsing.cpp:140