Botan 3.14.1
Crypto and TLS for C&
os_utils.h
Go to the documentation of this file.
1/*
2* OS specific utility functions
3* (C) 2015,2016,2017,2018 Jack Lloyd
4*
5* Botan is released under the Simplified BSD License (see license.txt)
6*/
7
8#ifndef BOTAN_OS_UTILS_H_
9#define BOTAN_OS_UTILS_H_
10
11#include <botan/types.h>
12#include <ctime>
13#include <functional>
14#include <memory>
15#include <optional>
16#include <string>
17#include <vector>
18
19#if defined(BOTAN_TARGET_OS_HAS_THREADS)
20 #include <thread>
21#endif
22
23namespace Botan::OS {
24
25/*
26* This header is internal (not installed) and these functions are not
27* intended to be called by applications. However they are given public
28* visibility (using BOTAN_TEST_API macro) for the tests. This also probably
29* allows them to be overridden by the application on ELF systems, but
30* this hasn't been tested.
31*/
32
33/**
34* @return process ID assigned by the operating system.
35*
36* On Unix and Windows systems, this always returns a result
37*
38* On systems where there is no processes to speak of (for example on baremetal
39* systems or within a unikernel), this function returns zero.
40*/
42
43/**
44* @return CPU processor clock, if available
45*
46* On Windows, calls QueryPerformanceCounter.
47*
48* Under GCC or Clang on supported platforms the hardware cycle counter is queried.
49* Currently supported processors are x86, PPC, Alpha, SPARC, IA-64, S/390x, and HP-PA.
50* If no CPU cycle counter is available on this system, returns zero.
51*/
53
55
56/**
57* If this system supports getauxval (or an equivalent interface,
58* like FreeBSD's elf_aux_info) queries AT_HWCAP and AT_HWCAP2
59* and returns both.
60*
61* Otherwise returns nullopt.
62*/
63std::optional<std::pair<unsigned long, unsigned long>> get_auxval_hwcap();
64
65/*
66* @return best resolution timestamp available
67*
68* The epoch and update rate of this clock is arbitrary and depending
69* on the hardware it may not tick at a constant rate.
70*
71* Uses hardware cycle counter, if available.
72* On POSIX platforms clock_gettime is used with a monotonic timer
73*
74* As a final fallback std::chrono::high_resolution_clock is used.
75*
76* On systems that are lacking a real time clock, this may return 0
77*/
79
80/**
81* @return system clock (reflecting wall clock) with best resolution
82* available, normalized to nanoseconds resolution, using Unix epoch.
83*
84* If the system does not have a real time clock this function will throw
85* Not_Implemented
86*/
88
89/**
90* @return CPU time consumed by the calling thread, normalized to
91* nanoseconds resolution, or nullopt if the system does not support
92* it or if the reported resolution is too coarse.
93*
94* The epoch is arbitrary; only differences between calls are meaningful.
95*/
96std::optional<uint64_t> BOTAN_TEST_API get_thread_cpu_time_ns();
97
98/**
99* @return an integer which increments every time the process forks.
100*
101* If the system does not have any notion of fork() this returns constant 0
102*/
104
105/**
106* Detects if the address space of this process may have been duplicated,
107* for example by fork(), since this object was created or last rebaselined.
108*/
110 public:
111 /**
112 * Record the state of the current process
113 */
115
116 /**
117 * Discard the recorded state and record the state of the current process
118 */
119 void rebaseline();
120
121 /**
122 * @return true if the current process may be a duplicate of the
123 * process in which this object was created or last rebaselined
124 */
125 bool fork_detected() const;
126
127 private:
128 uint32_t m_process_id;
129 uint64_t m_fork_generation;
130};
131
132/**
133* Format a time
134*
135* Converts the time_t to a local time representation,
136* then invokes std::put_time with the specified format.
137*/
138std::string BOTAN_TEST_API format_time(time_t time, const std::string& format);
139
140/**
141* @return maximum amount of memory (in bytes) Botan could/should
142* hypothetically allocate for the memory poool. Reads environment
143* variable "BOTAN_MLOCK_POOL_SIZE", set to "0" to disable pool.
144*/
146
147/**
148* Return the size of a memory page, if that can be derived on the
149* current system. Otherwise returns some default value (eg 4096)
150*/
151size_t system_page_size();
152
153/**
154* Read the value of an environment variable, setting it to value_out if it
155* exists. Returns false and sets value_out to empty string if no such variable
156* is set. If the process seems to be running in a privileged state (such as
157* setuid) then always returns false and does not examine the environment.
158*/
159bool read_env_variable(std::string& value_out, std::string_view var_name);
160
161/**
162* Read the value of an environment variable and convert it to an
163* integer. If not set or conversion fails, returns the default value.
164*
165* If the process seems to be running in a privileged state (such as setuid)
166* then always returns nullptr, similar to glibc's secure_getenv.
167*/
168size_t read_env_variable_sz(std::string_view var_name, size_t def_value = 0);
169
170/**
171* Request count pages of RAM which are locked into memory using mlock,
172* VirtualLock, or some similar OS specific API. Free it with free_locked_pages.
173*
174* Returns an empty list on failure. This function is allowed to return fewer
175* than count pages.
176*
177* The contents of the allocated pages are undefined.
178*
179* Each page is preceded by and followed by a page which is marked
180* as noaccess, such that accessing it will cause a crash. This turns
181* out of bound reads/writes into crash events.
182*
183* @param count requested number of locked pages
184*/
185std::vector<void*> allocate_locked_pages(size_t count);
186
187/**
188* Free memory allocated by allocate_locked_pages
189* @param pages a list of pages returned by allocate_locked_pages
190*/
191void free_locked_pages(const std::vector<void*>& pages);
192
193/**
194* Set the MMU to prohibit access to this page
195*/
196void page_prohibit_access(void* page);
197
198/**
199* Set the MMU to allow R/W access to this page
200*/
201void page_allow_access(void* page);
202
203#if defined(BOTAN_TARGET_OS_HAS_THREADS)
204void set_thread_name(std::thread& thread, const std::string& name);
205#endif
206
207/**
208* Run a probe instruction to test for support for a CPU instruction.
209* Runs in system-specific env that catches illegal instructions; this
210* function always fails if the OS doesn't provide this.
211* Returns value of probe_fn, if it could run.
212* If error occurs, returns negative number.
213* This allows probe_fn to indicate errors of its own, if it wants.
214* For example the instruction might not only be only available on some
215* CPUs, but also buggy on some subset of these - the probe function
216* can test to make sure the instruction works properly before
217* indicating that the instruction is available.
218*
219* @warning on Unix systems this temporarily replaces the process-wide SIGILL
220* handler. Probes are serialized, and a SIGILL raised by another thread while
221* a probe is running is forwarded to the previous handler, but any such fault
222* on the probing thread (other than the probe itself) will be misreported.
223*
224* If probe_fn throws an exception the result is undefined.
225*
226* Return codes:
227* -1 illegal instruction detected
228*/
229int BOTAN_TEST_API run_cpu_instruction_probe(const std::function<int()>& probe_fn);
230
231/**
232* Represents a terminal state
233*/
234class BOTAN_UNSTABLE_API Echo_Suppression /* NOLINT(*special-member-functions) */ {
235 public:
236 /**
237 * Reenable echo on this terminal. Can be safely called
238 * multiple times. May throw if an error occurs.
239 */
240 virtual void reenable_echo() = 0;
241
242 /**
243 * Implicitly calls reenable_echo, but swallows/ignored all
244 * errors which would leave the terminal in an invalid state.
245 */
246 virtual ~Echo_Suppression() = default;
247};
248
249/**
250* Suppress echo on the terminal
251* Returns null if this operation is not supported on the current system.
252*/
253std::unique_ptr<Echo_Suppression> BOTAN_UNSTABLE_API suppress_echo_on_terminal();
254
255} // namespace Botan::OS
256
257#endif
#define BOTAN_UNSTABLE_API
Definition api.h:34
#define BOTAN_TEST_API
Definition api.h:41
virtual void reenable_echo()=0
virtual ~Echo_Suppression()=default
bool fork_detected() const
Definition os_utils.cpp:720
const char * name
Definition ffi_tls.h:59
size_t get_memory_locking_limit()
Definition os_utils.cpp:410
uint64_t BOTAN_TEST_API get_high_resolution_clock()
Definition os_utils.cpp:273
size_t BOTAN_TEST_API get_cpu_available()
Definition os_utils.cpp:241
std::unique_ptr< Echo_Suppression > BOTAN_UNSTABLE_API suppress_echo_on_terminal()
Definition os_utils.cpp:862
size_t read_env_variable_sz(std::string_view var_name, size_t def_value=0)
Definition os_utils.cpp:507
void page_allow_access(void *page)
Definition os_utils.cpp:649
std::string BOTAN_TEST_API format_time(time_t time, const std::string &format)
Definition os_utils.cpp:366
bool read_env_variable(std::string &value_out, std::string_view var_name)
Definition os_utils.cpp:471
void page_prohibit_access(void *page)
Definition os_utils.cpp:663
std::optional< std::pair< unsigned long, unsigned long > > get_auxval_hwcap()
Definition os_utils.cpp:137
int BOTAN_TEST_API run_cpu_instruction_probe(const std::function< int()> &probe_fn)
Definition os_utils.cpp:814
std::vector< void * > allocate_locked_pages(size_t count)
Definition os_utils.cpp:573
size_t system_page_size()
Definition os_utils.cpp:390
uint64_t BOTAN_TEST_API get_system_timestamp_ns()
Definition os_utils.cpp:328
std::optional< uint64_t > BOTAN_TEST_API get_thread_cpu_time_ns()
Definition os_utils.cpp:345
void free_locked_pages(const std::vector< void * > &pages)
Definition os_utils.cpp:725
uint32_t BOTAN_TEST_API get_process_id()
Definition os_utils.cpp:78
uint64_t BOTAN_TEST_API get_cpu_cycle_counter()
Definition os_utils.cpp:170
uint64_t BOTAN_TEST_API get_fork_generation()
Definition os_utils.cpp:704