Botan 3.8.1
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 flags.push_back(CPUFeature(static_cast<CPUFeature::Bit>(b)).to_string());
43 }
44 }
45
46 return string_join(flags, ' ');
47}
48
49//static
51 state() = CPUID_Data();
52}
53
54#if defined(BOTAN_HAS_CPUID_DETECTION)
55
56namespace {
57
58uint32_t cleared_cpuid_bits() {
59 uint32_t cleared = 0;
60
61 #if defined(BOTAN_HAS_OS_UTILS)
62 std::string clear_cpuid_env;
63 if(OS::read_env_variable(clear_cpuid_env, "BOTAN_CLEAR_CPUID")) {
64 for(const auto& cpuid : split_on(clear_cpuid_env, ',')) {
65 if(auto bit = CPUID::bit_from_string(cpuid)) {
66 cleared |= bit->as_u32();
67 }
68 }
69 }
70 #endif
71
72 return cleared;
73}
74
75} // namespace
76
77#endif
78
79CPUID::CPUID_Data::CPUID_Data() {
80#if defined(BOTAN_HAS_CPUID_DETECTION)
81 m_processor_features = detect_cpu_features(~cleared_cpuid_bits());
82#else
83 m_processor_features = 0;
84#endif
85}
86
87std::optional<CPUFeature> CPUID::bit_from_string(std::string_view tok) {
88 return CPUFeature::from_string(tok);
89}
90
91} // 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:87
static std::string to_string()
Definition cpuid.cpp:34
static void initialize()
Definition cpuid.cpp:50
bool read_env_variable(std::string &value_out, std::string_view var_name)
Definition os_utils.cpp:435
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