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

randombit / botan / 10326069803

09 Aug 2024 09:40PM UTC coverage: 91.298% (+0.004%) from 91.294%
10326069803

push

github

web-flow
Merge pull request #4290 from randombit/jack/cpuid-bit-gate

Avoid testing multiple bits in CPUID feature checks

87707 of 96067 relevant lines covered (91.3%)

9287762.81 hits per line

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

68.93
/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_IS_ANDROID) || \
44
   defined(BOTAN_TARGET_OS_HAS_ELF_AUX_INFO)
45
   #include <sys/auxv.h>
46
#endif
47

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

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

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

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>
72
#endif
73

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

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>
80
#endif
81

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

86
namespace Botan {
87

88
// Not defined in OS namespace for historical reasons
89
void secure_scrub_memory(void* ptr, size_t n) {
234,943,705✔
90
#if defined(BOTAN_TARGET_OS_HAS_RTLSECUREZEROMEMORY)
91
   ::RtlSecureZeroMemory(ptr, n);
92

93
#elif defined(BOTAN_TARGET_OS_HAS_EXPLICIT_BZERO)
94
   ::explicit_bzero(ptr, n);
234,943,705✔
95

96
#elif defined(BOTAN_TARGET_OS_HAS_EXPLICIT_MEMSET)
97
   (void)::explicit_memset(ptr, 0, n);
98

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

111
   volatile uint8_t* p = reinterpret_cast<volatile uint8_t*>(ptr);
112

113
   for(size_t i = 0; i != n; ++i)
114
      p[i] = 0;
115
#endif
116
}
234,943,705✔
117

118
uint32_t OS::get_process_id() {
229,041✔
119
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
120
   return ::getpid();
229,041✔
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)
124
   return 0;  // truly no meaningful value
125
#else
126
   #error "Missing get_process_id"
127
#endif
128
}
129

130
bool OS::has_auxval() {
×
131
#if defined(BOTAN_TARGET_OS_HAS_GETAUXVAL)
132
   return true;
×
133
#elif defined(BOTAN_TARGET_OS_IS_ANDROID) && defined(BOTAN_TARGET_ARCH_IS_ARM32)
134
   return true;
135
#elif defined(BOTAN_TARGET_OS_HAS_ELF_AUX_INFO)
136
   return true;
137
#elif defined(BOTAN_TARGET_OS_HAS_AUXINFO)
138
   return true;
139
#else
140
   return false;
141
#endif
142
}
143

144
unsigned long OS::get_auxval(unsigned long id) {
22,294✔
145
#if defined(BOTAN_TARGET_OS_HAS_GETAUXVAL)
146
   return ::getauxval(id);
×
147
#elif defined(BOTAN_TARGET_OS_IS_ANDROID) && defined(BOTAN_TARGET_ARCH_IS_ARM32)
148

149
   if(id == 0)
150
      return 0;
151

152
   char** p = environ;
153

154
   while(*p++ != nullptr)
155
      ;
156

157
   Elf32_auxv_t* e = reinterpret_cast<Elf32_auxv_t*>(p);
158

159
   while(e != nullptr) {
160
      if(e->a_type == id)
161
         return e->a_un.a_val;
162
      e++;
163
   }
164

165
   return 0;
166
#elif defined(BOTAN_TARGET_OS_HAS_ELF_AUX_INFO)
167
   unsigned long auxinfo = 0;
168
   ::elf_aux_info(static_cast<int>(id), &auxinfo, sizeof(auxinfo));
169
   return auxinfo;
170
#elif defined(BOTAN_TARGET_OS_HAS_AUXINFO)
171
   for(const AuxInfo* auxinfo = static_cast<AuxInfo*>(::_dlauxinfo()); auxinfo != AT_NULL; ++auxinfo) {
172
      if(id == auxinfo->a_type)
173
         return auxinfo->a_v;
174
   }
175

176
   return 0;
177
#else
178
   BOTAN_UNUSED(id);
179
   return 0;
180
#endif
181
}
182

