Botan 3.6.1
Crypto and TLS for C&
os_utils.cpp
Go to the documentation of this file.
1/*
2* OS and machine specific utility functions
3* (C) 2015,2016,2017,2018 Jack Lloyd
4* (C) 2016 Daniel Neus
5*
6* Botan is released under the Simplified BSD License (see license.txt)
7*/
8
9#include <botan/internal/os_utils.h>
10
11#include <botan/exceptn.h>
12#include <botan/mem_ops.h>
13#include <botan/internal/cpuid.h>
14
15#include <algorithm>
16#include <chrono>
17#include <cstdlib>
18#include <iomanip>
19#include <sstream>
20
21#if defined(BOTAN_TARGET_OS_HAS_EXPLICIT_BZERO)
22 #include <string.h>
23#endif
24
25#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
26 #include <errno.h>
27 #include <pthread.h>
28 #include <setjmp.h>
29 #include <signal.h>
30 #include <stdlib.h>
31 #include <sys/mman.h>
32 #include <sys/resource.h>
33 #include <sys/types.h>
34 #include <termios.h>
35 #include <unistd.h>
36 #undef B0
37#endif
38
39#if defined(BOTAN_TARGET_OS_IS_EMSCRIPTEN)
40 #include <emscripten/emscripten.h>
41#endif
42
43#if defined(BOTAN_TARGET_OS_HAS_GETAUXVAL) || defined(BOTAN_TARGET_OS_HAS_ELF_AUX_INFO)
44 #include <sys/auxv.h>
45#endif
46
47#if defined(BOTAN_TARGET_OS_HAS_AUXINFO)
48 #include <dlfcn.h>
49 #include <elf.h>
50#endif
51
52#if defined(BOTAN_TARGET_OS_HAS_WIN32)
53 #define NOMINMAX 1
54 #define _WINSOCKAPI_ // stop windows.h including winsock.h
55 #include <windows.h>
56 #if defined(BOTAN_BUILD_COMPILER_IS_MSVC)
57 #include <libloaderapi.h>
58 #include <stringapiset.h>
59 #endif
60#endif
61
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>
66#endif
67
68#if defined(BOTAN_TARGET_OS_HAS_PRCTL)
69 #include <sys/prctl.h>
70#endif
71
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>
74#endif
75
76#if defined(BOTAN_TARGET_OS_IS_HAIKU)
77 #include <kernel/OS.h>
78#endif
79
80namespace Botan {
81
82// Not defined in OS namespace for historical reasons
83void secure_scrub_memory(void* ptr, size_t n) {
84#if defined(BOTAN_TARGET_OS_HAS_RTLSECUREZEROMEMORY)
85 ::RtlSecureZeroMemory(ptr, n);
86
87#elif defined(BOTAN_TARGET_OS_HAS_EXPLICIT_BZERO)
88 ::explicit_bzero(ptr, n);
89
90#elif defined(BOTAN_TARGET_OS_HAS_EXPLICIT_MEMSET)
91 (void)::explicit_memset(ptr, 0, n);
92
93#elif defined(BOTAN_USE_VOLATILE_MEMSET_FOR_ZERO) && (BOTAN_USE_VOLATILE_MEMSET_FOR_ZERO == 1)
94 /*
95 Call memset through a static volatile pointer, which the compiler
96 should not elide. This construct should be safe in conforming
97 compilers, but who knows. I did confirm that on x86-64 GCC 6.1 and
98 Clang 3.8 both create code that saves the memset address in the
99 data segment and unconditionally loads and jumps to that address.
100 */
101 static void* (*const volatile memset_ptr)(void*, int, size_t) = std::memset;
102 (memset_ptr)(ptr, 0, n);
103#else
104
105 volatile uint8_t* p = reinterpret_cast<volatile uint8_t*>(ptr);
106
107 for(size_t i = 0; i != n; ++i)
108 p[i] = 0;
109#endif
110}
111
113#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
114 return ::getpid();
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)
118 return 0; // truly no meaningful value
119#else
120 #error "Missing get_process_id"
121#endif
122}
123
125#if defined(BOTAN_TARGET_OS_HAS_GETAUXVAL)
126 return true;
127#elif defined(BOTAN_TARGET_OS_HAS_ELF_AUX_INFO)
128 return true;
129#elif defined(BOTAN_TARGET_OS_HAS_AUXINFO)
130 return true;
131#else
132 return false;
133#endif
134}
135
136unsigned long OS::auxval_hwcap() {
137#if defined(AT_HWCAP)
138 return AT_HWCAP;
139#else
140 // If the value is not defined in a header we can see,
141 // but auxval is supported, return the Linux/Android value
142 return (OS::has_auxval()) ? 16 : 0;
143#endif
144}
145
146unsigned long OS::auxval_hwcap2() {
147#if defined(AT_HWCAP2)
148 return AT_HWCAP2;
149#else
150 // If the value is not defined in a header we can see,
151 // but auxval is supported, return the Linux/Android value
152 return (OS::has_auxval()) ? 26 : 0;
153#endif
154}
155
156unsigned long OS::get_auxval(unsigned long id) {
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));
162 return 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)
166 return auxinfo->a_v;
167 }
168
169 return 0;
170#else
171 BOTAN_UNUSED(id);
172 return 0;
173#endif
174}
175
177#if defined(AT_SECURE)
178 if(OS::has_auxval()) {
179 return OS::get_auxval(AT_SECURE) != 0;
180 }
181#endif
182
183#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
184 return (::getuid() != ::geteuid()) || (::getgid() != ::getegid());
185#else
186 return false;
187#endif
188}
189
191 uint64_t rtc = 0;
192
193#if defined(BOTAN_TARGET_OS_HAS_WIN32)
194 LARGE_INTEGER tv;
195 ::QueryPerformanceCounter(&tv);
196 rtc = tv.QuadPart;
197
198#elif defined(BOTAN_USE_GCC_INLINE_ASM)
199
200 #if defined(BOTAN_TARGET_CPU_IS_X86_FAMILY)
201
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;
206 }
207
208 #elif defined(BOTAN_TARGET_ARCH_IS_PPC64)
209
210 for(;;) {
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));
215
216 if(rtc_high == rtc_high2) {
217 rtc = (static_cast<uint64_t>(rtc_high) << 32) | rtc_low;
218 break;
219 }
220 }
221
222 #elif defined(BOTAN_TARGET_ARCH_IS_ALPHA)
223 asm volatile("rpcc %0" : "=r"(rtc));
224
225 // OpenBSD does not trap access to the %tick register
226 #elif defined(BOTAN_TARGET_ARCH_IS_SPARC64) && !defined(BOTAN_TARGET_OS_IS_OPENBSD)
227 asm volatile("rd %%tick, %0" : "=r"(rtc));
228
229 #elif defined(BOTAN_TARGET_ARCH_IS_IA64)
230 asm volatile("mov %0=ar.itc" : "=r"(rtc));
231
232 #elif defined(BOTAN_TARGET_ARCH_IS_S390X)
233 asm volatile("stck 0(%0)" : : "a"(&rtc) : "memory", "cc");
234
235 #elif defined(BOTAN_TARGET_ARCH_IS_HPPA)
236 asm volatile("mfctl 16,%0" : "=r"(rtc)); // 64-bit only?
237
238 #else
239 //#warning "OS::get_cpu_cycle_counter not implemented"
240 #endif
241
242#endif
243
244 return rtc;
245}
246
248#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
249
250 #if defined(_SC_NPROCESSORS_ONLN)
251 const long cpu_online = ::sysconf(_SC_NPROCESSORS_ONLN);
252 if(cpu_online > 0) {
253 return static_cast<size_t>(cpu_online);
254 }
255 #endif
256
257 #if defined(_SC_NPROCESSORS_CONF)
258 const long cpu_conf = ::sysconf(_SC_NPROCESSORS_CONF);
259 if(cpu_conf > 0) {
260 return static_cast<size_t>(cpu_conf);
261 }
262 #endif
263
264#endif
265
266#if defined(BOTAN_TARGET_OS_HAS_THREADS)
267 // hardware_concurrency is allowed to return 0 if the value is not
268 // well defined or not computable.
269 const size_t hw_concur = std::thread::hardware_concurrency();
270
271 if(hw_concur > 0) {
272 return hw_concur;
273 }
274#endif
275
276 return 1;
277}
278
280 if(uint64_t cpu_clock = OS::get_cpu_cycle_counter()) {
281 return cpu_clock;
282 }
283
284#if defined(BOTAN_TARGET_OS_IS_EMSCRIPTEN)
285 return emscripten_get_now();
286#endif
287
288 /*
289 If we got here either we either don't have an asm instruction
290 above, or (for x86) RDTSC is not available at runtime. Try some
291 clock_gettimes and return the first one that works, or otherwise
292 fall back to std::chrono.
293 */
294
295#if defined(BOTAN_TARGET_OS_HAS_CLOCK_GETTIME)
296
297 // The ordering here is somewhat arbitrary...
298 const clockid_t clock_types[] = {
299 #if defined(CLOCK_MONOTONIC_HR)
300 CLOCK_MONOTONIC_HR,
301 #endif
302 #if defined(CLOCK_MONOTONIC_RAW)
303 CLOCK_MONOTONIC_RAW,
304 #endif
305 #if defined(CLOCK_MONOTONIC)
306 CLOCK_MONOTONIC,
307 #endif
308 #if defined(CLOCK_PROCESS_CPUTIME_ID)
309 CLOCK_PROCESS_CPUTIME_ID,
310 #endif
311 #if defined(CLOCK_THREAD_CPUTIME_ID)
312 CLOCK_THREAD_CPUTIME_ID,
313 #endif
314 };
315
316 for(clockid_t clock : clock_types) {
317 struct timespec ts;
318 if(::clock_gettime(clock, &ts) == 0) {
319 return (static_cast<uint64_t>(ts.tv_sec) * 1000000000) + static_cast<uint64_t>(ts.tv_nsec);
320 }
321 }
322#endif
323
324 // Plain C++11 fallback
325 auto now = std::chrono::high_resolution_clock::now().time_since_epoch();
326 return std::chrono::duration_cast<std::chrono::nanoseconds>(now).count();
327}
328
330#if defined(BOTAN_TARGET_OS_HAS_CLOCK_GETTIME)
331 struct timespec ts;
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);
334 }
335#endif
336
337 auto now = std::chrono::system_clock::now().time_since_epoch();
338 return std::chrono::duration_cast<std::chrono::nanoseconds>(now).count();
339}
340
341std::string OS::format_time(time_t time, const std::string& format) {
342 std::tm tm;
343
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);
348#else
349 if(auto tmp = std::localtime(&time)) {
350 tm = *tmp;
351 } else {
352 throw Encoding_Error("Could not convert time_t to localtime");
353 }
354#endif
355
356 std::ostringstream oss;
357 oss << std::put_time(&tm, format.c_str());
358 return oss.str();
359}
360
362 const size_t default_page_size = 4096;
363
364#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
365 long p = ::sysconf(_SC_PAGESIZE);
366 if(p > 1) {
367 return static_cast<size_t>(p);
368 } else {
369 return default_page_size;
370 }
371#elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
372 BOTAN_UNUSED(default_page_size);
373 SYSTEM_INFO sys_info;
374 ::GetSystemInfo(&sys_info);
375 return sys_info.dwPageSize;
376#else
377 return default_page_size;
378#endif
379}
380
382 /*
383 * Linux defaults to only 64 KiB of mlockable memory per process (too small)
384 * but BSDs offer a small fraction of total RAM (more than we need). Bound the
385 * total mlock size to 512 KiB which is enough to run the entire test suite
386 * without spilling to non-mlock memory (and thus presumably also enough for
387 * many useful programs), but small enough that we should not cause problems
388 * even if many processes are mlocking on the same machine.
389 */
390 const size_t max_locked_kb = 512;
391
392 /*
393 * If RLIMIT_MEMLOCK is not defined, likely the OS does not support
394 * unprivileged mlock calls.
395 */
396#if defined(RLIMIT_MEMLOCK) && defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
397 const size_t mlock_requested =
398 std::min<size_t>(read_env_variable_sz("BOTAN_MLOCK_POOL_SIZE", max_locked_kb), max_locked_kb);
399
400 if(mlock_requested > 0) {
401 struct ::rlimit limits;
402
403 ::getrlimit(RLIMIT_MEMLOCK, &limits);
404
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);
409 }
410
411 return std::min<size_t>(limits.rlim_cur, mlock_requested * 1024);
412 }
413
414#elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
415 const size_t mlock_requested =
416 std::min<size_t>(read_env_variable_sz("BOTAN_MLOCK_POOL_SIZE", max_locked_kb), max_locked_kb);
417
418 SIZE_T working_min = 0, working_max = 0;
419 if(!::GetProcessWorkingSetSize(::GetCurrentProcess(), &working_min, &working_max)) {
420 return 0;
421 }
422
423 // According to Microsoft MSDN:
424 // The maximum number of pages that a process can lock is equal to the number of pages in its minimum working set minus a small overhead
425 // In the book "Windows Internals Part 2": the maximum lockable pages are minimum working set size - 8 pages
426 // But the information in the book seems to be inaccurate/outdated
427 // I've tested this on Windows 8.1 x64, Windows 10 x64 and Windows 7 x86
428 // On all three OS the value is 11 instead of 8
429 const size_t overhead = OS::system_page_size() * 11;
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);
433 }
434#else
435 // Not supported on this platform
436 BOTAN_UNUSED(max_locked_kb);
437#endif
438
439 return 0;
440}
441
442bool OS::read_env_variable(std::string& value_out, std::string_view name_view) {
443 value_out = "";
444
446 return false;
447 }
448
449#if defined(BOTAN_TARGET_OS_HAS_WIN32) && defined(BOTAN_BUILD_COMPILER_IS_MSVC)
450 const std::string name(name_view);
451 char val[128] = {0};
452 size_t req_size = 0;
453 if(getenv_s(&req_size, val, sizeof(val), name.c_str()) == 0) {
454 // Microsoft's implementation always writes a terminating \0,
455 // and includes it in the reported length of the environment variable
456 // if a value exists.
457 if(req_size > 0 && val[req_size - 1] == '\0') {
458 value_out = std::string(val);
459 } else {
460 value_out = std::string(val, req_size);
461 }
462 return true;
463 }
464#else
465 const std::string name(name_view);
466 if(const char* val = std::getenv(name.c_str())) {
467 value_out = val;
468 return true;
469 }
470#endif
471
472 return false;
473}
474
475size_t OS::read_env_variable_sz(std::string_view name, size_t def) {
476 std::string value;
477 if(read_env_variable(value, name) && !value.empty()) {
478 try {
479 const size_t val = std::stoul(value, nullptr);
480 return val;
481 } catch(std::exception&) { /* ignore it */
482 }
483 }
484
485 return def;
486}
487
488#if defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
489
490namespace {
491
492int get_locked_fd() {
493 #if defined(BOTAN_TARGET_OS_IS_IOS) || defined(BOTAN_TARGET_OS_IS_MACOS)
494 // On Darwin, tagging anonymous pages allows vmmap to track these.
495 // Allowed from 240 to 255 for userland applications
496 static constexpr int default_locked_fd = 255;
497 int locked_fd = default_locked_fd;
498
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;
502 }
503 locked_fd = static_cast<int>(locked_fdl);
504 }
505 return VM_MAKE_TAG(locked_fd);
506 #else
507 return -1;
508 #endif
509}
510
511} // namespace
512
513#endif
514
515std::vector<void*> OS::allocate_locked_pages(size_t count) {
516 std::vector<void*> result;
517
518#if(defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)) || \
519 defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
520
521 result.reserve(count);
522
523 const size_t page_size = OS::system_page_size();
524
525 #if defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
526 static const int locked_fd = get_locked_fd();
527 #endif
528
529 for(size_t i = 0; i != count; ++i) {
530 void* ptr = nullptr;
531
532 #if defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
533
534 int mmap_flags = MAP_PRIVATE;
535
536 #if defined(MAP_ANONYMOUS)
537 mmap_flags |= MAP_ANONYMOUS;
538 #elif defined(MAP_ANON)
539 mmap_flags |= MAP_ANON;
540 #endif
541
542 #if defined(MAP_CONCEAL)
543 mmap_flags |= MAP_CONCEAL;
544 #elif defined(MAP_NOCORE)
545 mmap_flags |= MAP_NOCORE;
546 #endif
547
548 int mmap_prot = PROT_READ | PROT_WRITE;
549
550 #if defined(PROT_MAX)
551 mmap_prot |= PROT_MAX(mmap_prot);
552 #endif
553
554 ptr = ::mmap(nullptr,
555 3 * page_size,
556 mmap_prot,
557 mmap_flags,
558 /*fd=*/locked_fd,
559 /*offset=*/0);
560
561 if(ptr == MAP_FAILED) {
562 continue;
563 }
564
565 // lock the data page
566 if(::mlock(static_cast<uint8_t*>(ptr) + page_size, page_size) != 0) {
567 ::munmap(ptr, 3 * page_size);
568 continue;
569 }
570
571 #if defined(MADV_DONTDUMP)
572 // we ignore errors here, as DONTDUMP is just a bonus
573 ::madvise(static_cast<uint8_t*>(ptr) + page_size, page_size, MADV_DONTDUMP);
574 #endif
575
576 #elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
577 ptr = ::VirtualAlloc(nullptr, 3 * page_size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
578
579 if(ptr == nullptr)
580 continue;
581
582 if(::VirtualLock(static_cast<uint8_t*>(ptr) + page_size, page_size) == 0) {
583 ::VirtualFree(ptr, 0, MEM_RELEASE);
584 continue;
585 }
586 #endif
587
588 std::memset(ptr, 0, 3 * page_size); // zero data page and both guard pages
589
590 // Attempts to name the data page
591 page_named(ptr, 3 * page_size);
592 // Make guard page preceeding the data page
593 page_prohibit_access(static_cast<uint8_t*>(ptr));
594 // Make guard page following the data page
595 page_prohibit_access(static_cast<uint8_t*>(ptr) + 2 * page_size);
596
597 result.push_back(static_cast<uint8_t*>(ptr) + page_size);
598 }
599#else
600 BOTAN_UNUSED(count);
601#endif
602
603 return result;
604}
605
606void OS::page_allow_access(void* page) {
607#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
608 const size_t page_size = OS::system_page_size();
609 ::mprotect(page, page_size, PROT_READ | PROT_WRITE);
610#elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
611 const size_t page_size = OS::system_page_size();
612 DWORD old_perms = 0;
613 ::VirtualProtect(page, page_size, PAGE_READWRITE, &old_perms);
614 BOTAN_UNUSED(old_perms);
615#else
616 BOTAN_UNUSED(page);
617#endif
618}
619
620void OS::page_prohibit_access(void* page) {
621#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
622 const size_t page_size = OS::system_page_size();
623 ::mprotect(page, page_size, PROT_NONE);
624#elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
625 const size_t page_size = OS::system_page_size();
626 DWORD old_perms = 0;
627 ::VirtualProtect(page, page_size, PAGE_NOACCESS, &old_perms);
628 BOTAN_UNUSED(old_perms);
629#else
630 BOTAN_UNUSED(page);
631#endif
632}
633
634void OS::free_locked_pages(const std::vector<void*>& pages) {
635 const size_t page_size = OS::system_page_size();
636
637 for(size_t i = 0; i != pages.size(); ++i) {
638 void* ptr = pages[i];
639
640 secure_scrub_memory(ptr, page_size);
641
642 // ptr points to the data page, guard pages are before and after
643 page_allow_access(static_cast<uint8_t*>(ptr) - page_size);
644 page_allow_access(static_cast<uint8_t*>(ptr) + page_size);
645
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);
652#endif
653 }
654}
655
656void OS::page_named(void* page, size_t size) {
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);
660 BOTAN_UNUSED(r);
661#else
662 BOTAN_UNUSED(page, size);
663#endif
664}
665
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) {
681 std::wstring w;
682 auto sz = MultiByteToWideChar(CP_UTF8, 0, name.data(), -1, nullptr, 0);
683 if(sz > 0) {
684 w.resize(sz);
685 if(MultiByteToWideChar(CP_UTF8, 0, name.data(), -1, &w[0], sz) > 0) {
686 (void)set_thread_name(thread.native_handle(), w.c_str());
687 }
688 }
689 }
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()));
693 #else
694 // TODO other possible oses ?
695 // macOs does not seem to allow to name threads other than the current one.
696 BOTAN_UNUSED(thread, name);
697 #endif
698}
699#endif
700
701#if defined(BOTAN_TARGET_OS_HAS_POSIX1) && !defined(BOTAN_TARGET_OS_IS_EMSCRIPTEN)
702
703namespace {
704
705// NOLINTNEXTLINE(*-avoid-non-const-global-variables)
706::sigjmp_buf g_sigill_jmp_buf;
707
708void botan_sigill_handler(int /*unused*/) {
709 siglongjmp(g_sigill_jmp_buf, /*non-zero return value*/ 1);
710}
711
712} // namespace
713
714#endif
715
716int OS::run_cpu_instruction_probe(const std::function<int()>& probe_fn) {
717 volatile int probe_result = -3;
718
719#if defined(BOTAN_TARGET_OS_HAS_POSIX1) && !defined(BOTAN_TARGET_OS_IS_EMSCRIPTEN)
720 struct sigaction old_sigaction;
721 struct sigaction sigaction;
722
723 sigaction.sa_handler = botan_sigill_handler;
724 sigemptyset(&sigaction.sa_mask);
725 sigaction.sa_flags = 0;
726
727 int rc = ::sigaction(SIGILL, &sigaction, &old_sigaction);
728
729 if(rc != 0) {
730 throw System_Error("run_cpu_instruction_probe sigaction failed", errno);
731 }
732
733 rc = sigsetjmp(g_sigill_jmp_buf, /*save sigs*/ 1);
734
735 if(rc == 0) {
736 // first call to sigsetjmp
737 probe_result = probe_fn();
738 } else if(rc == 1) {
739 // non-local return from siglongjmp in signal handler: return error
740 probe_result = -1;
741 }
742
743 // Restore old SIGILL handler, if any
744 rc = ::sigaction(SIGILL, &old_sigaction, nullptr);
745 if(rc != 0) {
746 throw System_Error("run_cpu_instruction_probe sigaction restore failed", errno);
747 }
748
749#else
750 BOTAN_UNUSED(probe_fn);
751#endif
752
753 return probe_result;
754}
755
756std::unique_ptr<OS::Echo_Suppression> OS::suppress_echo_on_terminal() {
757#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
758 class POSIX_Echo_Suppression : public Echo_Suppression {
759 public:
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);
764 }
765
766 struct termios noecho_flags = m_old_termios;
767 noecho_flags.c_lflag &= ~ECHO;
768 noecho_flags.c_lflag |= ECHONL;
769
770 if(::tcsetattr(m_stdin_fd, TCSANOW, &noecho_flags) != 0) {
771 throw System_Error("Clearing terminal echo bit failed", errno);
772 }
773 }
774
775 void reenable_echo() override {
776 if(m_stdin_fd > 0) {
777 if(::tcsetattr(m_stdin_fd, TCSANOW, &m_old_termios) != 0) {
778 throw System_Error("Restoring terminal echo bit failed", errno);
779 }
780 m_stdin_fd = -1;
781 }
782 }
783
784 ~POSIX_Echo_Suppression() override {
785 try {
786 reenable_echo();
787 } catch(...) {}
788 }
789
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;
794
795 private:
796 int m_stdin_fd;
797 struct termios m_old_termios;
798 };
799
800 return std::make_unique<POSIX_Echo_Suppression>();
801
802#elif defined(BOTAN_TARGET_OS_HAS_WIN32)
803
804 class Win32_Echo_Suppression : public Echo_Suppression {
805 public:
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());
810
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());
814 }
815
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;
821 }
822 }
823
824 ~Win32_Echo_Suppression() override {
825 try {
826 reenable_echo();
827 } catch(...) {}
828 }
829
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;
834
835 private:
836 HANDLE m_input_handle;
837 DWORD m_console_state;
838 };
839
840 return std::make_unique<Win32_Echo_Suppression>();
841
842#else
843
844 // Not supported on this platform, return null
845 return nullptr;
846#endif
847}
848
849} // namespace Botan
#define BOTAN_UNUSED
Definition assert.h:118
std::string name
bool running_in_privileged_state()
Definition os_utils.cpp:176
size_t get_memory_locking_limit()
Definition os_utils.cpp:381
uint64_t BOTAN_TEST_API get_high_resolution_clock()
Definition os_utils.cpp:279
size_t BOTAN_TEST_API get_cpu_available()
Definition os_utils.cpp:247
std::unique_ptr< Echo_Suppression > BOTAN_UNSTABLE_API suppress_echo_on_terminal()
Definition os_utils.cpp:756
size_t read_env_variable_sz(std::string_view var_name, size_t def_value=0)
Definition os_utils.cpp:475
void page_allow_access(void *page)
Definition os_utils.cpp:606
unsigned long auxval_hwcap()
Definition os_utils.cpp:136
bool has_auxval()
Definition os_utils.cpp:124
std::string BOTAN_TEST_API format_time(time_t time, const std::string &format)
Definition os_utils.cpp:341
bool read_env_variable(std::string &value_out, std::string_view var_name)
Definition os_utils.cpp:442
void page_prohibit_access(void *page)
Definition os_utils.cpp:620
int BOTAN_TEST_API run_cpu_instruction_probe(const std::function< int()> &probe_fn)
Definition os_utils.cpp:716
std::vector< void * > allocate_locked_pages(size_t count)
Definition os_utils.cpp:515
size_t system_page_size()
Definition os_utils.cpp:361
uint64_t BOTAN_TEST_API get_system_timestamp_ns()
Definition os_utils.cpp:329
unsigned long get_auxval(unsigned long id)
Definition os_utils.cpp:156
void free_locked_pages(const std::vector< void * > &pages)
Definition os_utils.cpp:634
void page_named(void *page, size_t size)
Definition os_utils.cpp:656
uint32_t BOTAN_TEST_API get_process_id()
Definition os_utils.cpp:112
uint64_t BOTAN_TEST_API get_cpu_cycle_counter()
Definition os_utils.cpp:190
unsigned long auxval_hwcap2()
Definition os_utils.cpp:146
void secure_scrub_memory(void *ptr, size_t n)
Definition os_utils.cpp:83