9#include <botan/internal/os_utils.h>
11#include <botan/exceptn.h>
12#include <botan/mem_ops.h>
13#include <botan/internal/cpuid.h>
21#if defined(BOTAN_TARGET_OS_HAS_EXPLICIT_BZERO)
25#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
32 #include <sys/resource.h>
33 #include <sys/types.h>
39#if defined(BOTAN_TARGET_OS_IS_EMSCRIPTEN)
40 #include <emscripten/emscripten.h>
43#if defined(BOTAN_TARGET_OS_HAS_GETAUXVAL) || defined(BOTAN_TARGET_OS_HAS_ELF_AUX_INFO)
47#if defined(BOTAN_TARGET_OS_HAS_AUXINFO)
52#if defined(BOTAN_TARGET_OS_HAS_WIN32)
56 #if defined(BOTAN_BUILD_COMPILER_IS_MSVC)
57 #include <libloaderapi.h>
58 #include <stringapiset.h>
62#if defined(BOTAN_TARGET_OS_IS_IOS) || defined(BOTAN_TARGET_OS_IS_MACOS)
63 #include <mach/vm_statistics.h>
64 #include <sys/sysctl.h>
65 #include <sys/types.h>
68#if defined(BOTAN_TARGET_OS_HAS_PRCTL)
69 #include <sys/prctl.h>
72#if defined(BOTAN_TARGET_OS_IS_FREEBSD) || defined(BOTAN_TARGET_OS_IS_OPENBSD) || defined(BOTAN_TARGET_OS_IS_DRAGONFLY)
73 #include <pthread_np.h>
76#if defined(BOTAN_TARGET_OS_IS_HAIKU)
77 #include <kernel/OS.h>
84#if defined(BOTAN_TARGET_OS_HAS_RTLSECUREZEROMEMORY)
85 ::RtlSecureZeroMemory(ptr, n);
87#elif defined(BOTAN_TARGET_OS_HAS_EXPLICIT_BZERO)
88 ::explicit_bzero(ptr, n);
90#elif defined(BOTAN_TARGET_OS_HAS_EXPLICIT_MEMSET)
91 (void)::explicit_memset(ptr, 0, n);
93#elif defined(BOTAN_USE_VOLATILE_MEMSET_FOR_ZERO) && (BOTAN_USE_VOLATILE_MEMSET_FOR_ZERO == 1)
101 static void* (*
const volatile memset_ptr)(
void*,
int,
size_t) = std::memset;
102 (memset_ptr)(ptr, 0, n);
105 volatile uint8_t* p =
reinterpret_cast<volatile uint8_t*
>(ptr);
107 for(
size_t i = 0; i != n; ++i)
113#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
115#elif defined(BOTAN_TARGET_OS_HAS_WIN32)
116 return ::GetCurrentProcessId();
117#elif defined(BOTAN_TARGET_OS_IS_LLVM) || defined(BOTAN_TARGET_OS_IS_NONE)
120 #error "Missing get_process_id"
125#if defined(BOTAN_TARGET_OS_HAS_GETAUXVAL)
127#elif defined(BOTAN_TARGET_OS_HAS_ELF_AUX_INFO)
129#elif defined(BOTAN_TARGET_OS_HAS_AUXINFO)
147#if defined(AT_HWCAP2)
157#if defined(BOTAN_TARGET_OS_HAS_GETAUXVAL)
158 return ::getauxval(
id);
159#elif defined(BOTAN_TARGET_OS_HAS_ELF_AUX_INFO)
160 unsigned long auxinfo = 0;
161 ::elf_aux_info(
static_cast<int>(
id), &auxinfo,
sizeof(auxinfo));
163#elif defined(BOTAN_TARGET_OS_HAS_AUXINFO)
164 for(
const AuxInfo* auxinfo =
static_cast<AuxInfo*
>(::_dlauxinfo()); auxinfo != AT_NULL; ++auxinfo) {
165 if(
id == auxinfo->a_type)
177#if defined(AT_SECURE)
183#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
184 return (::getuid() != ::geteuid()) || (::getgid() != ::getegid());
193#if defined(BOTAN_TARGET_OS_HAS_WIN32)
195 ::QueryPerformanceCounter(&tv);
198#elif defined(BOTAN_USE_GCC_INLINE_ASM)
200 #if defined(BOTAN_TARGET_CPU_IS_X86_FAMILY)
202 if(CPUID::has_rdtsc()) {
203 uint32_t rtc_low = 0, rtc_high = 0;
204 asm volatile(
"rdtsc" :
"=d"(rtc_high),
"=a"(rtc_low));
205 rtc = (
static_cast<uint64_t
>(rtc_high) << 32) | rtc_low;
208 #elif defined(BOTAN_TARGET_ARCH_IS_PPC64)
211 uint32_t rtc_low = 0, rtc_high = 0, rtc_high2 = 0;
212 asm volatile(
"mftbu %0" :
"=r"(rtc_high));
213 asm volatile(
"mftb %0" :
"=r"(rtc_low));
214 asm volatile(
"mftbu %0" :
"=r"(rtc_high2));
216 if(rtc_high == rtc_high2) {
217 rtc = (
static_cast<uint64_t
>(rtc_high) << 32) | rtc_low;
222 #elif defined(BOTAN_TARGET_ARCH_IS_ALPHA)
223 asm volatile(
"rpcc %0" :
"=r"(rtc));
226 #elif defined(BOTAN_TARGET_ARCH_IS_SPARC64) && !defined(BOTAN_TARGET_OS_IS_OPENBSD)
227 asm volatile(
"rd %%tick, %0" :
"=r"(rtc));
229 #elif defined(BOTAN_TARGET_ARCH_IS_IA64)
230 asm volatile(
"mov %0=ar.itc" :
"=r"(rtc));
232 #elif defined(BOTAN_TARGET_ARCH_IS_S390X)
233 asm volatile(
"stck 0(%0)" : :
"a"(&rtc) :
"memory",
"cc");
235 #elif defined(BOTAN_TARGET_ARCH_IS_HPPA)
236 asm volatile(
"mfctl 16,%0" :
"=r"(rtc));
248#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
250 #if defined(_SC_NPROCESSORS_ONLN)
251 const long cpu_online = ::sysconf(_SC_NPROCESSORS_ONLN);
253 return static_cast<size_t>(cpu_online);
257 #if defined(_SC_NPROCESSORS_CONF)
258 const long cpu_conf = ::sysconf(_SC_NPROCESSORS_CONF);
260 return static_cast<size_t>(cpu_conf);
266#if defined(BOTAN_TARGET_OS_HAS_THREADS)
269 const size_t hw_concur = std::thread::hardware_concurrency();
284#if defined(BOTAN_TARGET_OS_IS_EMSCRIPTEN)
285 return emscripten_get_now();
295#if defined(BOTAN_TARGET_OS_HAS_CLOCK_GETTIME)
298 const clockid_t clock_types[] = {
299 #if defined(CLOCK_MONOTONIC_HR)
302 #if defined(CLOCK_MONOTONIC_RAW)
305 #if defined(CLOCK_MONOTONIC)
308 #if defined(CLOCK_PROCESS_CPUTIME_ID)
309 CLOCK_PROCESS_CPUTIME_ID,
311 #if defined(CLOCK_THREAD_CPUTIME_ID)
312 CLOCK_THREAD_CPUTIME_ID,
316 for(clockid_t clock : clock_types) {
318 if(::clock_gettime(clock, &ts) == 0) {
319 return (
static_cast<uint64_t
>(ts.tv_sec) * 1000000000) +
static_cast<uint64_t
>(ts.tv_nsec);
325 auto now = std::chrono::high_resolution_clock::now().time_since_epoch();
326 return std::chrono::duration_cast<std::chrono::nanoseconds>(now).count();
330#if defined(BOTAN_TARGET_OS_HAS_CLOCK_GETTIME)
332 if(::clock_gettime(CLOCK_REALTIME, &ts) == 0) {
333 return (
static_cast<uint64_t
>(ts.tv_sec) * 1000000000) +
static_cast<uint64_t
>(ts.tv_nsec);
337 auto now = std::chrono::system_clock::now().time_since_epoch();
338 return std::chrono::duration_cast<std::chrono::nanoseconds>(now).count();
344#if defined(BOTAN_TARGET_OS_HAS_WIN32)
345 localtime_s(&tm, &time);
346#elif defined(BOTAN_TARGET_OS_HAS_POSIX1)
347 localtime_r(&time, &tm);
349 if(
auto tmp = std::localtime(&time)) {
356 std::ostringstream oss;
357 oss << std::put_time(&tm, format.c_str());
362 const size_t default_page_size = 4096;
364#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
365 long p = ::sysconf(_SC_PAGESIZE);
367 return static_cast<size_t>(p);
369 return default_page_size;
371#elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
373 SYSTEM_INFO sys_info;
374 ::GetSystemInfo(&sys_info);
375 return sys_info.dwPageSize;
377 return default_page_size;
390 const size_t max_locked_kb = 512;
396#if defined(RLIMIT_MEMLOCK) && defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
397 const size_t mlock_requested =
400 if(mlock_requested > 0) {
401 struct ::rlimit limits;
403 ::getrlimit(RLIMIT_MEMLOCK, &limits);
405 if(limits.rlim_cur < limits.rlim_max) {
406 limits.rlim_cur = limits.rlim_max;
407 ::setrlimit(RLIMIT_MEMLOCK, &limits);
408 ::getrlimit(RLIMIT_MEMLOCK, &limits);
411 return std::min<size_t>(limits.rlim_cur, mlock_requested * 1024);
414#elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
415 const size_t mlock_requested =
418 SIZE_T working_min = 0, working_max = 0;
419 if(!::GetProcessWorkingSetSize(::GetCurrentProcess(), &working_min, &working_max)) {
430 if(working_min > overhead) {
431 const size_t lockable_bytes = working_min - overhead;
432 return std::min<size_t>(lockable_bytes, mlock_requested * 1024);
449#if defined(BOTAN_TARGET_OS_HAS_WIN32) && defined(BOTAN_BUILD_COMPILER_IS_MSVC)
450 const std::string
name(name_view);
453 if(getenv_s(&req_size, val,
sizeof(val),
name.c_str()) == 0) {
457 if(req_size > 0 && val[req_size - 1] ==
'\0') {
458 value_out = std::string(val);
460 value_out = std::string(val, req_size);
465 const std::string
name(name_view);
466 if(
const char* val = std::getenv(
name.c_str())) {
479 const size_t val = std::stoul(value,
nullptr);
481 }
catch(std::exception&) {
488#if defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
493 #if defined(BOTAN_TARGET_OS_IS_IOS) || defined(BOTAN_TARGET_OS_IS_MACOS)
496 static constexpr int default_locked_fd = 255;
497 int locked_fd = default_locked_fd;
499 if(
size_t locked_fdl = OS::read_env_variable_sz(
"BOTAN_LOCKED_FD", default_locked_fd)) {
500 if(locked_fdl < 240 || locked_fdl > 255) {
501 locked_fdl = default_locked_fd;
503 locked_fd =
static_cast<int>(locked_fdl);
505 return VM_MAKE_TAG(locked_fd);
516 std::vector<void*> result;
518#if(defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)) || \
519 defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
521 result.reserve(count);
525 #if defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
526 static const int locked_fd = get_locked_fd();
529 for(
size_t i = 0; i != count; ++i) {
532 #if defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
534 int mmap_flags = MAP_PRIVATE;
536 #if defined(MAP_ANONYMOUS)
537 mmap_flags |= MAP_ANONYMOUS;
538 #elif defined(MAP_ANON)
539 mmap_flags |= MAP_ANON;
542 #if defined(MAP_CONCEAL)
543 mmap_flags |= MAP_CONCEAL;
544 #elif defined(MAP_NOCORE)
545 mmap_flags |= MAP_NOCORE;
548 int mmap_prot = PROT_READ | PROT_WRITE;
550 #if defined(PROT_MAX)
551 mmap_prot |= PROT_MAX(mmap_prot);
554 ptr = ::mmap(
nullptr,
561 if(ptr == MAP_FAILED) {
566 if(::mlock(
static_cast<uint8_t*
>(ptr) + page_size, page_size) != 0) {
567 ::munmap(ptr, 3 * page_size);
571 #if defined(MADV_DONTDUMP)
573 ::madvise(
static_cast<uint8_t*
>(ptr) + page_size, page_size, MADV_DONTDUMP);
576 #elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
577 ptr = ::VirtualAlloc(
nullptr, 3 * page_size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
582 if(::VirtualLock(
static_cast<uint8_t*
>(ptr) + page_size, page_size) == 0) {
583 ::VirtualFree(ptr, 0, MEM_RELEASE);
588 std::memset(ptr, 0, 3 * page_size);
597 result.push_back(
static_cast<uint8_t*
>(ptr) + page_size);
607#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
609 ::mprotect(page, page_size, PROT_READ | PROT_WRITE);
610#elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
613 ::VirtualProtect(page, page_size, PAGE_READWRITE, &old_perms);
621#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
623 ::mprotect(page, page_size, PROT_NONE);
624#elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
627 ::VirtualProtect(page, page_size, PAGE_NOACCESS, &old_perms);
637 for(
size_t i = 0; i != pages.size(); ++i) {
638 void* ptr = pages[i];
646#if defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
647 ::munlock(ptr, page_size);
648 ::munmap(
static_cast<uint8_t*
>(ptr) - page_size, 3 * page_size);
649#elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
650 ::VirtualUnlock(ptr, page_size);
651 ::VirtualFree(
static_cast<uint8_t*
>(ptr) - page_size, 0, MEM_RELEASE);
657#if defined(BOTAN_TARGET_OS_HAS_PRCTL) && defined(PR_SET_VMA) && defined(PR_SET_VMA_ANON_NAME)
658 static constexpr char name[] =
"Botan mlock pool";
659 int r = prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME,
reinterpret_cast<uintptr_t
>(page), size,
name);
666#if defined(BOTAN_TARGET_OS_HAS_THREADS)
667void OS::set_thread_name(std::thread& thread,
const std::string&
name) {
668 #if defined(BOTAN_TARGET_OS_IS_LINUX) || defined(BOTAN_TARGET_OS_IS_FREEBSD) || defined(BOTAN_TARGET_OS_IS_DRAGONFLY)
669 static_cast<void>(pthread_setname_np(thread.native_handle(),
name.c_str()));
670 #elif defined(BOTAN_TARGET_OS_IS_OPENBSD)
671 static_cast<void>(pthread_set_name_np(thread.native_handle(),
name.c_str()));
672 #elif defined(BOTAN_TARGET_OS_IS_NETBSD)
673 static_cast<void>(pthread_setname_np(thread.native_handle(),
"%s",
const_cast<char*
>(
name.c_str())));
674 #elif defined(BOTAN_TARGET_OS_HAS_WIN32) && defined(_LIBCPP_HAS_THREAD_API_PTHREAD)
675 static_cast<void>(pthread_setname_np(thread.native_handle(),
name.c_str()));
676 #elif defined(BOTAN_TARGET_OS_HAS_WIN32) && defined(BOTAN_BUILD_COMPILER_IS_MSVC)
677 typedef HRESULT(WINAPI * std_proc)(HANDLE, PCWSTR);
678 HMODULE kern = GetModuleHandleA(
"KernelBase.dll");
679 std_proc set_thread_name =
reinterpret_cast<std_proc
>(GetProcAddress(kern,
"SetThreadDescription"));
680 if(set_thread_name) {
682 auto sz = MultiByteToWideChar(CP_UTF8, 0,
name.data(), -1,
nullptr, 0);
685 if(MultiByteToWideChar(CP_UTF8, 0,
name.data(), -1, &w[0], sz) > 0) {
686 (void)set_thread_name(thread.native_handle(), w.c_str());
690 #elif defined(BOTAN_TARGET_OS_IF_HAIKU)
691 auto thread_id = get_pthread_thread_id(thread.native_handle());
692 static_cast<void>(rename_thread(thread_id,
name.c_str()));
701#if defined(BOTAN_TARGET_OS_HAS_POSIX1) && !defined(BOTAN_TARGET_OS_IS_EMSCRIPTEN)
706::sigjmp_buf g_sigill_jmp_buf;
708void botan_sigill_handler(
int ) {
709 siglongjmp(g_sigill_jmp_buf, 1);
717 volatile int probe_result = -3;
719#if defined(BOTAN_TARGET_OS_HAS_POSIX1) && !defined(BOTAN_TARGET_OS_IS_EMSCRIPTEN)
720 struct sigaction old_sigaction;
721 struct sigaction sigaction;
723 sigaction.sa_handler = botan_sigill_handler;
724 sigemptyset(&sigaction.sa_mask);
725 sigaction.sa_flags = 0;
727 int rc = ::sigaction(SIGILL, &sigaction, &old_sigaction);
730 throw System_Error(
"run_cpu_instruction_probe sigaction failed", errno);
733 rc = sigsetjmp(g_sigill_jmp_buf, 1);
737 probe_result = probe_fn();
744 rc = ::sigaction(SIGILL, &old_sigaction,
nullptr);
746 throw System_Error(
"run_cpu_instruction_probe sigaction restore failed", errno);
757#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
760 POSIX_Echo_Suppression() {
761 m_stdin_fd = fileno(stdin);
762 if(::tcgetattr(m_stdin_fd, &m_old_termios) != 0) {
763 throw System_Error(
"Getting terminal status failed", errno);
766 struct termios noecho_flags = m_old_termios;
767 noecho_flags.c_lflag &= ~ECHO;
768 noecho_flags.c_lflag |= ECHONL;
770 if(::tcsetattr(m_stdin_fd, TCSANOW, &noecho_flags) != 0) {
771 throw System_Error(
"Clearing terminal echo bit failed", errno);
775 void reenable_echo()
override {
777 if(::tcsetattr(m_stdin_fd, TCSANOW, &m_old_termios) != 0) {
778 throw System_Error(
"Restoring terminal echo bit failed", errno);
784 ~POSIX_Echo_Suppression()
override {
790 POSIX_Echo_Suppression(
const POSIX_Echo_Suppression& other) =
delete;
791 POSIX_Echo_Suppression(POSIX_Echo_Suppression&& other) =
delete;
792 POSIX_Echo_Suppression& operator=(
const POSIX_Echo_Suppression& other) =
delete;
793 POSIX_Echo_Suppression& operator=(POSIX_Echo_Suppression&& other) =
delete;
797 struct termios m_old_termios;
800 return std::make_unique<POSIX_Echo_Suppression>();
802#elif defined(BOTAN_TARGET_OS_HAS_WIN32)
806 Win32_Echo_Suppression() {
807 m_input_handle = ::GetStdHandle(STD_INPUT_HANDLE);
808 if(::GetConsoleMode(m_input_handle, &m_console_state) == 0)
809 throw System_Error(
"Getting console mode failed", ::GetLastError());
811 DWORD new_mode = ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT;
812 if(::SetConsoleMode(m_input_handle, new_mode) == 0)
813 throw System_Error(
"Setting console mode failed", ::GetLastError());
816 void reenable_echo()
override {
817 if(m_input_handle != INVALID_HANDLE_VALUE) {
818 if(::SetConsoleMode(m_input_handle, m_console_state) == 0)
819 throw System_Error(
"Setting console mode failed", ::GetLastError());
820 m_input_handle = INVALID_HANDLE_VALUE;
824 ~Win32_Echo_Suppression()
override {
830 Win32_Echo_Suppression(
const Win32_Echo_Suppression& other) =
delete;
831 Win32_Echo_Suppression(Win32_Echo_Suppression&& other) =
delete;
832 Win32_Echo_Suppression& operator=(
const Win32_Echo_Suppression& other) =
delete;
833 Win32_Echo_Suppression& operator=(Win32_Echo_Suppression&& other) =
delete;
836 HANDLE m_input_handle;
837 DWORD m_console_state;
840 return std::make_unique<Win32_Echo_Suppression>();
bool running_in_privileged_state()
size_t get_memory_locking_limit()
uint64_t BOTAN_TEST_API get_high_resolution_clock()
size_t BOTAN_TEST_API get_cpu_available()
std::unique_ptr< Echo_Suppression > BOTAN_UNSTABLE_API suppress_echo_on_terminal()
size_t read_env_variable_sz(std::string_view var_name, size_t def_value=0)
void page_allow_access(void *page)
unsigned long auxval_hwcap()
std::string BOTAN_TEST_API format_time(time_t time, const std::string &format)
bool read_env_variable(std::string &value_out, std::string_view var_name)
void page_prohibit_access(void *page)
int BOTAN_TEST_API run_cpu_instruction_probe(const std::function< int()> &probe_fn)
std::vector< void * > allocate_locked_pages(size_t count)
size_t system_page_size()
uint64_t BOTAN_TEST_API get_system_timestamp_ns()
unsigned long get_auxval(unsigned long id)
void free_locked_pages(const std::vector< void * > &pages)
void page_named(void *page, size_t size)
uint32_t BOTAN_TEST_API get_process_id()
uint64_t BOTAN_TEST_API get_cpu_cycle_counter()
unsigned long auxval_hwcap2()
void secure_scrub_memory(void *ptr, size_t n)