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

randombit / botan / 22835645575

09 Mar 2026 02:17AM UTC coverage: 90.183% (-0.001%) from 90.184%
22835645575

Pull #5423

github

web-flow
Merge 8f65abe96 into cdaa9c0ff
Pull Request #5423: Add z/OS support with clang compiler

103788 of 115086 relevant lines covered (90.18%)

11566961.3 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_POSIX1)
26
   #include <errno.h>
27
   #include <pthread.h>
28
   #include <setjmp.h>
29
   #include <signal.h>
30
   #include <sys/mman.h>
31
   #include <sys/resource.h>
32
   #include <sys/types.h>
33
   #include <termios.h>
34
   #include <unistd.h>
35
   #undef B0
36
#endif
37

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

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

46
#if defined(BOTAN_TARGET_OS_HAS_WIN32)
47
   #define NOMINMAX 1
48
   #define _WINSOCKAPI_  // stop windows.h including winsock.h
49
   #include <windows.h>
50
   #if defined(BOTAN_BUILD_COMPILER_IS_MSVC)
51
      #include <libloaderapi.h>
52
      #include <stringapiset.h>
53
   #endif
54
#endif
55

56
#if defined(BOTAN_TARGET_OS_IS_IOS) || defined(BOTAN_TARGET_OS_IS_MACOS)
57
   #include <mach/vm_statistics.h>
58
   #include <sys/sysctl.h>
59
   #include <sys/types.h>
60
#endif
61

62
#if defined(BOTAN_TARGET_OS_HAS_PRCTL)
63
   #include <sys/prctl.h>
64
#endif
65

66
#if defined(BOTAN_TARGET_OS_IS_FREEBSD) || defined(BOTAN_TARGET_OS_IS_OPENBSD) || defined(BOTAN_TARGET_OS_IS_DRAGONFLY)
67
   #include <pthread_np.h>
68
#endif
69

70
#if defined(BOTAN_TARGET_OS_IS_HAIKU)
71
   #include <kernel/OS.h>
72
#endif
73

