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

randombit / botan / 13535848071

26 Feb 2025 03:22AM UTC coverage: 91.695% (-0.001%) from 91.696%
13535848071

push

github

web-flow
Merge pull request #4718 from randombit/jack/split-cpuid

Make cpuid module optional

95832 of 104512 relevant lines covered (91.69%)

11266034.88 hits per line

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

66.67
/src/lib/utils/os_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/target_info.h>
14

15
#if defined(BOTAN_HAS_CPUID)
16
   #include <botan/internal/cpuid.h>
17
#endif
18

19
#include <algorithm>
20
#include <chrono>
21
#include <cstdlib>
22
#include <iomanip>
23
#include <sstream>
24

25
#if defined(BOTAN_TARGET_OS_HAS_EXPLICIT_BZERO)
26
   #include <string.h>
27
#endif
28

29
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
30
   #include <errno.h>
31
   #include <pthread.h>
32
   #include <setjmp.h>
33
   #include <signal.h>
34
   #include <stdlib.h>
35
   #include <sys/mman.h>
36
   #include <sys/resource.h>
37
   #include <sys/types.h>
38
   #include <termios.h>
39
   #include <unistd.h>
40
   #undef B0
41
#endif
42

43
#if defined(BOTAN_TARGET_OS_IS_EMSCRIPTEN)
44
   #include <emscripten/emscripten.h>
45
#endif
46

47
#if defined(BOTAN_TARGET_OS_HAS_GETAUXVAL) || defined(BOTAN_TARGET_OS_HAS_ELF_AUX_INFO)
48
   #include <sys/auxv.h>
49
#endif
50

51
#if defined(BOTAN_TARGET_OS_HAS_AUXINFO)
52
   #include <dlfcn.h>
53
   #include <elf.h>
54
#endif
55

56
#if defined(BOTAN_TARGET_OS_HAS_WIN32)
57
   #define NOMINMAX 1
58
   #define _WINSOCKAPI_  // stop windows.h including winsock.h
59
   #include <windows.h>
60
   #if defined(BOTAN_BUILD_COMPILER_IS_MSVC)
61
      #include <libloaderapi.h>
62
      #include <stringapiset.h>
63
   #endif
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) || defined(BOTAN_TARGET_OS_IS_DRAGONFLY)
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
uint32_t OS::get_process_id() {
192,181✔
87
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
88
   return ::getpid();
192,181✔
89
#elif defined(BOTAN_TARGET_OS_HAS_WIN32)
90
   return ::GetCurrentProcessId();
91
#elif defined(BOTAN_TARGET_OS_IS_LLVM) || defined(BOTAN_TARGET_OS_IS_NONE)
92
   return 0;  // truly no meaningful value
93
#else
94
   #error "Missing get_process_id"
95
#endif
96
}
97

98
namespace {
99

100
#if defined(BOTAN_TARGET_OS_HAS_GETAUXVAL) || defined(BOTAN_TARGET_OS_HAS_ELF_AUX_INFO) || \
101
   defined(BOTAN_TARGET_OS_HAS_AUXINFO)
102

103
   #define BOTAN_TARGET_HAS_AUXVAL_INTERFACE
104
#endif
105

106
std::optional<unsigned long> auxval_hwcap() {
×
107
#if defined(AT_HWCAP)
108
   return AT_HWCAP;
×
109
#elif defined(BOTAN_TARGET_HAS_AUXVAL_INTERFACE)
110
   // If the value is not defined in a header we can see,
111
   // but auxval is supported, return the Linux/Android value
112
   return 16;
113
#else
114
   return {};
115
#endif
116
}
117

118
std::optional<unsigned long> auxval_hwcap2() {
×
119
#if defined(AT_HWCAP2)
120
   return AT_HWCAP2;
×
121
#elif defined(BOTAN_TARGET_HAS_AUXVAL_INTERFACE)
122
   // If the value is not defined in a header we can see,
123
   // but auxval is supported, return the Linux/Android value
124
   return 26;
125
#else
126
   return {};
127
#endif
128
}
129

130
std::optional<unsigned long> get_auxval(std::optional<unsigned long> id) {
22,563✔
131
   if(id) {
×
132
#if defined(BOTAN_TARGET_OS_HAS_GETAUXVAL)
133
      return ::getauxval(*id);
22,563✔
134
#elif defined(BOTAN_TARGET_OS_HAS_ELF_AUX_INFO)
135
      unsigned long auxinfo = 0;
136
      if(::elf_aux_info(static_cast<int>(*id), &auxinfo, sizeof(auxinfo)) == 0) {
137
         return auxinfo;
138
      }
139
#elif defined(BOTAN_TARGET_OS_HAS_AUXINFO)
140
      for(const AuxInfo* auxinfo = static_cast<AuxInfo*>(::_dlauxinfo()); auxinfo != AT_NULL; ++auxinfo) {
141
         if(*id == auxinfo->a_type) {
142
            return auxinfo->a_v;
143
         }
144
      }
145
      // no match; fall off the end and return nullopt
146
#endif
147
   }
148

149
   return {};
150
}
151

152
}  // namespace
153