183
bool OS::running_in_privileged_state() {
22,294✔
184
#if defined(AT_SECURE)
185
   if(OS::has_auxval()) {
22,294✔
186
      return OS::get_auxval(AT_SECURE) != 0;
×
187
   }
188
#endif
189

190
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
191
   return (::getuid() != ::geteuid()) || (::getgid() != ::getegid());
192
#else
193
   return false;
194
#endif
195
}
196

197
uint64_t OS::get_cpu_cycle_counter() {
7,204,312✔
198
   uint64_t rtc = 0;
7,204,312✔
199

200
#if defined(BOTAN_TARGET_OS_HAS_WIN32)
201
   LARGE_INTEGER tv;
202
   ::QueryPerformanceCounter(&tv);
203
   rtc = tv.QuadPart;
204

205
#elif defined(BOTAN_USE_GCC_INLINE_ASM)
206

207
   #if defined(BOTAN_TARGET_CPU_IS_X86_FAMILY)
208

209
   if(CPUID::has_rdtsc()) {
7,204,312✔
210
      uint32_t rtc_low = 0, rtc_high = 0;
7,204,312✔
211
      asm volatile("rdtsc" : "=d"(rtc_high), "=a"(rtc_low));
7,204,312✔
212
      rtc = (static_cast<uint64_t>(rtc_high) << 32) | rtc_low;
7,204,312✔
213
   }
214

215
   #elif defined(BOTAN_TARGET_ARCH_IS_PPC64)
216

217
   for(;;) {
218
      uint32_t rtc_low = 0, rtc_high = 0, rtc_high2 = 0;
219
      asm volatile("mftbu %0" : "=r"(rtc_high));
220
      asm volatile("mftb %0" : "=r"(rtc_low));
221
      asm volatile("mftbu %0" : "=r"(rtc_high2));
222

223
      if(rtc_high == rtc_high2) {
224
         rtc = (static_cast<uint64_t>(rtc_high) << 32) | rtc_low;
225
         break;
226
      }
227
   }
228

229
   #elif defined(BOTAN_TARGET_ARCH_IS_ALPHA)
230
   asm volatile("rpcc %0" : "=r"(rtc));
231

232
      // OpenBSD does not trap access to the %tick register
233
   #elif defined(BOTAN_TARGET_ARCH_IS_SPARC64) && !defined(BOTAN_TARGET_OS_IS_OPENBSD)
234
   asm volatile("rd %%tick, %0" : "=r"(rtc));
235

236
   #elif defined(BOTAN_TARGET_ARCH_IS_IA64)
237
   asm volatile("mov %0=ar.itc" : "=r"(rtc));
238

239
   #elif defined(BOTAN_TARGET_ARCH_IS_S390X)
240
   asm volatile("stck 0(%0)" : : "a"(&rtc) : "memory", "cc");
241

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

245
   #else
246
      //#warning "OS::get_cpu_cycle_counter not implemented"
247
   #endif
248

249
#endif
250

251
   return rtc;
7,204,312✔
252
}
253

254
size_t OS::get_cpu_available() {
754✔
255
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
256

257
   #if defined(_SC_NPROCESSORS_ONLN)
258
   const long cpu_online = ::sysconf(_SC_NPROCESSORS_ONLN);
754✔
259
   if(cpu_online > 0) {
754✔
260
      return static_cast<size_t>(cpu_online);
754✔
261
   }
262
   #endif
263

264
   #if defined(_SC_NPROCESSORS_CONF)
265
   const long cpu_conf = ::sysconf(_SC_NPROCESSORS_CONF);
×
266
   if(cpu_conf > 0) {
×
267
      return static_cast<size_t>(cpu_conf);
×
268
   }
269
   #endif
270

271
#endif
272

273
#if defined(BOTAN_TARGET_OS_HAS_THREADS)
274
   // hardware_concurrency is allowed to return 0 if the value is not
275
   // well defined or not computable.
276
   const size_t hw_concur = std::thread::hardware_concurrency();
×
277

278
   if(hw_concur > 0) {
×
279
      return hw_concur;
280
   }
281
#endif
282

283
   return 1;
284
}
285