74
namespace Botan {
75

76
uint32_t OS::get_process_id() {
205,481✔
77
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
78
   return ::getpid();
205,481✔
79
#elif defined(BOTAN_TARGET_OS_HAS_WIN32)
80
   return ::GetCurrentProcessId();
81
#elif defined(BOTAN_TARGET_OS_IS_LLVM) || defined(BOTAN_TARGET_OS_IS_NONE)
82
   return 0;  // truly no meaningful value
83
#else
84
   #error "Missing get_process_id"
85
#endif
86
}
87

88
namespace {
89

90
#if defined(BOTAN_TARGET_OS_HAS_GETAUXVAL) || defined(BOTAN_TARGET_OS_HAS_ELF_AUX_INFO)
91
   #define BOTAN_TARGET_HAS_AUXVAL_INTERFACE
92
#endif
93

94
std::optional<unsigned long> auxval_hwcap() {
×
95
#if defined(AT_HWCAP)
96
   return AT_HWCAP;
×
97
#elif defined(BOTAN_TARGET_HAS_AUXVAL_INTERFACE)
98
   // If the value is not defined in a header we can see,
99
   // but auxval is supported, return the Linux/Android value
100
   return 16;
101
#else
102
   return {};
103
#endif
104
}
105

106
std::optional<unsigned long> auxval_hwcap2() {
×
107
#if defined(AT_HWCAP2)
108
   return AT_HWCAP2;
×
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 26;
113
#else
114
   return {};
115
#endif
116
}
117

118
std::optional<unsigned long> get_auxval(std::optional<unsigned long> id) {
16,761✔
119
   if(id) {
×
120
#if defined(BOTAN_TARGET_OS_HAS_GETAUXVAL)
121
      return ::getauxval(*id);
16,761✔
122
#elif defined(BOTAN_TARGET_OS_HAS_ELF_AUX_INFO)
123
      unsigned long auxinfo = 0;
124
      if(::elf_aux_info(static_cast<int>(*id), &auxinfo, sizeof(auxinfo)) == 0) {
125
         return auxinfo;
126
      }
127
#endif
128
   }
129

130
   return {};
131
}
132

133
}  // namespace
134

135
std::optional<std::pair<unsigned long, unsigned long>> OS::get_auxval_hwcap() {
×
136
   if(const auto hwcap = get_auxval(auxval_hwcap())) {
×
137
      // If hwcap worked/was valid, we don't require hwcap2 to also
138
      // succeed but instead will return zeros if it failed.
139
      auto hwcap2 = get_auxval(auxval_hwcap2()).value_or(0);
×
140
      return std::make_pair(*hwcap, hwcap2);
×
141
   } else {
142
      return {};
143
   }
144
}
145

146
namespace {
147

148
/**
149
* Test if we are currently running with elevated permissions
150
* eg setuid, setgid, or with POSIX caps set.
151
*/
152
bool running_in_privileged_state() {
16,761✔
153
#if defined(AT_SECURE)
154
   if(auto at_secure = get_auxval(AT_SECURE)) {
33,522✔
155
      return at_secure != 0;
33,522✔
156
   }
157
#endif
158

159
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
160
   return (::getuid() != ::geteuid()) || (::getgid() != ::getegid());
161
#else
162
   return false;
163
#endif
164
}
165

166
}  // namespace
167

168
uint64_t OS::get_cpu_cycle_counter() {
10,112,656✔
169
   uint64_t rtc = 0;
10,112,656✔
170

171
#if defined(BOTAN_TARGET_OS_HAS_WIN32)
172
   LARGE_INTEGER tv;
173
   ::QueryPerformanceCounter(&tv);
174
   rtc = tv.QuadPart;
175

176
#elif defined(BOTAN_USE_GCC_INLINE_ASM)
177

178
   // NOLINTBEGIN(*-no-assembler)
179

180
   #if defined(BOTAN_TARGET_ARCH_IS_X86_64)
181

182
   uint32_t rtc_low = 0;   // NOLINT(*-const-correctness) clang-tidy doesn't understand inline asm
10,112,656✔
183
   uint32_t rtc_high = 0;  // NOLINT(*-const-correctness) clang-tidy doesn't understand inline asm
10,112,656✔
184
   asm volatile("rdtsc" : "=d"(rtc_high), "=a"(rtc_low));
10,112,656✔
185
   rtc = (static_cast<uint64_t>(rtc_high) << 32) | rtc_low;
10,112,656✔
186

187
   #elif defined(BOTAN_TARGET_ARCH_IS_X86_FAMILY) && defined(BOTAN_HAS_CPUID)
188

189
   if(CPUID::has(CPUID::Feature::RDTSC)) {
190
      uint32_t rtc_low = 0;
191
      uint32_t rtc_high = 0;
192
      asm volatile("rdtsc" : "=d"(rtc_high), "=a"(rtc_low));
193
      rtc = (static_cast<uint64_t>(rtc_high) << 32) | rtc_low;
194
   }
195

196
   #elif defined(BOTAN_TARGET_ARCH_IS_PPC64)
197

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

206
      if(rtc_high == rtc_high2) {
207
         rtc = (static_cast<uint64_t>(rtc_high) << 32) | rtc_low;
208
         break;
209
      }
210
   }
211

212
   #elif defined(BOTAN_TARGET_ARCH_IS_ALPHA)
213
   asm volatile("rpcc %0" : "=r"(rtc));
214

215
   #elif defined(BOTAN_TARGET_ARCH_IS_SPARC64) && !defined(BOTAN_TARGET_OS_IS_OPENBSD)
216
   // OpenBSD does not trap access to the %tick register so we avoid it there
217
   asm volatile("rd %%tick, %0" : "=r"(rtc));
218

219
   #elif defined(BOTAN_TARGET_ARCH_IS_IA64)
220
   asm volatile("mov %0=ar.itc" : "=r"(rtc));
221

222
   #elif defined(BOTAN_TARGET_ARCH_IS_S390X)
223
#ifdef __MVS__
224
   unsigned long long value;
225
   __stckf(&value);
226
   return value;
227
#else
228
   asm volatile("stck 0(%0)" : : "a"(&rtc) : "memory", "cc");
229
#endif
230

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

234
   #else
235
      //#warning "OS::get_cpu_cycle_counter not implemented"
236
   #endif
237

238
   // NOLINTEND(*-no-assembler)
239

240
#endif
241

242
   return rtc;
10,112,656✔
243
}
244