154
std::optional<std::pair<unsigned long, unsigned long>> OS::get_auxval_hwcap() {
×
155
   if(const auto hwcap = get_auxval(auxval_hwcap())) {
×
156
      // If hwcap worked/was valid, we don't require hwcap2 to also
157
      // succeed but instead will return zeros if it failed.
158
      auto hwcap2 = get_auxval(auxval_hwcap2()).value_or(0);
×
159
      return std::make_pair(*hwcap, hwcap2);
×
160
   } else {
161
      return {};
162
   }
163
}
164

165
namespace {
166

167
/**
168
* Test if we are currently running with elevated permissions
169
* eg setuid, setgid, or with POSIX caps set.
170
*/
171
bool running_in_privileged_state() {
22,563✔
172
#if defined(AT_SECURE)
173
   if(auto at_secure = get_auxval(AT_SECURE)) {
45,126✔
174
      return at_secure != 0;
45,126✔
175
   }
176
#endif
177

178
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
179
   return (::getuid() != ::geteuid()) || (::getgid() != ::getegid());
180
#else
181
   return false;
182
#endif
183
}
184

185
}  // namespace
186

187
uint64_t OS::get_cpu_cycle_counter() {
3,939,585✔
188
   uint64_t rtc = 0;
3,939,585✔
189

190
#if defined(BOTAN_TARGET_OS_HAS_WIN32)
191
   LARGE_INTEGER tv;
192
   ::QueryPerformanceCounter(&tv);
193
   rtc = tv.QuadPart;
194

195
#elif defined(BOTAN_USE_GCC_INLINE_ASM)
196

197
   #if defined(BOTAN_TARGET_ARCH_IS_X86_64)
198

199
   uint32_t rtc_low = 0, rtc_high = 0;
3,939,585✔
200
   asm volatile("rdtsc" : "=d"(rtc_high), "=a"(rtc_low));
3,939,585✔
201
   rtc = (static_cast<uint64_t>(rtc_high) << 32) | rtc_low;
3,939,585✔
202

203
   #elif defined(BOTAN_TARGET_CPU_IS_X86_FAMILY) && defined(BOTAN_HAS_CPUID)
204

205
   if(CPUID::has_rdtsc()) {
206
      uint32_t rtc_low = 0, rtc_high = 0;
207
      asm volatile("rdtsc" : "=d"(rtc_high), "=a"(rtc_low));
208
      rtc = (static_cast<uint64_t>(rtc_high) << 32) | rtc_low;
209
   }
210

211
   #elif defined(BOTAN_TARGET_ARCH_IS_PPC64)
212

213
   for(;;) {
214
      uint32_t rtc_low = 0, rtc_high = 0, rtc_high2 = 0;
215
      asm volatile("mftbu %0" : "=r"(rtc_high));
216
      asm volatile("mftb %0" : "=r"(rtc_low));
217
      asm volatile("mftbu %0" : "=r"(rtc_high2));
218

219
      if(rtc_high == rtc_high2) {
220
         rtc = (static_cast<uint64_t>(rtc_high) << 32) | rtc_low;
221
         break;
222
      }
223
   }
224

225
   #elif defined(BOTAN_TARGET_ARCH_IS_ALPHA)
226
   asm volatile("rpcc %0" : "=r"(rtc));
227

228
      // OpenBSD does not trap access to the %tick register
229
   #elif defined(BOTAN_TARGET_ARCH_IS_SPARC64) && !defined(BOTAN_TARGET_OS_IS_OPENBSD)
230
   asm volatile("rd %%tick, %0" : "=r"(rtc));
231

232
   #elif defined(BOTAN_TARGET_ARCH_IS_IA64)
233
   asm volatile("mov %0=ar.itc" : "=r"(rtc));
234

235
   #elif defined(BOTAN_TARGET_ARCH_IS_S390X)
236
   asm volatile("stck 0(%0)" : : "a"(&rtc) : "memory", "cc");
237

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

241
   #else
242
      //#warning "OS::get_cpu_cycle_counter not implemented"
243
   #endif
244

245
#endif
246

247
   return rtc;
3,939,585✔
248
}
249