286
uint64_t OS::get_high_resolution_clock() {
4,520✔
287
   if(uint64_t cpu_clock = OS::get_cpu_cycle_counter()) {
4,520✔
288
      return cpu_clock;
289
   }
290

291
#if defined(BOTAN_TARGET_OS_IS_EMSCRIPTEN)
292
   return emscripten_get_now();
293
#endif
294

295
   /*
296
   If we got here either we either don't have an asm instruction
297
   above, or (for x86) RDTSC is not available at runtime. Try some
298
   clock_gettimes and return the first one that works, or otherwise
299
   fall back to std::chrono.
300
   */
301

302
#if defined(BOTAN_TARGET_OS_HAS_CLOCK_GETTIME)
303

304
   // The ordering here is somewhat arbitrary...
305
   const clockid_t clock_types[] = {
×
306
   #if defined(CLOCK_MONOTONIC_HR)
307
      CLOCK_MONOTONIC_HR,
308
   #endif
309
   #if defined(CLOCK_MONOTONIC_RAW)
310
      CLOCK_MONOTONIC_RAW,
311
   #endif
312
   #if defined(CLOCK_MONOTONIC)
313
      CLOCK_MONOTONIC,
314
   #endif
315
   #if defined(CLOCK_PROCESS_CPUTIME_ID)
316
      CLOCK_PROCESS_CPUTIME_ID,
317
   #endif
318
   #if defined(CLOCK_THREAD_CPUTIME_ID)
319
      CLOCK_THREAD_CPUTIME_ID,
320
   #endif
321
   };
322

323
   for(clockid_t clock : clock_types) {
×
324
      struct timespec ts;
×
325
      if(::clock_gettime(clock, &ts) == 0) {
×
326
         return (static_cast<uint64_t>(ts.tv_sec) * 1000000000) + static_cast<uint64_t>(ts.tv_nsec);
×
327
      }
328
   }
329
#endif
330

331
   // Plain C++11 fallback
332
   auto now = std::chrono::high_resolution_clock::now().time_since_epoch();
×
333
   return std::chrono::duration_cast<std::chrono::nanoseconds>(now).count();
×
334
}
335

336
uint64_t OS::get_system_timestamp_ns() {
7,201,097✔
337
#if defined(BOTAN_TARGET_OS_HAS_CLOCK_GETTIME)
338
   struct timespec ts;
7,201,097✔
339
   if(::clock_gettime(CLOCK_REALTIME, &ts) == 0) {
7,201,097✔
340
      return (static_cast<uint64_t>(ts.tv_sec) * 1000000000) + static_cast<uint64_t>(ts.tv_nsec);
7,201,097✔
341
   }
342
#endif
343

344
   auto now = std::chrono::system_clock::now().time_since_epoch();
×
345
   return std::chrono::duration_cast<std::chrono::nanoseconds>(now).count();
×
346
}
347

348
std::string OS::format_time(time_t time, const std::string& format) {
2,419✔
349
   std::tm tm;
2,419✔
350

351
#if defined(BOTAN_TARGET_OS_HAS_WIN32)
352
   localtime_s(&tm, &time);
353
#elif defined(BOTAN_TARGET_OS_HAS_POSIX1)
354
   localtime_r(&time, &tm);
2,419✔
355
#else
356
   if(auto tmp = std::localtime(&time)) {
357
      tm = *tmp;
358
   } else {
359
      throw Encoding_Error("Could not convert time_t to localtime");
360
   }
361
#endif
362

363
   std::ostringstream oss;
2,419✔
364
   oss << std::put_time(&tm, format.c_str());
2,419✔
365
   return oss.str();
4,838✔
366
}
2,419✔
367

368
size_t OS::system_page_size() {
4,443,420✔
369
   const size_t default_page_size = 4096;
4,443,420✔
370

371
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
372
   long p = ::sysconf(_SC_PAGESIZE);
8,628✔
373
   if(p > 1) {
4,443,420✔
374
      return static_cast<size_t>(p);
4,443,420✔
375
   } else {
376
      return default_page_size;
377
   }
378
#elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
379
   BOTAN_UNUSED(default_page_size);
380
   SYSTEM_INFO sys_info;
381
   ::GetSystemInfo(&sys_info);
382
   return sys_info.dwPageSize;
383
#else
384
   return default_page_size;
385
#endif
386
}
387

