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_IS_ANDROID) || \
44 defined(BOTAN_TARGET_OS_HAS_ELF_AUX_INFO)
48#if defined(BOTAN_TARGET_OS_HAS_AUXINFO)
53#if defined(BOTAN_TARGET_OS_HAS_WIN32)
57 #if defined(BOTAN_BUILD_COMPILER_IS_MSVC)
58 #include <libloaderapi.h>
59 #include <stringapiset.h>
63#if defined(BOTAN_TARGET_OS_IS_ANDROID)
65extern "C" char** environ;
68#if defined(BOTAN_TARGET_OS_IS_IOS) || defined(BOTAN_TARGET_OS_IS_MACOS)
69 #include <mach/vm_statistics.h>
70 #include <sys/sysctl.h>
71 #include <sys/types.h>
74#if defined(BOTAN_TARGET_OS_HAS_PRCTL)
75 #include <sys/prctl.h>
78#if defined(BOTAN_TARGET_OS_IS_FREEBSD) || defined(BOTAN_TARGET_OS_IS_OPENBSD) || defined(BOTAN_TARGET_OS_IS_DRAGONFLY)
79 #include <pthread_np.h>
82#if defined(BOTAN_TARGET_OS_IS_HAIKU)
83 #include <kernel/OS.h>
90#if defined(BOTAN_TARGET_OS_HAS_RTLSECUREZEROMEMORY)
91 ::RtlSecureZeroMemory(ptr, n);
93#elif defined(BOTAN_TARGET_OS_HAS_EXPLICIT_BZERO)
94 ::explicit_bzero(ptr, n);
96#elif defined(BOTAN_TARGET_OS_HAS_EXPLICIT_MEMSET)
97 (void)::explicit_memset(ptr, 0, n);
99#elif defined(BOTAN_USE_VOLATILE_MEMSET_FOR_ZERO) && (BOTAN_USE_VOLATILE_MEMSET_FOR_ZERO == 1)
107 static void* (*
const volatile memset_ptr)(
void*,
int,
size_t) = std::memset;
108 (memset_ptr)(ptr, 0, n);
111 volatile uint8_t* p =
reinterpret_cast<volatile uint8_t*
>(ptr);
113 for(
size_t i = 0; i != n; ++i)
119#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
121#elif defined(BOTAN_TARGET_OS_HAS_WIN32)
122 return ::GetCurrentProcessId();
123#elif defined(BOTAN_TARGET_OS_IS_LLVM) || defined(BOTAN_TARGET_OS_IS_NONE)
126 #error "Missing get_process_id"
131#if defined(BOTAN_TARGET_OS_HAS_GETAUXVAL)
132 return ::getauxval(
id);
133#elif defined(BOTAN_TARGET_OS_IS_ANDROID) && defined(BOTAN_TARGET_ARCH_IS_ARM32)
140 while(*p++ !=
nullptr)
143 Elf32_auxv_t* e =
reinterpret_cast<Elf32_auxv_t*
>(p);
145 while(e !=
nullptr) {
147 return e->a_un.a_val;
152#elif defined(BOTAN_TARGET_OS_HAS_ELF_AUX_INFO)
153 unsigned long auxinfo = 0;
154 ::elf_aux_info(
static_cast<int>(
id), &auxinfo,
sizeof(auxinfo));
156#elif defined(BOTAN_TARGET_OS_HAS_AUXINFO)
157 for(
const AuxInfo* auxinfo =
static_cast<AuxInfo*
>(::_dlauxinfo()); auxinfo != AT_NULL; ++auxinfo) {
158 if(
id == auxinfo->a_type)
170#if defined(AT_SECURE)
172#elif defined(BOTAN_TARGET_OS_HAS_POSIX1)
173 return (::getuid() != ::geteuid()) || (::getgid() != ::getegid());
182#if defined(BOTAN_TARGET_OS_HAS_WIN32)
184 ::QueryPerformanceCounter(&tv);
187#elif defined(BOTAN_USE_GCC_INLINE_ASM)
189 #if defined(BOTAN_TARGET_CPU_IS_X86_FAMILY)
191 if(CPUID::has_rdtsc()) {
192 uint32_t rtc_low = 0, rtc_high = 0;
193 asm volatile(
"rdtsc" :
"=d"(rtc_high),
"=a"(rtc_low));
194 rtc = (
static_cast<uint64_t
>(rtc_high) << 32) | rtc_low;
197 #elif defined(BOTAN_TARGET_ARCH_IS_PPC64)
200 uint32_t rtc_low = 0, rtc_high = 0, rtc_high2 = 0;
201 asm volatile(
"mftbu %0" :
"=r"(rtc_high));
202 asm volatile(
"mftb %0" :
"=r"(rtc_low));
203 asm volatile(
"mftbu %0" :
"=r"(rtc_high2));
205 if(rtc_high == rtc_high2) {
206 rtc = (
static_cast<uint64_t
>(rtc_high) << 32) | rtc_low;
211 #elif defined(BOTAN_TARGET_ARCH_IS_ALPHA)
212 asm volatile(
"rpcc %0" :
"=r"(rtc));
215 #elif defined(BOTAN_TARGET_ARCH_IS_SPARC64) && !defined(BOTAN_TARGET_OS_IS_OPENBSD)
216 asm volatile(
"rd %%tick, %0" :
"=r"(rtc));
218 #elif defined(BOTAN_TARGET_ARCH_IS_IA64)
219 asm volatile(
"mov %0=ar.itc" :
"=r"(rtc));
221 #elif defined(BOTAN_TARGET_ARCH_IS_S390X)
222 asm volatile(
"stck 0(%0)" : :
"a"(&rtc) :
"memory",
"cc");
224 #elif defined(BOTAN_TARGET_ARCH_IS_HPPA)
225 asm volatile(
"mfctl 16,%0" :
"=r"(rtc));
237#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
239 #if defined(_SC_NPROCESSORS_ONLN)
240 const long cpu_online = ::sysconf(_SC_NPROCESSORS_ONLN);
242 return static_cast<size_t>(cpu_online);
246 #if defined(_SC_NPROCESSORS_CONF)
247 const long cpu_conf = ::sysconf(_SC_NPROCESSORS_CONF);
249 return static_cast<size_t>(cpu_conf);
255#if defined(BOTAN_TARGET_OS_HAS_THREADS)
258 const size_t hw_concur = std::thread::hardware_concurrency();
273#if defined(BOTAN_TARGET_OS_IS_EMSCRIPTEN)
274 return emscripten_get_now();
284#if defined(BOTAN_TARGET_OS_HAS_CLOCK_GETTIME)
287 const clockid_t clock_types[] = {
288 #if defined(CLOCK_MONOTONIC_HR)
291 #if defined(CLOCK_MONOTONIC_RAW)
294 #if defined(CLOCK_MONOTONIC)
297 #if defined(CLOCK_PROCESS_CPUTIME_ID)
298 CLOCK_PROCESS_CPUTIME_ID,
300 #if defined(CLOCK_THREAD_CPUTIME_ID)
301 CLOCK_THREAD_CPUTIME_ID,
305 for(clockid_t clock : clock_types) {
307 if(::clock_gettime(clock, &ts) == 0) {
308 return (
static_cast<uint64_t
>(ts.tv_sec) * 1000000000) +
static_cast<uint64_t
>(ts.tv_nsec);
314 auto now = std::chrono::high_resolution_clock::now().time_since_epoch();
315 return std::chrono::duration_cast<std::chrono::nanoseconds>(now).count();
319#if defined(BOTAN_TARGET_OS_HAS_CLOCK_GETTIME)
321 if(::clock_gettime(CLOCK_REALTIME, &ts) == 0) {
322 return (
static_cast<uint64_t
>(ts.tv_sec) * 1000000000) +
static_cast<uint64_t
>(ts.tv_nsec);
326 auto now = std::chrono::system_clock::now().time_since_epoch();
327 return std::chrono::duration_cast<std::chrono::nanoseconds>(now).count();
333#if defined(BOTAN_TARGET_OS_HAS_WIN32)
334 localtime_s(&tm, &time);
335#elif defined(BOTAN_TARGET_OS_HAS_POSIX1)
336 localtime_r(&time, &tm);
338 if(
auto tmp = std::localtime(&time)) {
345 std::ostringstream oss;
346 oss << std::put_time(&tm, format.c_str());
351 const size_t default_page_size = 4096;
353#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
354 long p = ::sysconf(_SC_PAGESIZE);
356 return static_cast<size_t>(p);
358 return default_page_size;
360#elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
362 SYSTEM_INFO sys_info;
363 ::GetSystemInfo(&sys_info);
364 return sys_info.dwPageSize;
366 return default_page_size;
379 const size_t max_locked_kb = 512;
385#if defined(RLIMIT_MEMLOCK) && defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
386 const size_t mlock_requested =
389 if(mlock_requested > 0) {
390 struct ::rlimit limits;
392 ::getrlimit(RLIMIT_MEMLOCK, &limits);
394 if(limits.rlim_cur < limits.rlim_max) {
395 limits.rlim_cur = limits.rlim_max;
396 ::setrlimit(RLIMIT_MEMLOCK, &limits);
397 ::getrlimit(RLIMIT_MEMLOCK, &limits);
400 return std::min<size_t>(limits.rlim_cur, mlock_requested * 1024);
403#elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
404 const size_t mlock_requested =
407 SIZE_T working_min = 0, working_max = 0;
408 if(!::GetProcessWorkingSetSize(::GetCurrentProcess(), &working_min, &working_max)) {
419 if(working_min > overhead) {
420 const size_t lockable_bytes = working_min - overhead;
421 return std::min<size_t>(lockable_bytes, mlock_requested * 1024);
438#if defined(BOTAN_TARGET_OS_HAS_WIN32) && defined(BOTAN_BUILD_COMPILER_IS_MSVC)
439 const std::string
name(name_view);
442 if(getenv_s(&req_size, val,
sizeof(val),
name.c_str()) == 0) {
446 if(req_size > 0 && val[req_size - 1] ==
'\0') {
447 value_out = std::string(val);
449 value_out = std::string(val, req_size);
454 const std::string
name(name_view);
455 if(
const char* val = std::getenv(
name.c_str())) {
468 const size_t val = std::stoul(value,
nullptr);
470 }
catch(std::exception&) {
477#if defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
482 #if defined(BOTAN_TARGET_OS_IS_IOS) || defined(BOTAN_TARGET_OS_IS_MACOS)
485 static constexpr int default_locked_fd = 255;
486 int locked_fd = default_locked_fd;
488 if(
size_t locked_fdl = OS::read_env_variable_sz(
"BOTAN_LOCKED_FD", default_locked_fd)) {
489 if(locked_fdl < 240 || locked_fdl > 255) {
490 locked_fdl = default_locked_fd;
492 locked_fd =
static_cast<int>(locked_fdl);
494 return VM_MAKE_TAG(locked_fd);
505 std::vector<void*> result;
507#if(defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)) || \
508 defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
510 result.reserve(count);
514 #if defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
515 static const int locked_fd = get_locked_fd();
518 for(
size_t i = 0; i != count; ++i) {
521 #if defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
523 int mmap_flags = MAP_PRIVATE;
525 #if defined(MAP_ANONYMOUS)
526 mmap_flags |= MAP_ANONYMOUS;
527 #elif defined(MAP_ANON)
528 mmap_flags |= MAP_ANON;
531 #if defined(MAP_CONCEAL)
532 mmap_flags |= MAP_CONCEAL;
533 #elif defined(MAP_NOCORE)
534 mmap_flags |= MAP_NOCORE;
537 int mmap_prot = PROT_READ | PROT_WRITE;
539 #if defined(PROT_MAX)
540 mmap_prot |= PROT_MAX(mmap_prot);
543 ptr = ::mmap(
nullptr,
550 if(ptr == MAP_FAILED) {
555 if(::mlock(
static_cast<uint8_t*
>(ptr) + page_size, page_size) != 0) {
556 ::munmap(ptr, 3 * page_size);
560 #if defined(MADV_DONTDUMP)
562 ::madvise(
static_cast<uint8_t*
>(ptr) + page_size, page_size, MADV_DONTDUMP);
565 #elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
566 ptr = ::VirtualAlloc(
nullptr, 3 * page_size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
571 if(::VirtualLock(
static_cast<uint8_t*
>(ptr) + page_size, page_size) == 0) {
572 ::VirtualFree(ptr, 0, MEM_RELEASE);
577 std::memset(ptr, 0, 3 * page_size);
586 result.push_back(
static_cast<uint8_t*
>(ptr) + page_size);
596#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
598 ::mprotect(page, page_size, PROT_READ | PROT_WRITE);
599#elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
602 ::VirtualProtect(page, page_size, PAGE_READWRITE, &old_perms);
610#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
612 ::mprotect(page, page_size, PROT_NONE);
613#elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
616 ::VirtualProtect(page, page_size, PAGE_NOACCESS, &old_perms);
626 for(
size_t i = 0; i != pages.size(); ++i) {
627 void* ptr = pages[i];
635#if defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
636 ::munlock(ptr, page_size);
637 ::munmap(
static_cast<uint8_t*
>(ptr) - page_size, 3 * page_size);
638#elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
639 ::VirtualUnlock(ptr, page_size);
640 ::VirtualFree(
static_cast<uint8_t*
>(ptr) - page_size, 0, MEM_RELEASE);
646#if defined(BOTAN_TARGET_OS_HAS_PRCTL) && defined(PR_SET_VMA) && defined(PR_SET_VMA_ANON_NAME)
647 static constexpr char name[] =
"Botan mlock pool";
648 int r = prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME,
reinterpret_cast<uintptr_t
>(page), size,
name);
655#if defined(BOTAN_TARGET_OS_HAS_THREADS)
656void OS::set_thread_name(std::thread& thread,
const std::string&
name) {
657 #if defined(BOTAN_TARGET_OS_IS_LINUX) || defined(BOTAN_TARGET_OS_IS_FREEBSD) || defined(BOTAN_TARGET_OS_IS_DRAGONFLY)
658 static_cast<void>(pthread_setname_np(thread.native_handle(),
name.c_str()));
659 #elif defined(BOTAN_TARGET_OS_IS_OPENBSD)
660 static_cast<void>(pthread_set_name_np(thread.native_handle(),
name.c_str()));
661 #elif defined(BOTAN_TARGET_OS_IS_NETBSD)
662 static_cast<void>(pthread_setname_np(thread.native_handle(),
"%s",
const_cast<char*
>(
name.c_str())));
663 #elif defined(BOTAN_TARGET_OS_HAS_WIN32) && defined(_LIBCPP_HAS_THREAD_API_PTHREAD)
664 static_cast<void>(pthread_setname_np(thread.native_handle(),
name.c_str()));
665 #elif defined(BOTAN_TARGET_OS_HAS_WIN32) && defined(BOTAN_BUILD_COMPILER_IS_MSVC)
666 typedef HRESULT(WINAPI * std_proc)(HANDLE, PCWSTR);
667 HMODULE kern = GetModuleHandleA(
"KernelBase.dll");
668 std_proc set_thread_name =
reinterpret_cast<std_proc
>(GetProcAddress(kern,
"SetThreadDescription"));
669 if(set_thread_name) {
671 auto sz = MultiByteToWideChar(CP_UTF8, 0,
name.data(), -1,
nullptr, 0);
674 if(MultiByteToWideChar(CP_UTF8, 0,
name.data(), -1, &w[0], sz) > 0) {
675 (void)set_thread_name(thread.native_handle(), w.c_str());
679 #elif defined(BOTAN_TARGET_OS_IF_HAIKU)
680 auto thread_id = get_pthread_thread_id(thread.native_handle());
681 static_cast<void>(rename_thread(thread_id,
name.c_str()));
690#if defined(BOTAN_TARGET_OS_HAS_POSIX1) && !defined(BOTAN_TARGET_OS_IS_EMSCRIPTEN)
695::sigjmp_buf g_sigill_jmp_buf;
697void botan_sigill_handler(
int ) {
698 siglongjmp(g_sigill_jmp_buf, 1);
706 volatile int probe_result = -3;
708#if defined(BOTAN_TARGET_OS_HAS_POSIX1) && !defined(BOTAN_TARGET_OS_IS_EMSCRIPTEN)
709 struct sigaction old_sigaction;
710 struct sigaction sigaction;
712 sigaction.sa_handler = botan_sigill_handler;
713 sigemptyset(&sigaction.sa_mask);
714 sigaction.sa_flags = 0;
716 int rc = ::sigaction(SIGILL, &sigaction, &old_sigaction);
719 throw System_Error(
"run_cpu_instruction_probe sigaction failed", errno);
722 rc = sigsetjmp(g_sigill_jmp_buf, 1);
726 probe_result = probe_fn();
733 rc = ::sigaction(SIGILL, &old_sigaction,
nullptr);
735 throw System_Error(
"run_cpu_instruction_probe sigaction restore failed", errno);
746#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
749 POSIX_Echo_Suppression() {
750 m_stdin_fd = fileno(stdin);
751 if(::tcgetattr(m_stdin_fd, &m_old_termios) != 0) {
752 throw System_Error(
"Getting terminal status failed", errno);
755 struct termios noecho_flags = m_old_termios;
756 noecho_flags.c_lflag &= ~ECHO;
757 noecho_flags.c_lflag |= ECHONL;
759 if(::tcsetattr(m_stdin_fd, TCSANOW, &noecho_flags) != 0) {
760 throw System_Error(
"Clearing terminal echo bit failed", errno);
764 void reenable_echo()
override {
766 if(::tcsetattr(m_stdin_fd, TCSANOW, &m_old_termios) != 0) {
767 throw System_Error(
"Restoring terminal echo bit failed", errno);
773 ~POSIX_Echo_Suppression()
override {
779 POSIX_Echo_Suppression(
const POSIX_Echo_Suppression& other) =
delete;
780 POSIX_Echo_Suppression(POSIX_Echo_Suppression&& other) =
delete;
781 POSIX_Echo_Suppression& operator=(
const POSIX_Echo_Suppression& other) =
delete;
782 POSIX_Echo_Suppression& operator=(POSIX_Echo_Suppression&& other) =
delete;
786 struct termios m_old_termios;
789 return std::make_unique<POSIX_Echo_Suppression>();
791#elif defined(BOTAN_TARGET_OS_HAS_WIN32)
795 Win32_Echo_Suppression() {
796 m_input_handle = ::GetStdHandle(STD_INPUT_HANDLE);
797 if(::GetConsoleMode(m_input_handle, &m_console_state) == 0)
798 throw System_Error(
"Getting console mode failed", ::GetLastError());
800 DWORD new_mode = ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT;
801 if(::SetConsoleMode(m_input_handle, new_mode) == 0)
802 throw System_Error(
"Setting console mode failed", ::GetLastError());
805 void reenable_echo()
override {
806 if(m_input_handle != INVALID_HANDLE_VALUE) {
807 if(::SetConsoleMode(m_input_handle, m_console_state) == 0)
808 throw System_Error(
"Setting console mode failed", ::GetLastError());
809 m_input_handle = INVALID_HANDLE_VALUE;
813 ~Win32_Echo_Suppression()
override {
819 Win32_Echo_Suppression(
const Win32_Echo_Suppression& other) =
delete;
820 Win32_Echo_Suppression(Win32_Echo_Suppression&& other) =
delete;
821 Win32_Echo_Suppression& operator=(
const Win32_Echo_Suppression& other) =
delete;
822 Win32_Echo_Suppression& operator=(Win32_Echo_Suppression&& other) =
delete;
825 HANDLE m_input_handle;
826 DWORD m_console_state;
829 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)
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()
void secure_scrub_memory(void *ptr, size_t n)