250
size_t OS::get_cpu_available() {
799✔
251
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
252

253
   #if defined(_SC_NPROCESSORS_ONLN)
254
   const long cpu_online = ::sysconf(_SC_NPROCESSORS_ONLN);
799✔
255
   if(cpu_online > 0) {
799✔
256
      return static_cast<size_t>(cpu_online);
799✔
257
   }
258
   #endif
259

260
   #if defined(_SC_NPROCESSORS_CONF)
261
   const long cpu_conf = ::sysconf(_SC_NPROCESSORS_CONF);
×
262
   if(cpu_conf > 0) {
×
263
      return static_cast<size_t>(cpu_conf);
×
264
   }
265
   #endif
266

267
#endif
268

269
#if defined(BOTAN_TARGET_OS_HAS_THREADS)
270
   // hardware_concurrency is allowed to return 0 if the value is not
271
   // well defined or not computable.
272
   const size_t hw_concur = std::thread::hardware_concurrency();
×
273

274
   if(hw_concur > 0) {
×
275
      return hw_concur;
276
   }
277
#endif
278

279
   return 1;
280
}
281

282
uint64_t OS::get_high_resolution_clock() {
4,645✔
283
   if(uint64_t cpu_clock = OS::get_cpu_cycle_counter()) {
4,645✔
284
      return cpu_clock;
285
   }
286

287
#if defined(BOTAN_TARGET_OS_IS_EMSCRIPTEN)
288
   return emscripten_get_now();
289
#endif
290

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

298
#if defined(BOTAN_TARGET_OS_HAS_CLOCK_GETTIME)
299

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

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

327
#if defined(BOTAN_TARGET_OS_HAS_SYSTEM_CLOCK)
328
   // Plain C++11 fallback
329
   auto now = std::chrono::high_resolution_clock::now().time_since_epoch();
×
330
   return std::chrono::duration_cast<std::chrono::nanoseconds>(now).count();
×
331
#else
332
   return 0;
333
#endif
334
}
335

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

344
#if defined(BOTAN_TARGET_OS_HAS_SYSTEM_CLOCK)
345
   auto now = std::chrono::system_clock::now().time_since_epoch();
×
346
   return std::chrono::duration_cast<std::chrono::nanoseconds>(now).count();
×
347
#else
348
   throw Not_Implemented("OS::get_system_timestamp_ns this system does not support a clock");
349
#endif
350
}
351

352
std::string OS::format_time(time_t time, const std::string& format) {
2,847✔
353
   std::tm tm;
2,847✔
354

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

367
   std::ostringstream oss;
2,847✔
368
   oss << std::put_time(&tm, format.c_str());
2,847✔
369
   return oss.str();
5,694✔
370
}
2,847✔
371