388
size_t OS::get_memory_locking_limit() {
8,628✔
389
   /*
390
   * Linux defaults to only 64 KiB of mlockable memory per process (too small)
391
   * but BSDs offer a small fraction of total RAM (more than we need). Bound the
392
   * total mlock size to 512 KiB which is enough to run the entire test suite
393
   * without spilling to non-mlock memory (and thus presumably also enough for
394
   * many useful programs), but small enough that we should not cause problems
395
   * even if many processes are mlocking on the same machine.
396
   */
397
   const size_t max_locked_kb = 512;
8,628✔
398

399
   /*
400
   * If RLIMIT_MEMLOCK is not defined, likely the OS does not support
401
   * unprivileged mlock calls.
402
   */
403
#if defined(RLIMIT_MEMLOCK) && defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
404
   const size_t mlock_requested =
8,628✔
405
      std::min<size_t>(read_env_variable_sz("BOTAN_MLOCK_POOL_SIZE", max_locked_kb), max_locked_kb);
8,628✔
406

407
   if(mlock_requested > 0) {
8,628✔
408
      struct ::rlimit limits;
8,628✔
409

410
      ::getrlimit(RLIMIT_MEMLOCK, &limits);
8,628✔
411

412
      if(limits.rlim_cur < limits.rlim_max) {
8,628✔
413
         limits.rlim_cur = limits.rlim_max;
×
414
         ::setrlimit(RLIMIT_MEMLOCK, &limits);
×
415
         ::getrlimit(RLIMIT_MEMLOCK, &limits);
×
416
      }
417

418
      return std::min<size_t>(limits.rlim_cur, mlock_requested * 1024);
17,256✔
419
   }
420

421
#elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
422
   const size_t mlock_requested =
423
      std::min<size_t>(read_env_variable_sz("BOTAN_MLOCK_POOL_SIZE", max_locked_kb), max_locked_kb);
424

425
   SIZE_T working_min = 0, working_max = 0;
426
   if(!::GetProcessWorkingSetSize(::GetCurrentProcess(), &working_min, &working_max)) {
427
      return 0;
428
   }
429

430
   // According to Microsoft MSDN:
431
   // 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
432
   // In the book "Windows Internals Part 2": the maximum lockable pages are minimum working set size - 8 pages
433
   // But the information in the book seems to be inaccurate/outdated
434
   // I've tested this on Windows 8.1 x64, Windows 10 x64 and Windows 7 x86
435
   // On all three OS the value is 11 instead of 8
436
   const size_t overhead = OS::system_page_size() * 11;
437
   if(working_min > overhead) {
438
      const size_t lockable_bytes = working_min - overhead;
439
      return std::min<size_t>(lockable_bytes, mlock_requested * 1024);
440
   }
441
#else
442
   // Not supported on this platform
443
   BOTAN_UNUSED(max_locked_kb);
444
#endif
445

446
   return 0;
447
}
448

449
bool OS::read_env_variable(std::string& value_out, std::string_view name_view) {
22,294✔
450
   value_out = "";
22,294✔
451

452
   if(running_in_privileged_state()) {
22,294✔
453
      return false;
454
   }
455

456
#if defined(BOTAN_TARGET_OS_HAS_WIN32) && defined(BOTAN_BUILD_COMPILER_IS_MSVC)
457
   const std::string name(name_view);
458
   char val[128] = {0};
459
   size_t req_size = 0;
460
   if(getenv_s(&req_size, val, sizeof(val), name.c_str()) == 0) {
461
      // Microsoft's implementation always writes a terminating \0,
462
      // and includes it in the reported length of the environment variable
463
      // if a value exists.
464
      if(req_size > 0 && val[req_size - 1] == '\0') {
465
         value_out = std::string(val);
466
      } else {
467
         value_out = std::string(val, req_size);
468
      }
469
      return true;
470
   }
471
#else
472
   const std::string name(name_view);
22,294✔
473
   if(const char* val = std::getenv(name.c_str())) {
22,294✔
474
      value_out = val;
22,294✔
475
      return true;
476
   }
477
#endif
478

479
   return false;
480
}
22,294✔
481

