• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

randombit / botan / 6512413501

13 Oct 2023 07:39PM UTC coverage: 91.708% (-0.005%) from 91.713%
6512413501

push

github

web-flow
Merge pull request #3758 from randombit/thread_debug_haiku

OS::set_thread_name for Haiku using native BeOS api

80033 of 87269 relevant lines covered (91.71%)

8647163.37 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

66.67
/src/lib/utils/os_utils.cpp
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

19
#if defined(BOTAN_TARGET_OS_HAS_EXPLICIT_BZERO)
20
   #include <string.h>
21
#endif
22

23
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
24
   #include <errno.h>
25
   #include <pthread.h>
26
   #include <setjmp.h>
27
   #include <signal.h>
28
   #include <stdlib.h>
29
   #include <sys/mman.h>
30
   #include <sys/resource.h>
31
   #include <sys/types.h>
32
   #include <termios.h>
33
   #include <unistd.h>
34
   #undef B0
35
#endif
36

37
#if defined(BOTAN_TARGET_OS_IS_EMSCRIPTEN)
38
   #include <emscripten/emscripten.h>
39
#endif
40

41
#if defined(BOTAN_TARGET_OS_HAS_GETAUXVAL) || defined(BOTAN_TARGET_OS_IS_ANDROID) || \
42
   defined(BOTAN_TARGET_OS_HAS_ELF_AUX_INFO)
43
   #include <sys/auxv.h>
44
#endif
45

46
#if defined(BOTAN_TARGET_OS_HAS_AUXINFO)
47
   #include <dlfcn.h>
48
   #include <elf.h>
49
#endif
50

51
#if defined(BOTAN_TARGET_OS_HAS_WIN32)
52
   #define NOMINMAX 1
53
   #define _WINSOCKAPI_  // stop windows.h including winsock.h
54
   #include <windows.h>
55
   #if defined(BOTAN_BUILD_COMPILER_IS_MSVC)
56
      #include <libloaderapi.h>
57
      #include <stringapiset.h>
58
   #endif
59
#endif
60

61
#if defined(BOTAN_TARGET_OS_IS_ANDROID)
62
   #include <elf.h>
63
extern "C" char** environ;
64
#endif
65

66
#if defined(BOTAN_TARGET_OS_IS_IOS) || defined(BOTAN_TARGET_OS_IS_MACOS)
67
   #include <mach/vm_statistics.h>
68
   #include <sys/sysctl.h>
69
   #include <sys/types.h>
70
#endif
71

72
#if defined(BOTAN_TARGET_OS_HAS_PRCTL)
73
   #include <sys/prctl.h>
74
#endif
75

76
#if defined(BOTAN_TARGET_OS_IS_FREEBSD) || defined(BOTAN_TARGET_OS_IS_OPENBSD)
77
   #include <pthread_np.h>
78
#endif
79

80
#if defined(BOTAN_TARGET_OS_IS_HAIKU)
81
   #include <kernel/OS.h>
82
#endif
83