372
size_t OS::system_page_size() {
4,499,040✔
373
   const size_t default_page_size = 4096;
4,499,040✔
374

375
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
376
   long p = ::sysconf(_SC_PAGESIZE);
8,736✔
377
   if(p > 1) {
4,499,040✔
378
      return static_cast<size_t>(p);
4,499,040✔
379
   } else {
380
      return default_page_size;
381
   }
382
#elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
383
   BOTAN_UNUSED(default_page_size);
384
   SYSTEM_INFO sys_info;
385
   ::GetSystemInfo(&sys_info);
386
   return sys_info.dwPageSize;
387
#else
388
   return default_page_size;
389
#endif
390
}
391

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

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

411
   if(mlock_requested > 0) {
8,736✔
412
      struct ::rlimit limits;
8,736✔
413

414
      ::getrlimit(RLIMIT_MEMLOCK, &limits);
8,736✔
415

416
      if(limits.rlim_cur < limits.rlim_max) {
8,736✔
417
         limits.rlim_cur = limits.rlim_max;
×
418
         ::setrlimit(RLIMIT_MEMLOCK, &limits);
×
419
         ::getrlimit(RLIMIT_MEMLOCK, &limits);
×
420
      }
421

422
      return std::min<size_t>(limits.rlim_cur, mlock_requested * 1024);
17,472✔
423
   }
424

425
#elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
426
   const size_t mlock_requested =
427
      std::min<size_t>(read_env_variable_sz("BOTAN_MLOCK_POOL_SIZE", max_locked_kb), max_locked_kb);
428

429
   SIZE_T working_min = 0, working_max = 0;
430
   if(!::GetProcessWorkingSetSize(::GetCurrentProcess(), &working_min, &working_max)) {
431
      return 0;
432
   }
433

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

450
   return 0;
451
}
452

453
bool OS::read_env_variable(std::string& value_out, std::string_view name_view) {
22,563✔
454
   value_out = "";
22,563✔
455

456
   if(running_in_privileged_state()) {
22,563✔
457
      return false;
458
   }
459

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

483
   return false;
484
}
22,563✔
485

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

496
   return def;
497
}
8,736✔
498

499
#if defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
500

501
namespace {
502

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

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

522
}  // namespace
523

524
#endif
525