482
size_t OS::read_env_variable_sz(std::string_view name, size_t def) {
8,628✔
483
   std::string value;
8,628✔
484
   if(read_env_variable(value, name) && !value.empty()) {
8,628✔
485
      try {
×
486
         const size_t val = std::stoul(value, nullptr);
8,628✔
487
         return val;
488
      } catch(std::exception&) { /* ignore it */
×
489
      }
×
490
   }
491

492
   return def;
493
}
8,628✔
494

495
#if defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
496

497
namespace {
498

499
int get_locked_fd() {
500
   #if defined(BOTAN_TARGET_OS_IS_IOS) || defined(BOTAN_TARGET_OS_IS_MACOS)
501
   // On Darwin, tagging anonymous pages allows vmmap to track these.
502
   // Allowed from 240 to 255 for userland applications
503
   static constexpr int default_locked_fd = 255;
504
   int locked_fd = default_locked_fd;
505

506
   if(size_t locked_fdl = OS::read_env_variable_sz("BOTAN_LOCKED_FD", default_locked_fd)) {
507
      if(locked_fdl < 240 || locked_fdl > 255) {
508
         locked_fdl = default_locked_fd;
509
      }
510
      locked_fd = static_cast<int>(locked_fdl);
511
   }
512
   return VM_MAKE_TAG(locked_fd);
513
   #else
514
   return -1;
515
   #endif
516
}
517

518
}  // namespace
519

520
#endif
521