245
size_t OS::get_cpu_available() {
790✔
246
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
247

248
   #if defined(_SC_NPROCESSORS_ONLN)
249
   const long cpu_online = ::sysconf(_SC_NPROCESSORS_ONLN);
790✔
250
   if(cpu_online > 0) {
790✔
251
      return static_cast<size_t>(cpu_online);
790✔
252
   }
253
   #endif
254

255
   #if defined(_SC_NPROCESSORS_CONF)
256
   const long cpu_conf = ::sysconf(_SC_NPROCESSORS_CONF);
×
257
   if(cpu_conf > 0) {
×
258
      return static_cast<size_t>(cpu_conf);
×
259
   }
260
   #endif
261

262
#endif
263

264
#if defined(BOTAN_TARGET_OS_HAS_THREADS)
265
   // hardware_concurrency is allowed to return 0 if the value is not
266
   // well defined or not computable.
267
   const size_t hw_concur = std::thread::hardware_concurrency();
×
268

269
   if(hw_concur > 0) {
×
270
      return hw_concur;
271
   }
272
#endif
273

274
   return 1;
275
}
276

277
uint64_t OS::get_high_resolution_clock() {
4,645✔
278
   if(const uint64_t cpu_clock = OS::get_cpu_cycle_counter()) {
4,645✔
279
      return cpu_clock;
280
   }
281

282
#if defined(BOTAN_TARGET_OS_IS_EMSCRIPTEN)
283
   return emscripten_get_now();
284
#endif
285

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

293
#if defined(BOTAN_TARGET_OS_HAS_CLOCK_GETTIME)
294

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

314
   for(const clockid_t clock : clock_types) {
×
315
      struct timespec ts {};
×
316

317
      if(::clock_gettime(clock, &ts) == 0) {
×
318
         return (static_cast<uint64_t>(ts.tv_sec) * 1000000000) + static_cast<uint64_t>(ts.tv_nsec);
×
319
      }
320
   }
321
#endif
322

323
#if defined(BOTAN_TARGET_OS_HAS_SYSTEM_CLOCK)
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
#else
328
   return 0;
329
#endif
330
}
331

332
uint64_t OS::get_system_timestamp_ns() {
10,067,800✔
333
#if defined(BOTAN_TARGET_OS_HAS_CLOCK_GETTIME)
334
   struct timespec ts {};
10,067,800✔
335

336
   if(::clock_gettime(CLOCK_REALTIME, &ts) == 0) {
10,067,800✔
337
      return (static_cast<uint64_t>(ts.tv_sec) * 1000000000) + static_cast<uint64_t>(ts.tv_nsec);
10,067,800✔
338
   }
339
#endif
340

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

349
std::string OS::format_time(time_t time, const std::string& format) {
3,039✔
350
   std::tm tm{};
3,039✔
351

352
#if defined(BOTAN_TARGET_OS_HAS_WIN32)
353
   if(::localtime_s(&tm, &time) != 0) {
354
      throw Encoding_Error("Could not convert time_t to localtime");
355
   }
356
#elif defined(BOTAN_TARGET_OS_HAS_POSIX1)
357
   if(::localtime_r(&time, &tm) == nullptr) {
3,039✔
358
      throw Encoding_Error("Could not convert time_t to localtime");
×
359
   }
360
#else
361
   if(auto tmp = std::localtime(&time)) {
362
      tm = *tmp;
363
   } else {
364
      throw Encoding_Error("Could not convert time_t to localtime");
365
   }
366
#endif
367

368
   std::ostringstream oss;
3,039✔
369
   oss << std::put_time(&tm, format.c_str());
3,039✔
370
   return oss.str();
6,078✔
371
}
3,039✔
372

373
size_t OS::system_page_size() {
1,977,085✔
374
   const size_t default_page_size = 4096;
1,977,085✔
375

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

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

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

412
   if(mlock_requested > 0) {
3,839✔
413
      struct ::rlimit limits {};
3,839✔
414

415
      ::getrlimit(RLIMIT_MEMLOCK, &limits);
3,839✔
416

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

423
      return std::min<size_t>(limits.rlim_cur, mlock_requested * 1024);
7,678✔
424
   }
425

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

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

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

451
   return 0;
452
}
453

454
bool OS::read_env_variable(std::string& value_out, std::string_view name_view) {
16,761✔
455
   value_out = "";
16,761✔
456

457
   if(running_in_privileged_state()) {
16,761✔
458
      return false;
459
   }
460

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

485
   return false;
486
}
16,761✔
487

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

498
   return def;
499
}
3,839✔
500

501
#if defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
502

503
namespace {
504

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

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

524
}  // namespace
525

526
#endif
527

528
std::vector<void*> OS::allocate_locked_pages(size_t count) {
3,839✔
529
   std::vector<void*> result;
3,839✔
530

531
#if(defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)) || \
532
   defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
533

534
   result.reserve(count);
3,839✔
535

536
   const size_t page_size = OS::system_page_size();
3,839✔
537

538
   #if defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
539
   static const int locked_fd = get_locked_fd();
3,839✔
540
   #endif
541

542
   for(size_t i = 0; i != count; ++i) {
495,231✔
543
      void* ptr = nullptr;
491,392✔
544

545
   #if defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
546

547
      int mmap_flags = MAP_PRIVATE;
491,392✔
548

549
      #if defined(MAP_ANONYMOUS)
550
      mmap_flags |= MAP_ANONYMOUS;
491,392✔
551
      #elif defined(MAP_ANON)
552
      mmap_flags |= MAP_ANON;
553
      #endif
554

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

561
      const int mmap_prot = PROT_READ | PROT_WRITE;
491,392✔
562

563
      #if defined(PROT_MAX)
564
      mmap_prot |= PROT_MAX(mmap_prot);
565
      #endif
566

567
      ptr = ::mmap(nullptr,
491,392✔
568
                   3 * page_size,
569
                   mmap_prot,
570
                   mmap_flags,
571
                   /*fd=*/locked_fd,
572
                   /*offset=*/0);
573

574
      if(ptr == MAP_FAILED) {
491,392✔
575
         continue;
×
576
      }
577

578
      // lock the data page
579
      if(::mlock(static_cast<uint8_t*>(ptr) + page_size, page_size) != 0) {
491,392✔
580
         ::munmap(ptr, 3 * page_size);
×
581
         continue;
×
582
      }
583

584
      #if defined(MADV_DONTDUMP)
585
      // we ignore errors here, as DONTDUMP is just a bonus
586
      ::madvise(static_cast<uint8_t*>(ptr) + page_size, page_size, MADV_DONTDUMP);
491,392✔
587
      #endif
588

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

592
      if(ptr == nullptr)
593
         continue;
594

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

601
      std::memset(ptr, 0, 3 * page_size);  // zero data page and both guard pages
491,392✔
602

603
      // Attempts to name the data page
604
      page_named(ptr, 3 * page_size);
982,784✔
605
      // Make guard page preceding the data page
606
      page_prohibit_access(static_cast<uint8_t*>(ptr));
491,392✔
607
      // Make guard page following the data page
608
      page_prohibit_access(static_cast<uint8_t*>(ptr) + 2 * page_size);
491,392✔
609

610
      result.push_back(static_cast<uint8_t*>(ptr) + page_size);
491,392✔
611
   }
612
#else
613
   BOTAN_UNUSED(count);
614
#endif
615

616
   return result;
3,839✔
617
}
×
618

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

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

647
void OS::free_locked_pages(const std::vector<void*>& pages) {
3,839✔
648
   const size_t page_size = OS::system_page_size();
3,839✔
649

650
   for(void* ptr : pages) {
495,231✔
651
      secure_scrub_memory(ptr, page_size);
491,392✔
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);
491,392✔
655
      page_allow_access(static_cast<uint8_t*>(ptr) + page_size);
491,392✔
656

657
#if defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
658
      ::munlock(ptr, page_size);
491,392✔
659
      ::munmap(static_cast<uint8_t*>(ptr) - page_size, 3 * page_size);
491,392✔
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
}
3,839✔
666

667
void OS::page_named(void* page, size_t size) {
491,392✔
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";
491,392✔
670
   // NOLINTNEXTLINE(*-vararg)
671
   const int r = prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME, reinterpret_cast<uintptr_t>(page), size, name);
491,392✔
672
   BOTAN_UNUSED(r);
491,392✔
673
#else
674
   BOTAN_UNUSED(page, size);
675
#endif
676
}
×
677

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

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

715
namespace {
716

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

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

724
}  // namespace
725

726
#endif
727

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

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

734
   struct sigaction sigaction {};
2✔
735

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

740
   int rc = ::sigaction(SIGILL, &sigaction, &old_sigaction);
2✔
741

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

746
   rc = sigsetjmp(g_sigill_jmp_buf, /*save sigs*/ 1);
3✔
747

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

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

762
#else
763
   BOTAN_UNUSED(probe_fn);
764
#endif
765

766
   return probe_result;
2✔
767
}
768

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

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

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

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

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

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

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

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

814
#elif defined(BOTAN_TARGET_OS_HAS_WIN32)
815

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

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

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

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

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

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

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

854
#else
855

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

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