526
std::vector<void*> OS::allocate_locked_pages(size_t count) {
8,736✔
527
   std::vector<void*> result;
8,736✔
528

529
#if(defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)) || \
530
   defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
531

532
   result.reserve(count);
8,736✔
533

534
   const size_t page_size = OS::system_page_size();
8,736✔
535

536
   #if defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
537
   static const int locked_fd = get_locked_fd();
8,736✔
538
   #endif
539

540
   for(size_t i = 0; i != count; ++i) {
1,126,944✔
541
      void* ptr = nullptr;
1,118,208✔
542

543
   #if defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
544

545
      int mmap_flags = MAP_PRIVATE;
1,118,208✔
546

547
      #if defined(MAP_ANONYMOUS)
548
      mmap_flags |= MAP_ANONYMOUS;
1,118,208✔
549
      #elif defined(MAP_ANON)
550
      mmap_flags |= MAP_ANON;
551
      #endif
552

553
      #if defined(MAP_CONCEAL)
554
      mmap_flags |= MAP_CONCEAL;
555
      #elif defined(MAP_NOCORE)
556
      mmap_flags |= MAP_NOCORE;
557
      #endif
558

559
      int mmap_prot = PROT_READ | PROT_WRITE;
1,118,208✔
560

561
      #if defined(PROT_MAX)
562
      mmap_prot |= PROT_MAX(mmap_prot);
563
      #endif
564

565
      ptr = ::mmap(nullptr,
1,118,208✔
566
                   3 * page_size,
567
                   mmap_prot,
568
                   mmap_flags,
569
                   /*fd=*/locked_fd,
570
                   /*offset=*/0);
571

572
      if(ptr == MAP_FAILED) {
1,118,208✔
573
         continue;
×
574
      }
575

576
      // lock the data page
577
      if(::mlock(static_cast<uint8_t*>(ptr) + page_size, page_size) != 0) {
1,118,208✔
578
         ::munmap(ptr, 3 * page_size);
×
579
         continue;
×
580
      }
581

582
      #if defined(MADV_DONTDUMP)
583
      // we ignore errors here, as DONTDUMP is just a bonus
584
      ::madvise(static_cast<uint8_t*>(ptr) + page_size, page_size, MADV_DONTDUMP);
1,118,208✔
585
      #endif
586

587
   #elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
588
      ptr = ::VirtualAlloc(nullptr, 3 * page_size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
589

590
      if(ptr == nullptr)
591
         continue;
592

593
      if(::VirtualLock(static_cast<uint8_t*>(ptr) + page_size, page_size) == 0) {
594
         ::VirtualFree(ptr, 0, MEM_RELEASE);
595
         continue;
596
      }
597
   #endif
598

599
      std::memset(ptr, 0, 3 * page_size);  // zero data page and both guard pages
1,118,208✔
600

601
      // Attempts to name the data page
602
      page_named(ptr, 3 * page_size);
2,236,416✔
603
      // Make guard page preceeding the data page
604
      page_prohibit_access(static_cast<uint8_t*>(ptr));
1,118,208✔
605
      // Make guard page following the data page
606
      page_prohibit_access(static_cast<uint8_t*>(ptr) + 2 * page_size);
1,118,208✔
607

608
      result.push_back(static_cast<uint8_t*>(ptr) + page_size);
1,118,208✔
609
   }
610
#else
611
   BOTAN_UNUSED(count);
612
#endif
613

614
   return result;
8,736✔
615
}
×
616

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

631
void OS::page_prohibit_access(void* page) {
2,236,416✔
632
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
633
   const size_t page_size = OS::system_page_size();
2,236,416✔
634
   ::mprotect(page, page_size, PROT_NONE);
2,236,416✔
635
#elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
636
   const size_t page_size = OS::system_page_size();
637
   DWORD old_perms = 0;
638
   ::VirtualProtect(page, page_size, PAGE_NOACCESS, &old_perms);
639
   BOTAN_UNUSED(old_perms);
640
#else
641
   BOTAN_UNUSED(page);
642
#endif
643
}
2,236,416✔
644

645
void OS::free_locked_pages(const std::vector<void*>& pages) {
8,736✔
646
   const size_t page_size = OS::system_page_size();
8,736✔
647

648
   for(size_t i = 0; i != pages.size(); ++i) {
1,126,944✔
649
      void* ptr = pages[i];
1,118,208✔
650

651
      secure_scrub_memory(ptr, page_size);
1,118,208✔
652

653
      // ptr points to the data page, guard pages are before and after
654
      page_allow_access(static_cast<uint8_t*>(ptr) - page_size);
1,118,208✔
655
      page_allow_access(static_cast<uint8_t*>(ptr) + page_size);
1,118,208✔
656

657
#if defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
658
      ::munlock(ptr, page_size);
1,118,208✔
659
      ::munmap(static_cast<uint8_t*>(ptr) - page_size, 3 * page_size);
1,118,208✔
660
#elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
661
      ::VirtualUnlock(ptr, page_size);
662
      ::VirtualFree(static_cast<uint8_t*>(ptr) - page_size, 0, MEM_RELEASE);
663
#endif
664
   }
665
}
8,736✔
666

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

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

712
#if defined(BOTAN_TARGET_OS_HAS_POSIX1) && !defined(BOTAN_TARGET_OS_IS_EMSCRIPTEN)
713

714
namespace {
715

716
// NOLINTNEXTLINE(*-avoid-non-const-global-variables)
717
::sigjmp_buf g_sigill_jmp_buf;
718

719
void botan_sigill_handler(int /*unused*/) {
1✔
720
   siglongjmp(g_sigill_jmp_buf, /*non-zero return value*/ 1);
1✔
721
}
722

723
}  // namespace
724

725
#endif
726

727
int OS::run_cpu_instruction_probe(const std::function<int()>& probe_fn) {
2✔
728
   volatile int probe_result = -3;
2✔
729

730
#if defined(BOTAN_TARGET_OS_HAS_POSIX1) && !defined(BOTAN_TARGET_OS_IS_EMSCRIPTEN)
731
   struct sigaction old_sigaction;
2✔
732
   struct sigaction sigaction;
2✔
733

734
   sigaction.sa_handler = botan_sigill_handler;
2✔
735
   sigemptyset(&sigaction.sa_mask);
2✔
736
   sigaction.sa_flags = 0;
2✔
737

738
   int rc = ::sigaction(SIGILL, &sigaction, &old_sigaction);
2✔
739

740
   if(rc != 0) {
2✔
741
      throw System_Error("run_cpu_instruction_probe sigaction failed", errno);
×
742
   }
743

744
   rc = sigsetjmp(g_sigill_jmp_buf, /*save sigs*/ 1);
3✔
745

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

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

760
#else
761
   BOTAN_UNUSED(probe_fn);
762
#endif
763

764
   return probe_result;
2✔
765
}
766

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

777
            struct termios noecho_flags = m_old_termios;
×
778
            noecho_flags.c_lflag &= ~ECHO;
×
779
            noecho_flags.c_lflag |= ECHONL;
×
780

781
            if(::tcsetattr(m_stdin_fd, TCSANOW, &noecho_flags) != 0) {
×
782
               throw System_Error("Clearing terminal echo bit failed", errno);
×
783
            }
784
         }