84
namespace Botan {
85

86
// Not defined in OS namespace for historical reasons
87
void secure_scrub_memory(void* ptr, size_t n) {
230,762,673✔
88
#if defined(BOTAN_TARGET_OS_HAS_RTLSECUREZEROMEMORY)
89
   ::RtlSecureZeroMemory(ptr, n);
90

91
#elif defined(BOTAN_TARGET_OS_HAS_EXPLICIT_BZERO)
92
   ::explicit_bzero(ptr, n);
230,762,673✔
93

94
#elif defined(BOTAN_TARGET_OS_HAS_EXPLICIT_MEMSET)
95
   (void)::explicit_memset(ptr, 0, n);
96

97
#elif defined(BOTAN_USE_VOLATILE_MEMSET_FOR_ZERO) && (BOTAN_USE_VOLATILE_MEMSET_FOR_ZERO == 1)
98
   /*
99
   Call memset through a static volatile pointer, which the compiler
100
   should not elide. This construct should be safe in conforming
101
   compilers, but who knows. I did confirm that on x86-64 GCC 6.1 and
102
   Clang 3.8 both create code that saves the memset address in the
103
   data segment and unconditionally loads and jumps to that address.
104
   */
105
   static void* (*const volatile memset_ptr)(void*, int, size_t) = std::memset;
106
   (memset_ptr)(ptr, 0, n);
107
#else
108

109
   volatile uint8_t* p = reinterpret_cast<volatile uint8_t*>(ptr);
110

111
   for(size_t i = 0; i != n; ++i)
112
      p[i] = 0;
113
#endif
114
}
230,762,673✔
115

116
uint32_t OS::get_process_id() {
217,725✔
117
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
118
   return ::getpid();
217,725✔
119
#elif defined(BOTAN_TARGET_OS_HAS_WIN32)
120
   return ::GetCurrentProcessId();
121
#elif defined(BOTAN_TARGET_OS_IS_LLVM) || defined(BOTAN_TARGET_OS_IS_NONE)
122
   return 0;  // truly no meaningful value
123
#else
124
   #error "Missing get_process_id"
125
#endif
126
}
127

128
unsigned long OS::get_auxval(unsigned long id) {
22,244✔
129
#if defined(BOTAN_TARGET_OS_HAS_GETAUXVAL)
130
   return ::getauxval(id);
×
131
#elif defined(BOTAN_TARGET_OS_IS_ANDROID) && defined(BOTAN_TARGET_ARCH_IS_ARM32)
132

133
   if(id == 0)
134
      return 0;
135

136
   char** p = environ;
137

138
   while(*p++ != nullptr)
139
      ;
140

141
   Elf32_auxv_t* e = reinterpret_cast<Elf32_auxv_t*>(p);
142

143
   while(e != nullptr) {
144
      if(e->a_type == id)
145
         return e->a_un.a_val;
146
      e++;
147
   }
148

149
   return 0;
150
#elif defined(BOTAN_TARGET_OS_HAS_ELF_AUX_INFO)
151
   unsigned long auxinfo = 0;
152
   ::elf_aux_info(static_cast<int>(id), &auxinfo, sizeof(auxinfo));
153
   return auxinfo;
154
#elif defined(BOTAN_TARGET_OS_HAS_AUXINFO)
155
   for(const AuxInfo* auxinfo = static_cast<AuxInfo*>(::_dlauxinfo()); auxinfo != AT_NULL; ++auxinfo) {
156
      if(id == auxinfo->a_type)
157
         return auxinfo->a_v;
158
   }
159

160
   return 0;
161
#else
162
   BOTAN_UNUSED(id);
163
   return 0;
164
#endif
165
}
166

167
bool OS::running_in_privileged_state() {
22,244✔
168
#if defined(AT_SECURE)
169
   return OS::get_auxval(AT_SECURE) != 0;
×
170
#elif defined(BOTAN_TARGET_OS_HAS_POSIX1)
171
   return (::getuid() != ::geteuid()) || (::getgid() != ::getegid());
172
#else
173
   return false;
174
#endif
175
}
176

177
uint64_t OS::get_cpu_cycle_counter() {
3,558,289✔
178
   uint64_t rtc = 0;
3,558,289✔
179

180
#if defined(BOTAN_TARGET_OS_HAS_WIN32)
181
   LARGE_INTEGER tv;
182
   ::QueryPerformanceCounter(&tv);
183
   rtc = tv.QuadPart;
184

185
#elif defined(BOTAN_USE_GCC_INLINE_ASM)
186

187
   #if defined(BOTAN_TARGET_CPU_IS_X86_FAMILY)
188

189
   if(CPUID::has_rdtsc()) {
3,558,289✔
190
      uint32_t rtc_low = 0, rtc_high = 0;
3,558,289✔
191
      asm volatile("rdtsc" : "=d"(rtc_high), "=a"(rtc_low));
3,558,289✔
192
      rtc = (static_cast<uint64_t>(rtc_high) << 32) | rtc_low;
3,558,289✔
193
   }
194

195
   #elif defined(BOTAN_TARGET_ARCH_IS_PPC64)
196

197
   for(;;) {
198
      uint32_t rtc_low = 0, rtc_high = 0, rtc_high2 = 0;
199
      asm volatile("mftbu %0" : "=r"(rtc_high));
200
      asm volatile("mftb %0" : "=r"(rtc_low));
201
      asm volatile("mftbu %0" : "=r"(rtc_high2));
202

203
      if(rtc_high == rtc_high2) {
204
         rtc = (static_cast<uint64_t>(rtc_high) << 32) | rtc_low;
205
         break;
206
      }
207
   }
208

209
   #elif defined(BOTAN_TARGET_ARCH_IS_ALPHA)
210
   asm volatile("rpcc %0" : "=r"(rtc));
211

212
      // OpenBSD does not trap access to the %tick register
213
   #elif defined(BOTAN_TARGET_ARCH_IS_SPARC64) && !defined(BOTAN_TARGET_OS_IS_OPENBSD)
214
   asm volatile("rd %%tick, %0" : "=r"(rtc));
215

216
   #elif defined(BOTAN_TARGET_ARCH_IS_IA64)
217
   asm volatile("mov %0=ar.itc" : "=r"(rtc));
218

219
   #elif defined(BOTAN_TARGET_ARCH_IS_S390X)
220
   asm volatile("stck 0(%0)" : : "a"(&rtc) : "memory", "cc");
221

222
   #elif defined(BOTAN_TARGET_ARCH_IS_HPPA)
223
   asm volatile("mfctl 16,%0" : "=r"(rtc));  // 64-bit only?
224

225
   #else
226
      //#warning "OS::get_cpu_cycle_counter not implemented"
227
   #endif
228

229
#endif
230

231
   return rtc;
3,558,289✔
232
}
233

234
size_t OS::get_cpu_available() {
758✔
235
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
236

237
   #if defined(_SC_NPROCESSORS_ONLN)
238
   const long cpu_online = ::sysconf(_SC_NPROCESSORS_ONLN);
758✔
239
   if(cpu_online > 0) {
758✔
240
      return static_cast<size_t>(cpu_online);
758✔
241
   }
242
   #endif
243

244
   #if defined(_SC_NPROCESSORS_CONF)
245
   const long cpu_conf = ::sysconf(_SC_NPROCESSORS_CONF);
×
246
   if(cpu_conf > 0) {
×
247
      return static_cast<size_t>(cpu_conf);
×
248
   }
249
   #endif
250

251
#endif
252

253
#if defined(BOTAN_TARGET_OS_HAS_THREADS)
254
   // hardware_concurrency is allowed to return 0 if the value is not
255
   // well defined or not computable.
256
   const size_t hw_concur = std::thread::hardware_concurrency();
×
257

258
   if(hw_concur > 0) {
×
259
      return hw_concur;
260
   }
261
#endif
262

263
   return 1;
264
}
265

266
uint64_t OS::get_high_resolution_clock() {
4,501✔
267
   if(uint64_t cpu_clock = OS::get_cpu_cycle_counter()) {
4,501✔
268
      return cpu_clock;
269
   }
270

271
#if defined(BOTAN_TARGET_OS_IS_EMSCRIPTEN)
272
   return emscripten_get_now();
273
#endif
274

275
   /*
276
   If we got here either we either don't have an asm instruction
277
   above, or (for x86) RDTSC is not available at runtime. Try some
278
   clock_gettimes and return the first one that works, or otherwise
279
   fall back to std::chrono.
280
   */
281

282
#if defined(BOTAN_TARGET_OS_HAS_CLOCK_GETTIME)
283

284
   // The ordering here is somewhat arbitrary...
285
   const clockid_t clock_types[] = {
×
286
   #if defined(CLOCK_MONOTONIC_HR)
287
      CLOCK_MONOTONIC_HR,
288
   #endif
289
   #if defined(CLOCK_MONOTONIC_RAW)
290
      CLOCK_MONOTONIC_RAW,
291
   #endif
292
   #if defined(CLOCK_MONOTONIC)
293
      CLOCK_MONOTONIC,
294
   #endif
295
   #if defined(CLOCK_PROCESS_CPUTIME_ID)
296
      CLOCK_PROCESS_CPUTIME_ID,
297
   #endif
298
   #if defined(CLOCK_THREAD_CPUTIME_ID)
299
      CLOCK_THREAD_CPUTIME_ID,
300
   #endif
301
   };
302

303
   for(clockid_t clock : clock_types) {
×
304
      struct timespec ts;
×
305
      if(::clock_gettime(clock, &ts) == 0) {
×
306
         return (static_cast<uint64_t>(ts.tv_sec) * 1000000000) + static_cast<uint64_t>(ts.tv_nsec);
×
307
      }
308
   }
309
#endif
310

311
   // Plain C++11 fallback
312
   auto now = std::chrono::high_resolution_clock::now().time_since_epoch();
×
313
   return std::chrono::duration_cast<std::chrono::nanoseconds>(now).count();
×
314
}
315

316
uint64_t OS::get_system_timestamp_ns() {
3,554,837✔
317
#if defined(BOTAN_TARGET_OS_HAS_CLOCK_GETTIME)
318
   struct timespec ts;
3,554,837✔
319
   if(::clock_gettime(CLOCK_REALTIME, &ts) == 0) {
3,554,837✔
320
      return (static_cast<uint64_t>(ts.tv_sec) * 1000000000) + static_cast<uint64_t>(ts.tv_nsec);
3,554,837✔
321
   }
322
#endif
323

324
   auto now = std::chrono::system_clock::now().time_since_epoch();
×
325
   return std::chrono::duration_cast<std::chrono::nanoseconds>(now).count();
×
326
}
327

328
size_t OS::system_page_size() {
4,434,150✔
329
   const size_t default_page_size = 4096;
4,434,150✔
330

331
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
332
   long p = ::sysconf(_SC_PAGESIZE);
8,610✔
333
   if(p > 1) {
4,434,150✔
334
      return static_cast<size_t>(p);
4,434,150✔
335
   } else {
336
      return default_page_size;
337
   }
338
#elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
339
   BOTAN_UNUSED(default_page_size);
340
   SYSTEM_INFO sys_info;
341
   ::GetSystemInfo(&sys_info);
342
   return sys_info.dwPageSize;
343
#else
344
   return default_page_size;
345
#endif
346
}
347

348
size_t OS::get_memory_locking_limit() {
8,610✔
349
   /*
350
   * Linux defaults to only 64 KiB of mlockable memory per process (too small)
351
   * but BSDs offer a small fraction of total RAM (more than we need). Bound the
352
   * total mlock size to 512 KiB which is enough to run the entire test suite
353
   * without spilling to non-mlock memory (and thus presumably also enough for
354
   * many useful programs), but small enough that we should not cause problems
355
   * even if many processes are mlocking on the same machine.
356
   */
357
   const size_t max_locked_kb = 512;
8,610✔
358

359
   /*
360
   * If RLIMIT_MEMLOCK is not defined, likely the OS does not support
361
   * unprivileged mlock calls.
362
   */
363
#if defined(RLIMIT_MEMLOCK) && defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
364
   const size_t mlock_requested =
8,610✔
365
      std::min<size_t>(read_env_variable_sz("BOTAN_MLOCK_POOL_SIZE", max_locked_kb), max_locked_kb);
8,610✔
366

367
   if(mlock_requested > 0) {
8,610✔
368
      struct ::rlimit limits;
8,610✔
369

370
      ::getrlimit(RLIMIT_MEMLOCK, &limits);
8,610✔
371

372
      if(limits.rlim_cur < limits.rlim_max) {
8,610✔
373
         limits.rlim_cur = limits.rlim_max;
×
374
         ::setrlimit(RLIMIT_MEMLOCK, &limits);
×
375
         ::getrlimit(RLIMIT_MEMLOCK, &limits);
×
376
      }
377

378
      return std::min<size_t>(limits.rlim_cur, mlock_requested * 1024);
17,220✔
379
   }
380

381
#elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
382
   const size_t mlock_requested =
383
      std::min<size_t>(read_env_variable_sz("BOTAN_MLOCK_POOL_SIZE", max_locked_kb), max_locked_kb);
384

385
   SIZE_T working_min = 0, working_max = 0;
386
   if(!::GetProcessWorkingSetSize(::GetCurrentProcess(), &working_min, &working_max)) {
387
      return 0;
388
   }
389

390
   // According to Microsoft MSDN:
391
   // 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
392
   // In the book "Windows Internals Part 2": the maximum lockable pages are minimum working set size - 8 pages
393
   // But the information in the book seems to be inaccurate/outdated
394
   // I've tested this on Windows 8.1 x64, Windows 10 x64 and Windows 7 x86
395
   // On all three OS the value is 11 instead of 8
396
   const size_t overhead = OS::system_page_size() * 11;
397
   if(working_min > overhead) {
398
      const size_t lockable_bytes = working_min - overhead;
399
      return std::min<size_t>(lockable_bytes, mlock_requested * 1024);
400
   }
401
#else
402
   // Not supported on this platform
403
   BOTAN_UNUSED(max_locked_kb);
404
#endif
405

406
   return 0;
407
}
408

409
bool OS::read_env_variable(std::string& value_out, std::string_view name_view) {
22,244✔
410
   value_out = "";
22,244✔
411

412
   if(running_in_privileged_state()) {
22,244✔
413
      return false;
414
   }
415

416
#if defined(BOTAN_TARGET_OS_HAS_WIN32) && defined(BOTAN_BUILD_COMPILER_IS_MSVC)
417
   const std::string name(name_view);
418
   char val[128] = {0};
419
   size_t req_size = 0;
420
   if(getenv_s(&req_size, val, sizeof(val), name.c_str()) == 0) {
421
      value_out = std::string(val, req_size);
422
      return true;
423
   }
424
#else
425
   const std::string name(name_view);
22,244✔
426
   if(const char* val = std::getenv(name.c_str())) {
22,244✔
427
      value_out = val;
22,244✔
428
      return true;
429
   }
430
#endif
431

432
   return false;
433
}
22,244✔
434

435
size_t OS::read_env_variable_sz(std::string_view name, size_t def) {
8,610✔
436
   std::string value;
8,610✔
437
   if(read_env_variable(value, name) && !value.empty()) {
8,610✔
438
      try {
×
439
         const size_t val = std::stoul(value, nullptr);
8,610✔
440
         return val;
441
      } catch(std::exception&) { /* ignore it */
×
442
      }
×
443
   }
444

445
   return def;
446
}
8,610✔
447

448
#if defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
449

450
namespace {
451

452
int get_locked_fd() {
453
   #if defined(BOTAN_TARGET_OS_IS_IOS) || defined(BOTAN_TARGET_OS_IS_MACOS)
454
   // On Darwin, tagging anonymous pages allows vmmap to track these.
455
   // Allowed from 240 to 255 for userland applications
456
   static constexpr int default_locked_fd = 255;
457
   int locked_fd = default_locked_fd;
458

459
   if(size_t locked_fdl = OS::read_env_variable_sz("BOTAN_LOCKED_FD", default_locked_fd)) {
460
      if(locked_fdl < 240 || locked_fdl > 255) {
461
         locked_fdl = default_locked_fd;
462
      }
463
      locked_fd = static_cast<int>(locked_fdl);
464
   }
465
   return VM_MAKE_TAG(locked_fd);
466
   #else
467
   return -1;
468
   #endif
469
}
470

471
}  // namespace
472

473
#endif
474

475
std::vector<void*> OS::allocate_locked_pages(size_t count) {
8,610✔
476
   std::vector<void*> result;
8,610✔
477

478
#if(defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)) || \
479
   defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
480

481
   result.reserve(count);
8,610✔
482

483
   const size_t page_size = OS::system_page_size();
8,610✔
484

485
   #if defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
486
   static const int locked_fd = get_locked_fd();
8,610✔
487
   #endif
488

489
   for(size_t i = 0; i != count; ++i) {
1,110,690✔
490
      void* ptr = nullptr;
1,102,080✔
491

492
   #if defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
493

494
      int mmap_flags = MAP_PRIVATE;
1,102,080✔
495

496
      #if defined(MAP_ANONYMOUS)
497
      mmap_flags |= MAP_ANONYMOUS;
1,102,080✔
498
      #elif defined(MAP_ANON)
499
      mmap_flags |= MAP_ANON;
500
      #endif
501

502
      #if defined(MAP_CONCEAL)
503
      mmap_flags |= MAP_CONCEAL;
504
      #elif defined(MAP_NOCORE)
505
      mmap_flags |= MAP_NOCORE;
506
      #endif
507

508
      int mmap_prot = PROT_READ | PROT_WRITE;
1,102,080✔
509

510
      #if defined(PROT_MAX)
511
      mmap_prot |= PROT_MAX(mmap_prot);
512
      #endif
513

514
      ptr = ::mmap(nullptr,
1,102,080✔
515
                   3 * page_size,
516
                   mmap_prot,
517
                   mmap_flags,
518
                   /*fd=*/locked_fd,
519
                   /*offset=*/0);
520

521
      if(ptr == MAP_FAILED) {
1,102,080✔
522
         continue;
×
523
      }
524

525
      // lock the data page
526
      if(::mlock(static_cast<uint8_t*>(ptr) + page_size, page_size) != 0) {
1,102,080✔
527
         ::munmap(ptr, 3 * page_size);
×
528
         continue;
×
529
      }
530

531
      #if defined(MADV_DONTDUMP)
532
      // we ignore errors here, as DONTDUMP is just a bonus
533
      ::madvise(static_cast<uint8_t*>(ptr) + page_size, page_size, MADV_DONTDUMP);
1,102,080✔
534
      #endif
535

536
   #elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
537
      ptr = ::VirtualAlloc(nullptr, 3 * page_size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
538

539
      if(ptr == nullptr)
540
         continue;
541

542
      if(::VirtualLock(static_cast<uint8_t*>(ptr) + page_size, page_size) == 0) {
543
         ::VirtualFree(ptr, 0, MEM_RELEASE);
544
         continue;
545
      }
546
   #endif
547

548
      std::memset(ptr, 0, 3 * page_size);  // zero data page and both guard pages
1,102,080✔
549

550
      // Attempts to name the data page
551
      page_named(ptr, 3 * page_size);
1,102,080✔
552
      // Make guard page preceeding the data page
553
      page_prohibit_access(static_cast<uint8_t*>(ptr));
1,102,080✔
554
      // Make guard page following the data page
555
      page_prohibit_access(static_cast<uint8_t*>(ptr) + 2 * page_size);
1,102,080✔
556

557
      result.push_back(static_cast<uint8_t*>(ptr) + page_size);
1,102,080✔
558
   }
559
#else
560
   BOTAN_UNUSED(count);
561
#endif
562

563
   return result;
8,610✔
564
}
×
565

566
void OS::page_allow_access(void* page) {
2,204,160✔
567
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
568
   const size_t page_size = OS::system_page_size();
2,204,160✔
569
   ::mprotect(page, page_size, PROT_READ | PROT_WRITE);
2,204,160✔
570
#elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
571
   const size_t page_size = OS::system_page_size();
572
   DWORD old_perms = 0;
573
   ::VirtualProtect(page, page_size, PAGE_READWRITE, &old_perms);
574
   BOTAN_UNUSED(old_perms);
575
#else
576
   BOTAN_UNUSED(page);
577
#endif
578
}
2,204,160✔
579

580
void OS::page_prohibit_access(void* page) {
2,204,160✔
581
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
582
   const size_t page_size = OS::system_page_size();
2,204,160✔
583
   ::mprotect(page, page_size, PROT_NONE);
2,204,160✔
584
#elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
585
   const size_t page_size = OS::system_page_size();
586
   DWORD old_perms = 0;
587
   ::VirtualProtect(page, page_size, PAGE_NOACCESS, &old_perms);
588
   BOTAN_UNUSED(old_perms);
589
#else
590
   BOTAN_UNUSED(page);
591
#endif
592
}
2,204,160✔
593

594
void OS::free_locked_pages(const std::vector<void*>& pages) {
8,610✔
595
   const size_t page_size = OS::system_page_size();
8,610✔
596

597
   for(size_t i = 0; i != pages.size(); ++i) {
1,110,690✔
598
      void* ptr = pages[i];
1,102,080✔
599

600
      secure_scrub_memory(ptr, page_size);
1,102,080✔
601

602
      // ptr points to the data page, guard pages are before and after
603
      page_allow_access(static_cast<uint8_t*>(ptr) - page_size);
1,102,080✔
604
      page_allow_access(static_cast<uint8_t*>(ptr) + page_size);
1,102,080✔
605

606
#if defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
607
      ::munlock(ptr, page_size);
1,102,080✔
608
      ::munmap(static_cast<uint8_t*>(ptr) - page_size, 3 * page_size);
1,102,080✔
609
#elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
610
      ::VirtualUnlock(ptr, page_size);
611
      ::VirtualFree(static_cast<uint8_t*>(ptr) - page_size, 0, MEM_RELEASE);
612
#endif
613
   }
614
}
8,610✔
615

616
void OS::page_named(void* page, size_t size) {
×
617
#if defined(BOTAN_TARGET_OS_HAS_PRCTL) && defined(PR_SET_VMA) && defined(PR_SET_VMA_ANON_NAME)
618
   static constexpr char name[] = "Botan mlock pool";
619
   int r = prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME, reinterpret_cast<uintptr_t>(page), size, name);
620
   BOTAN_UNUSED(r);
621
#else
622
   BOTAN_UNUSED(page, size);
×
623
#endif
624
}
×
625

626
#if defined(BOTAN_TARGET_OS_HAS_THREADS)
627
void OS::set_thread_name(std::thread& thread, const std::string& name) {
1,526✔
628
   #if defined(BOTAN_TARGET_OS_IS_LINUX) || defined(BOTAN_TARGET_OS_IS_FREEBSD)
629
   static_cast<void>(pthread_setname_np(thread.native_handle(), name.c_str()));
1,526✔
630
   #elif defined(BOTAN_TARGET_OS_IS_OPENBSD)
631
   static_cast<void>(pthread_set_name_np(thread.native_handle(), name.c_str()));
632
   #elif defined(BOTAN_TARGET_OS_IS_NETBSD)
633
   static_cast<void>(pthread_set_name_np(thread.native_handle(), "%s", const_cast<char*>(name.c_str())));
634
   #elif defined(BOTAN_TARGET_OS_HAS_WIN32) && defined(BOTAN_BUILD_COMPILER_IS_MSVC)
635
   typedef HRESULT(WINAPI * std_proc)(HANDLE, PCWSTR);
636
   HMODULE kern = GetModuleHandleA("KernelBase.dll");
637
   std_proc set_thread_name = reinterpret_cast<std_proc>(GetProcAddress(kern, "SetThreadDescription"));
638
   if(set_thread_name) {
639
      std::wstring w;
640
      auto sz = MultiByteToWideChar(CP_UTF8, 0, name.data(), -1, nullptr, 0);
641
      if(sz > 0) {
642
         w.resize(sz);
643
         if(MultiByteToWideChar(CP_UTF8, 0, name.data(), -1, &w[0], sz) > 0) {
644
            (void)set_thread_name(thread.native_handle(), w.c_str());
645
         }
646
      }
647
   }
648
   #elif defined(BOTAN_TARGET_OS_IF_HAIKU)
649
   auto thread_id = get_pthread_thread_id(thread.native_handle());
650
   static_cast<void>(rename_thread(thread_id, name.c_str()));
651
   #else
652
   // TODO other possible oses ?
653
   // macOs does not seem to allow to name threads other than the current one.
654
   BOTAN_UNUSED(thread, name);
655
   #endif
656
}
1,526✔
657
#endif
658

659
#if defined(BOTAN_TARGET_OS_HAS_POSIX1) && !defined(BOTAN_TARGET_OS_IS_EMSCRIPTEN)
660

661
namespace {
662

663
// NOLINTNEXTLINE(*-avoid-non-const-global-variables)
664
::sigjmp_buf g_sigill_jmp_buf;
665

666
void botan_sigill_handler(int /*unused*/) {
1✔
667
   siglongjmp(g_sigill_jmp_buf, /*non-zero return value*/ 1);
1✔
668
}
669

670
}  // namespace
671

672
#endif
673

674
int OS::run_cpu_instruction_probe(const std::function<int()>& probe_fn) {
2✔
675
   volatile int probe_result = -3;
2✔
676

677
#if defined(BOTAN_TARGET_OS_HAS_POSIX1) && !defined(BOTAN_TARGET_OS_IS_EMSCRIPTEN)
678
   struct sigaction old_sigaction;
2✔
679
   struct sigaction sigaction;
2✔
680

681
   sigaction.sa_handler = botan_sigill_handler;
2✔
682
   sigemptyset(&sigaction.sa_mask);
2✔
683
   sigaction.sa_flags = 0;
2✔
684

685
   int rc = ::sigaction(SIGILL, &sigaction, &old_sigaction);
2✔
686

687
   if(rc != 0) {
2✔
688
      throw System_Error("run_cpu_instruction_probe sigaction failed", errno);
×
689
   }
690

691
   rc = sigsetjmp(g_sigill_jmp_buf, /*save sigs*/ 1);
3✔
692

693
   if(rc == 0) {
3✔
694
      // first call to sigsetjmp
695
      probe_result = probe_fn();
3✔
696
   } else if(rc == 1) {
1✔
697
      // non-local return from siglongjmp in signal handler: return error
698
      probe_result = -1;
1✔
699
   }
700

701
   // Restore old SIGILL handler, if any
702
   rc = ::sigaction(SIGILL, &old_sigaction, nullptr);
2✔
703
   if(rc != 0) {
2✔
704
      throw System_Error("run_cpu_instruction_probe sigaction restore failed", errno);
×
705
   }
706

707
#else
708
   BOTAN_UNUSED(probe_fn);
709
#endif
710

711
   return probe_result;
2✔
712
}
713

714
std::unique_ptr<OS::Echo_Suppression> OS::suppress_echo_on_terminal() {
×
715
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
716
   class POSIX_Echo_Suppression : public Echo_Suppression {
×
717
      public:
718
         POSIX_Echo_Suppression() {
×
719
            m_stdin_fd = fileno(stdin);
×
720
            if(::tcgetattr(m_stdin_fd, &m_old_termios) != 0) {
×
721
               throw System_Error("Getting terminal status failed", errno);
×
722
            }
723

724
            struct termios noecho_flags = m_old_termios;
×
725
            noecho_flags.c_lflag &= ~ECHO;
×
726
            noecho_flags.c_lflag |= ECHONL;
×
727

728
            if(::tcsetattr(m_stdin_fd, TCSANOW, &noecho_flags) != 0) {
×
729
               throw System_Error("Clearing terminal echo bit failed", errno);
×
730
            }
731
         }
×
732

733
         void reenable_echo() override {
×
734
            if(m_stdin_fd > 0) {
×
735
               if(::tcsetattr(m_stdin_fd, TCSANOW, &m_old_termios) != 0) {
×
736
                  throw System_Error("Restoring terminal echo bit failed", errno);
×
737
               }
738
               m_stdin_fd = -1;
×
739
            }
740
         }
×
741

742
         ~POSIX_Echo_Suppression() override {
×
743
            try {
×
744
               reenable_echo();
×
745
            } catch(...) {}
×
746
         }
×
747

748
         POSIX_Echo_Suppression(const POSIX_Echo_Suppression& other) = delete;
749
         POSIX_Echo_Suppression(POSIX_Echo_Suppression&& other) = delete;
750
         POSIX_Echo_Suppression& operator=(const POSIX_Echo_Suppression& other) = delete;
751
         POSIX_Echo_Suppression& operator=(POSIX_Echo_Suppression&& other) = delete;
752

753
      private:
754
         int m_stdin_fd;
755
         struct termios m_old_termios;
756
   };
757

758
   return std::make_unique<POSIX_Echo_Suppression>();
×
759

760
#elif defined(BOTAN_TARGET_OS_HAS_WIN32)
761

762
   class Win32_Echo_Suppression : public Echo_Suppression {
763
      public:
764
         Win32_Echo_Suppression() {
765
            m_input_handle = ::GetStdHandle(STD_INPUT_HANDLE);
766
            if(::GetConsoleMode(m_input_handle, &m_console_state) == 0)
767
               throw System_Error("Getting console mode failed", ::GetLastError());
768

769
            DWORD new_mode = ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT;
770
            if(::SetConsoleMode(m_input_handle, new_mode) == 0)
771
               throw System_Error("Setting console mode failed", ::GetLastError());
772
         }
773

774
         void reenable_echo() override {
775
            if(m_input_handle != INVALID_HANDLE_VALUE) {
776
               if(::SetConsoleMode(m_input_handle, m_console_state) == 0)
777
                  throw System_Error("Setting console mode failed", ::GetLastError());
778
               m_input_handle = INVALID_HANDLE_VALUE;
779
            }
780
         }
781

782
         ~Win32_Echo_Suppression() override {
783
            try {
784
               reenable_echo();
785
            } catch(...) {}
786
         }
787

788
         Win32_Echo_Suppression(const Win32_Echo_Suppression& other) = delete;
789
         Win32_Echo_Suppression(Win32_Echo_Suppression&& other) = delete;
790
         Win32_Echo_Suppression& operator=(const Win32_Echo_Suppression& other) = delete;
791
         Win32_Echo_Suppression& operator=(Win32_Echo_Suppression&& other) = delete;
792

793
      private:
794
         HANDLE m_input_handle;
795
         DWORD m_console_state;
796
   };
797

798
   return std::make_unique<Win32_Echo_Suppression>();
799

800
#else
801

802
   // Not supported on this platform, return null
803
   return nullptr;
804
#endif
805
}
806

807
}  // namespace Botan
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc