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

randombit / botan / 10431738724

17 Aug 2024 11:01AM UTC coverage: 91.275% (-0.002%) from 91.277%
10431738724

push

github

web-flow
Merge pull request #4317 from randombit/jack/remove-android-getauxval-hack

Remove obsolete hack for Android getauxval

87848 of 96245 relevant lines covered (91.28%)

9107098.32 hits per line

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

67.4
/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
#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

80
namespace Botan {
81

82
// Not defined in OS namespace for historical reasons
83
void secure_scrub_memory(void* ptr, size_t n) {
211,343,094✔
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);
211,343,094✔
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
}
211,343,094✔
111

112
uint32_t OS::get_process_id() {
231,690✔
113
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
114
   return ::getpid();
231,690✔
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

124
bool OS::has_auxval() {
×
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

136
unsigned 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

146
unsigned 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

156
unsigned long OS::get_auxval(unsigned long id) {
22,294✔
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

176
bool OS::running_in_privileged_state() {
22,294✔
177
#if defined(AT_SECURE)
178
   if(OS::has_auxval()) {
22,294✔
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

190
uint64_t OS::get_cpu_cycle_counter() {
6,383,182✔
191
   uint64_t rtc = 0;
6,383,182✔
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()) {
6,383,182✔
203
      uint32_t rtc_low = 0, rtc_high = 0;
6,383,182✔
204
      asm volatile("rdtsc" : "=d"(rtc_high), "=a"(rtc_low));
6,383,182✔
205
      rtc = (static_cast<uint64_t>(rtc_high) << 32) | rtc_low;
6,383,182✔
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;
6,383,182✔
245
}
246

247
size_t OS::get_cpu_available() {
754✔
248
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
249

250
   #if defined(_SC_NPROCESSORS_ONLN)
251
   const long cpu_online = ::sysconf(_SC_NPROCESSORS_ONLN);
754✔
252
   if(cpu_online > 0) {
754✔
253
      return static_cast<size_t>(cpu_online);
754✔
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

279
uint64_t OS::get_high_resolution_clock() {
4,589✔
280
   if(uint64_t cpu_clock = OS::get_cpu_cycle_counter()) {
4,589✔
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

329
uint64_t OS::get_system_timestamp_ns() {
6,379,898✔
330
#if defined(BOTAN_TARGET_OS_HAS_CLOCK_GETTIME)
331
   struct timespec ts;
6,379,898✔
332
   if(::clock_gettime(CLOCK_REALTIME, &ts) == 0) {
6,379,898✔
333
      return (static_cast<uint64_t>(ts.tv_sec) * 1000000000) + static_cast<uint64_t>(ts.tv_nsec);
6,379,898✔
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

341
std::string OS::format_time(time_t time, const std::string& format) {
2,412✔
342
   std::tm tm;
2,412✔
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);
2,412✔
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;
2,412✔
357
   oss << std::put_time(&tm, format.c_str());
2,412✔
358
   return oss.str();
4,824✔
359
}
2,412✔
360

361
size_t OS::system_page_size() {
4,443,420✔
362
   const size_t default_page_size = 4096;
4,443,420✔
363

364
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
365
   long p = ::sysconf(_SC_PAGESIZE);
8,628✔
366
   if(p > 1) {
4,443,420✔
367
      return static_cast<size_t>(p);
4,443,420✔
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

381
size_t OS::get_memory_locking_limit() {
8,628✔
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;
8,628✔
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 =
8,628✔
398
      std::min<size_t>(read_env_variable_sz("BOTAN_MLOCK_POOL_SIZE", max_locked_kb), max_locked_kb);
8,628✔
399

400
   if(mlock_requested > 0) {
8,628✔
401
      struct ::rlimit limits;
8,628✔
402

403
      ::getrlimit(RLIMIT_MEMLOCK, &limits);
8,628✔
404

405
      if(limits.rlim_cur < limits.rlim_max) {
8,628✔
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);
17,256✔
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

442
bool OS::read_env_variable(std::string& value_out, std::string_view name_view) {
22,294✔
443
   value_out = "";
22,294✔
444

445
   if(running_in_privileged_state()) {
22,294✔
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);
22,294✔
466
   if(const char* val = std::getenv(name.c_str())) {
22,294✔
467
      value_out = val;
22,294✔
468
      return true;
469
   }
470
#endif
471

472
   return false;
473
}
22,294✔
474

475
size_t OS::read_env_variable_sz(std::string_view name, size_t def) {
8,628✔
476
   std::string value;
8,628✔
477
   if(read_env_variable(value, name) && !value.empty()) {
8,628✔
478
      try {
×
479
         const size_t val = std::stoul(value, nullptr);
8,628✔
480
         return val;
481
      } catch(std::exception&) { /* ignore it */
×
482
      }
×
483
   }
484

485
   return def;
486
}
8,628✔
487

488
#if defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
489

490
namespace {
491

492
int 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

515
std::vector<void*> OS::allocate_locked_pages(size_t count) {
8,628✔
516
   std::vector<void*> result;
8,628✔
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);
8,628✔
522

523
   const size_t page_size = OS::system_page_size();
8,628✔
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();
8,628✔
527
   #endif
528

529
   for(size_t i = 0; i != count; ++i) {
1,113,012✔
530
      void* ptr = nullptr;
1,104,384✔
531

532
   #if defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
533

534
      int mmap_flags = MAP_PRIVATE;
1,104,384✔
535

536
      #if defined(MAP_ANONYMOUS)
537
      mmap_flags |= MAP_ANONYMOUS;
1,104,384✔
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;
1,104,384✔
549

550
      #if defined(PROT_MAX)
551
      mmap_prot |= PROT_MAX(mmap_prot);
552
      #endif
553

554
      ptr = ::mmap(nullptr,
1,104,384✔
555
                   3 * page_size,
556
                   mmap_prot,
557
                   mmap_flags,
558
                   /*fd=*/locked_fd,
559
                   /*offset=*/0);
560

561
      if(ptr == MAP_FAILED) {
1,104,384✔
562
         continue;
×
563
      }
564

565
      // lock the data page
566
      if(::mlock(static_cast<uint8_t*>(ptr) + page_size, page_size) != 0) {
1,104,384✔
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);
1,104,384✔
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
1,104,384✔
589

590
      // Attempts to name the data page
591
      page_named(ptr, 3 * page_size);
2,208,768✔
592
      // Make guard page preceeding the data page
593
      page_prohibit_access(static_cast<uint8_t*>(ptr));
1,104,384✔
594
      // Make guard page following the data page
595
      page_prohibit_access(static_cast<uint8_t*>(ptr) + 2 * page_size);
1,104,384✔
596

597
      result.push_back(static_cast<uint8_t*>(ptr) + page_size);
1,104,384✔
598
   }
599
#else
600
   BOTAN_UNUSED(count);
601
#endif
602

603
   return result;
8,628✔
604
}
×
605

606
void OS::page_allow_access(void* page) {
2,208,768✔
607
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
608
   const size_t page_size = OS::system_page_size();
2,208,768✔
609
   ::mprotect(page, page_size, PROT_READ | PROT_WRITE);
2,208,768✔
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
}
2,208,768✔
619

620
void OS::page_prohibit_access(void* page) {
2,208,768✔
621
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
622
   const size_t page_size = OS::system_page_size();
2,208,768✔
623
   ::mprotect(page, page_size, PROT_NONE);
2,208,768✔
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
}
2,208,768✔
633

634
void OS::free_locked_pages(const std::vector<void*>& pages) {
8,628✔
635
   const size_t page_size = OS::system_page_size();
8,628✔
636

637
   for(size_t i = 0; i != pages.size(); ++i) {
1,113,012✔
638
      void* ptr = pages[i];
1,104,384✔
639

640
      secure_scrub_memory(ptr, page_size);
1,104,384✔
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);
1,104,384✔
644
      page_allow_access(static_cast<uint8_t*>(ptr) + page_size);
1,104,384✔
645

646
#if defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
647
      ::munlock(ptr, page_size);
1,104,384✔
648
      ::munmap(static_cast<uint8_t*>(ptr) - page_size, 3 * page_size);
1,104,384✔
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
}
8,628✔
655

656
void OS::page_named(void* page, size_t size) {
1,104,384✔
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";
1,104,384✔
659
   int r = prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME, reinterpret_cast<uintptr_t>(page), size, name);
1,104,384✔
660
   BOTAN_UNUSED(r);
1,104,384✔
661
#else
662
   BOTAN_UNUSED(page, size);
663
#endif
664
}
×
665

666
#if defined(BOTAN_TARGET_OS_HAS_THREADS)
667
void OS::set_thread_name(std::thread& thread, const std::string& name) {
3,020✔
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()));
3,020✔
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
}
3,020✔
699
#endif
700

701
#if defined(BOTAN_TARGET_OS_HAS_POSIX1) && !defined(BOTAN_TARGET_OS_IS_EMSCRIPTEN)
702

703
namespace {
704

705
// NOLINTNEXTLINE(*-avoid-non-const-global-variables)
706
::sigjmp_buf g_sigill_jmp_buf;
707

708
void botan_sigill_handler(int /*unused*/) {
1✔
709
   siglongjmp(g_sigill_jmp_buf, /*non-zero return value*/ 1);
1✔
710
}
711

712
}  // namespace
713

714
#endif
715

716
int OS::run_cpu_instruction_probe(const std::function<int()>& probe_fn) {
2✔
717
   volatile int probe_result = -3;
2✔
718

719
#if defined(BOTAN_TARGET_OS_HAS_POSIX1) && !defined(BOTAN_TARGET_OS_IS_EMSCRIPTEN)
720
   struct sigaction old_sigaction;
2✔
721
   struct sigaction sigaction;
2✔
722

723
   sigaction.sa_handler = botan_sigill_handler;
2✔
724
   sigemptyset(&sigaction.sa_mask);
2✔
725
   sigaction.sa_flags = 0;
2✔
726

727
   int rc = ::sigaction(SIGILL, &sigaction, &old_sigaction);
2✔
728

729
   if(rc != 0) {
2✔
730
      throw System_Error("run_cpu_instruction_probe sigaction failed", errno);
×
731
   }
732

733
   rc = sigsetjmp(g_sigill_jmp_buf, /*save sigs*/ 1);
3✔
734

735
   if(rc == 0) {
3✔
736
      // first call to sigsetjmp
737
      probe_result = probe_fn();
3✔
738
   } else if(rc == 1) {
1✔
739
      // non-local return from siglongjmp in signal handler: return error
740
      probe_result = -1;
1✔
741
   }
742

743
   // Restore old SIGILL handler, if any
744
   rc = ::sigaction(SIGILL, &old_sigaction, nullptr);
2✔
745
   if(rc != 0) {
2✔
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;
2✔
754
}
755

756
std::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
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

© 2026 Coveralls, Inc