522
std::vector<void*> OS::allocate_locked_pages(size_t count) {
8,628✔
523
   std::vector<void*> result;
8,628✔
524

525
#if(defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)) || \
526
   defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
527

528
   result.reserve(count);
8,628✔
529

530
   const size_t page_size = OS::system_page_size();
8,628✔
531

532
   #if defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
533
   static const int locked_fd = get_locked_fd();
8,628✔
534
   #endif
535

536
   for(size_t i = 0; i != count; ++i) {
1,113,012✔
537
      void* ptr = nullptr;
1,104,384✔
538

539
   #if defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
540

541
      int mmap_flags = MAP_PRIVATE;
1,104,384✔
542

543
      #if defined(MAP_ANONYMOUS)
544
      mmap_flags |= MAP_ANONYMOUS;
1,104,384✔
545
      #elif defined(MAP_ANON)
546
      mmap_flags |= MAP_ANON;
547
      #endif
548

549
      #if defined(MAP_CONCEAL)
550
      mmap_flags |= MAP_CONCEAL;
551
      #elif defined(MAP_NOCORE)
552
      mmap_flags |= MAP_NOCORE;
553
      #endif
554

555
      int mmap_prot = PROT_READ | PROT_WRITE;
1,104,384✔
556

557
      #if defined(PROT_MAX)
558
      mmap_prot |= PROT_MAX(mmap_prot);
559
      #endif
560

561
      ptr = ::mmap(nullptr,
1,104,384✔
562
                   3 * page_size,
563
                   mmap_prot,
564
                   mmap_flags,
565
                   /*fd=*/locked_fd,
566
                   /*offset=*/0);
567

568
      if(ptr == MAP_FAILED) {
1,104,384✔
569
         continue;
×
570
      }
571

572
      // lock the data page
573
      if(::mlock(static_cast<uint8_t*>(ptr) + page_size, page_size) != 0) {
1,104,384✔
574
         ::munmap(ptr, 3 * page_size);
×
575
         continue;
×
576
      }
577

578
      #if defined(MADV_DONTDUMP)
579
      // we ignore errors here, as DONTDUMP is just a bonus
580
      ::madvise(static_cast<uint8_t*>(ptr) + page_size, page_size, MADV_DONTDUMP);
1,104,384✔
581
      #endif
582

583
   #elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
584
      ptr = ::VirtualAlloc(nullptr, 3 * page_size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
585

586
      if(ptr == nullptr)
587
         continue;
588

589
      if(::VirtualLock(static_cast<uint8_t*>(ptr) + page_size, page_size) == 0) {
590
         ::VirtualFree(ptr, 0, MEM_RELEASE);
591
         continue;
592
      }
593
   #endif
594

595
      std::memset(ptr, 0, 3 * page_size);  // zero data page and both guard pages
1,104,384✔
596

597
      // Attempts to name the data page
598
      page_named(ptr, 3 * page_size);
2,208,768✔
599
      // Make guard page preceeding the data page
600
      page_prohibit_access(static_cast<uint8_t*>(ptr));
1,104,384✔
601
      // Make guard page following the data page
602
      page_prohibit_access(static_cast<uint8_t*>(ptr) + 2 * page_size);
1,104,384✔
603

604
      result.push_back(static_cast<uint8_t*>(ptr) + page_size);
1,104,384✔
605
   }
606
#else
607
   BOTAN_UNUSED(count);
608
#endif
609

610
   return result;
8,628✔
611
}
×
612

613
void OS::page_allow_access(void* page) {
2,208,768✔
614
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
615
   const size_t page_size = OS::system_page_size();
2,208,768✔
616
   ::mprotect(page, page_size, PROT_READ | PROT_WRITE);
2,208,768✔
617
#elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
618
   const size_t page_size = OS::system_page_size();
619
   DWORD old_perms = 0;
620
   ::VirtualProtect(page, page_size, PAGE_READWRITE, &old_perms);
621
   BOTAN_UNUSED(old_perms);
622
#else
623
   BOTAN_UNUSED(page);
624
#endif
625
}
2,208,768✔
626

627
void OS::page_prohibit_access(void* page) {
2,208,768✔
628
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
629
   const size_t page_size = OS::system_page_size();
2,208,768✔
630
   ::mprotect(page, page_size, PROT_NONE);
2,208,768✔
631
#elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
632
   const size_t page_size = OS::system_page_size();
633
   DWORD old_perms = 0;
634
   ::VirtualProtect(page, page_size, PAGE_NOACCESS, &old_perms);
635
   BOTAN_UNUSED(old_perms);
636
#else
637
   BOTAN_UNUSED(page);
638
#endif
639
}
2,208,768✔
640

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

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

647
      secure_scrub_memory(ptr, page_size);
1,104,384✔
648

649
      // ptr points to the data page, guard pages are before and after
650
      page_allow_access(static_cast<uint8_t*>(ptr) - page_size);
1,104,384✔
651
      page_allow_access(static_cast<uint8_t*>(ptr) + page_size);
1,104,384✔
652

653
#if defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
654
      ::munlock(ptr, page_size);
1,104,384✔
655
      ::munmap(static_cast<uint8_t*>(ptr) - page_size, 3 * page_size);
1,104,384✔
656
#elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
657
      ::VirtualUnlock(ptr, page_size);
658
      ::VirtualFree(static_cast<uint8_t*>(ptr) - page_size, 0, MEM_RELEASE);
659
#endif
660
   }
661
}
8,628✔
662

663
void OS::page_named(void* page, size_t size) {
1,104,384✔
664
#if defined(BOTAN_TARGET_OS_HAS_PRCTL) && defined(PR_SET_VMA) && defined(PR_SET_VMA_ANON_NAME)
665
   static constexpr char name[] = "Botan mlock pool";
1,104,384✔
666
   int r = prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME, reinterpret_cast<uintptr_t>(page), size, name);
1,104,384✔
667
   BOTAN_UNUSED(r);
1,104,384✔
668
#else
669
   BOTAN_UNUSED(page, size);
670
#endif
671
}
×
672