×
785

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

795
         ~POSIX_Echo_Suppression() override {
×
796
            try {
×
797
               reenable_echo();
×
798
            } catch(...) {}
×
799
         }
×
800

801
         POSIX_Echo_Suppression(const POSIX_Echo_Suppression& other) = delete;
802
         POSIX_Echo_Suppression(POSIX_Echo_Suppression&& other) = delete;
803
         POSIX_Echo_Suppression& operator=(const POSIX_Echo_Suppression& other) = delete;
804
         POSIX_Echo_Suppression& operator=(POSIX_Echo_Suppression&& other) = delete;
805

806
      private:
807
         int m_stdin_fd;
808
         struct termios m_old_termios;
809
   };
810

811
   return std::make_unique<POSIX_Echo_Suppression>();
×
812

813
#elif defined(BOTAN_TARGET_OS_HAS_WIN32)
814

815
   class Win32_Echo_Suppression : public Echo_Suppression {
816
      public:
817
         Win32_Echo_Suppression() {
818
            m_input_handle = ::GetStdHandle(STD_INPUT_HANDLE);
819
            if(::GetConsoleMode(m_input_handle, &m_console_state) == 0)
820
               throw System_Error("Getting console mode failed", ::GetLastError());
821

822
            DWORD new_mode = ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT;
823
            if(::SetConsoleMode(m_input_handle, new_mode) == 0)
824
               throw System_Error("Setting console mode failed", ::GetLastError());
825
         }
826

827
         void reenable_echo() override {
828
            if(m_input_handle != INVALID_HANDLE_VALUE) {
829
               if(::SetConsoleMode(m_input_handle, m_console_state) == 0)
830
                  throw System_Error("Setting console mode failed", ::GetLastError());
831
               m_input_handle = INVALID_HANDLE_VALUE;
832
            }
833
         }
834

835
         ~Win32_Echo_Suppression() override {
836
            try {
837
               reenable_echo();
838
            } catch(...) {}
839
         }
840

841
         Win32_Echo_Suppression(const Win32_Echo_Suppression& other) = delete;
842
         Win32_Echo_Suppression(Win32_Echo_Suppression&& other) = delete;
843
         Win32_Echo_Suppression& operator=(const Win32_Echo_Suppression& other) = delete;
844
         Win32_Echo_Suppression& operator=(Win32_Echo_Suppression&& other) = delete;
845

846
      private:
847
         HANDLE m_input_handle;
848
         DWORD m_console_state;
849
   };
850

851
   return std::make_unique<Win32_Echo_Suppression>();
852

853
#else
854

855
   // Not supported on this platform, return null
856
   return nullptr;
857
#endif
858
}
859

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