673
#if defined(BOTAN_TARGET_OS_HAS_THREADS)
674
void OS::set_thread_name(std::thread& thread, const std::string& name) {
3,020✔
675
   #if defined(BOTAN_TARGET_OS_IS_LINUX) || defined(BOTAN_TARGET_OS_IS_FREEBSD) || defined(BOTAN_TARGET_OS_IS_DRAGONFLY)
676
   static_cast<void>(pthread_setname_np(thread.native_handle(), name.c_str()));
3,020✔
677
   #elif defined(BOTAN_TARGET_OS_IS_OPENBSD)
678
   static_cast<void>(pthread_set_name_np(thread.native_handle(), name.c_str()));
679
   #elif defined(BOTAN_TARGET_OS_IS_NETBSD)
680
   static_cast<void>(pthread_setname_np(thread.native_handle(), "%s", const_cast<char*>(name.c_str())));
681
   #elif defined(BOTAN_TARGET_OS_HAS_WIN32) && defined(_LIBCPP_HAS_THREAD_API_PTHREAD)
682
   static_cast<void>(pthread_setname_np(thread.native_handle(), name.c_str()));
683
   #elif defined(BOTAN_TARGET_OS_HAS_WIN32) && defined(BOTAN_BUILD_COMPILER_IS_MSVC)
684
   typedef HRESULT(WINAPI * std_proc)(HANDLE, PCWSTR);
685
   HMODULE kern = GetModuleHandleA("KernelBase.dll");
686
   std_proc set_thread_name = reinterpret_cast<std_proc>(GetProcAddress(kern, "SetThreadDescription"));
687
   if(set_thread_name) {
688
      std::wstring w;
689
      auto sz = MultiByteToWideChar(CP_UTF8, 0, name.data(), -1, nullptr, 0);
690
      if(sz > 0) {
691
         w.resize(sz);
692
         if(MultiByteToWideChar(CP_UTF8, 0, name.data(), -1, &w[0], sz) > 0) {
693
            (void)set_thread_name(thread.native_handle(), w.c_str());
694
         }
695
      }
696
   }
697
   #elif defined(BOTAN_TARGET_OS_IF_HAIKU)
698
   auto thread_id = get_pthread_thread_id(thread.native_handle());
699
   static_cast<void>(rename_thread(thread_id, name.c_str()));
700
   #else
701
   // TODO other possible oses ?
702
   // macOs does not seem to allow to name threads other than the current one.
703
   BOTAN_UNUSED(thread, name);
704
   #endif
705
}
3,020✔
706
#endif
707

708
#if defined(BOTAN_TARGET_OS_HAS_POSIX1) && !defined(BOTAN_TARGET_OS_IS_EMSCRIPTEN)
709

710
namespace {
711

712
// NOLINTNEXTLINE(*-avoid-non-const-global-variables)
713
::sigjmp_buf g_sigill_jmp_buf;
714

715
void botan_sigill_handler(int /*unused*/) {
1✔
716
   siglongjmp(g_sigill_jmp_buf, /*non-zero return value*/ 1);
1✔
717
}
718

719
}  // namespace
720

721
#endif
722

723
int OS::run_cpu_instruction_probe(const std::function<int()>& probe_fn) {
2✔
724
   volatile int probe_result = -3;
2✔
725

726
#if defined(BOTAN_TARGET_OS_HAS_POSIX1) && !defined(BOTAN_TARGET_OS_IS_EMSCRIPTEN)
727
   struct sigaction old_sigaction;
2✔
728
   struct sigaction sigaction;
2✔
729

730
   sigaction.sa_handler = botan_sigill_handler;
2✔
731
   sigemptyset(&sigaction.sa_mask);
2✔
732
   sigaction.sa_flags = 0;
2✔
733

734
   int rc = ::sigaction(SIGILL, &sigaction, &old_sigaction);
2✔
735

736
   if(rc != 0) {
2✔
737
      throw System_Error("run_cpu_instruction_probe sigaction failed", errno);
×
738
   }
739

740
   rc = sigsetjmp(g_sigill_jmp_buf, /*save sigs*/ 1);
3✔
741

742
   if(rc == 0) {
3✔
743
      // first call to sigsetjmp
744
      probe_result = probe_fn();
3✔
745
   } else if(rc == 1) {
1✔
746
      // non-local return from siglongjmp in signal handler: return error
747
      probe_result = -1;
1✔
748
   }
749

750
   // Restore old SIGILL handler, if any
751
   rc = ::sigaction(SIGILL, &old_sigaction, nullptr);
2✔
752
   if(rc != 0) {
2✔
753
      throw System_Error("run_cpu_instruction_probe sigaction restore failed", errno);
×
754
   }
755

756
#else
757
   BOTAN_UNUSED(probe_fn);
758
#endif
759

760
   return probe_result;
2✔
761
}
762

763
std::unique_ptr<OS::Echo_Suppression> OS::suppress_echo_on_terminal() {
×
764
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
765
   class POSIX_Echo_Suppression : public Echo_Suppression {
×
766
      public:
767
         POSIX_Echo_Suppression() {
×
768
            m_stdin_fd = fileno(stdin);
×
769
            if(::tcgetattr(m_stdin_fd, &m_old_termios) != 0) {
×
770
               throw System_Error("Getting terminal status failed", errno);
×
771
            }
772

773
            struct termios noecho_flags = m_old_termios;
×
774
            noecho_flags.c_lflag &= ~ECHO;
×
775
            noecho_flags.c_lflag |= ECHONL;
×
776

777
            if(::tcsetattr(m_stdin_fd, TCSANOW, &noecho_flags) != 0) {
×
778
               throw System_Error("Clearing terminal echo bit failed", errno);
×
779
            }
780
         }
×
781

782
         void reenable_echo() override {
×
783
            if(m_stdin_fd > 0) {
×
784
               if(::tcsetattr(m_stdin_fd, TCSANOW, &m_old_termios) != 0) {
×
785
                  throw System_Error("Restoring terminal echo bit failed", errno);
×
786
               }
787
               m_stdin_fd = -1;
×
788
            }
789
         }
×
790

791
         ~POSIX_Echo_Suppression() override {
×
792
            try {
×
793
               reenable_echo();
×
794
            } catch(...) {}
×
795
         }
×
796

797
         POSIX_Echo_Suppression(const POSIX_Echo_Suppression& other) = delete;
798
         POSIX_Echo_Suppression(POSIX_Echo_Suppression&& other) = delete;
799
         POSIX_Echo_Suppression& operator=(const POSIX_Echo_Suppression& other) = delete;
800
         POSIX_Echo_Suppression& operator=(POSIX_Echo_Suppression&& other) = delete;
801

802
      private:
803
         int m_stdin_fd;
804
         struct termios m_old_termios;
805
   };
806

807
   return std::make_unique<POSIX_Echo_Suppression>();
×
808

809
#elif defined(BOTAN_TARGET_OS_HAS_WIN32)
810

811
   class Win32_Echo_Suppression : public Echo_Suppression {
812
      public:
813
         Win32_Echo_Suppression() {
814
            m_input_handle = ::GetStdHandle(STD_INPUT_HANDLE);
815
            if(::GetConsoleMode(m_input_handle, &m_console_state) == 0)
816
               throw System_Error("Getting console mode failed", ::GetLastError());
817

818
            DWORD new_mode = ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT;
819
            if(::SetConsoleMode(m_input_handle, new_mode) == 0)
820
               throw System_Error("Setting console mode failed", ::GetLastError());
821
         }
822

823
         void reenable_echo() override {
824
            if(m_input_handle != INVALID_HANDLE_VALUE) {
825
               if(::SetConsoleMode(m_input_handle, m_console_state) == 0)
826
                  throw System_Error("Setting console mode failed", ::GetLastError());
827
               m_input_handle = INVALID_HANDLE_VALUE;
828
            }
829
         }
830

831
         ~Win32_Echo_Suppression() override {
832
            try {
833
               reenable_echo();
834
            } catch(...) {}
835
         }
836

837
         Win32_Echo_Suppression(const Win32_Echo_Suppression& other) = delete;
838
         Win32_Echo_Suppression(Win32_Echo_Suppression&& other) = delete;
839
         Win32_Echo_Suppression& operator=(const Win32_Echo_Suppression& other) = delete;
840
         Win32_Echo_Suppression& operator=(Win32_Echo_Suppression&& other) = delete;
841

842
      private:
843
         HANDLE m_input_handle;
844
         DWORD m_console_state;
845
   };
846

847
   return std::make_unique<Win32_Echo_Suppression>();
848

849
#else
850

851
   // Not supported on this platform, return null
852
   return nullptr;
853
#endif
854
}
855

856
}  // 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