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

randombit / botan / 16231861852

11 Jul 2025 11:53PM UTC coverage: 90.572%. Remained the same
16231861852

push

github

web-flow
Merge pull request #4968 from randombit/jack/fix-clang-tidy-hicpp-member-init

Enable and fix clang-tidy warning hicpp-member-init

99072 of 109385 relevant lines covered (90.57%)

12554504.23 hits per line

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

66.3
/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 <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_WIN32)
48
   #define NOMINMAX 1
49
   #define _WINSOCKAPI_  // stop windows.h including winsock.h
50
   #include <windows.h>
51
   #if defined(BOTAN_BUILD_COMPILER_IS_MSVC)
52
      #include <libloaderapi.h>
53
      #include <stringapiset.h>
54
   #endif
55
#endif
56

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

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

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

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

75
namespace Botan {
76

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

89
namespace {
90

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

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

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

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

131
   return {};
132
}
133

134
}  // namespace
135

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

147
namespace {
148

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

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

167
}  // namespace
168

169
uint64_t OS::get_cpu_cycle_counter() {
3,760,934✔
170
   uint64_t rtc = 0;
3,760,934✔
171

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

177
#elif defined(BOTAN_USE_GCC_INLINE_ASM)
178

179
   #if defined(BOTAN_TARGET_ARCH_IS_X86_64)
180

181
   uint32_t rtc_low = 0, rtc_high = 0;
3,760,934✔
182
   asm volatile("rdtsc" : "=d"(rtc_high), "=a"(rtc_low));
3,760,934✔
183
   rtc = (static_cast<uint64_t>(rtc_high) << 32) | rtc_low;
3,760,934✔
184

185
   #elif defined(BOTAN_TARGET_CPU_IS_X86_FAMILY) && defined(BOTAN_HAS_CPUID)
186

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

193
   #elif defined(BOTAN_TARGET_ARCH_IS_PPC64)
194

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

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

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

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

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

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

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

223
   #else
224
      //#warning "OS::get_cpu_cycle_counter not implemented"
225
   #endif
226

227
#endif
228

229
   return rtc;
3,760,934✔
230
}
231

232
size_t OS::get_cpu_available() {
798✔
233
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
234

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

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

249
#endif
250

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

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

261
   return 1;
262
}
263

264
uint64_t OS::get_high_resolution_clock() {
4,641✔
265
   if(uint64_t cpu_clock = OS::get_cpu_cycle_counter()) {
4,641✔
266
      return cpu_clock;
267
   }
268

269
#if defined(BOTAN_TARGET_OS_IS_EMSCRIPTEN)
270
   return emscripten_get_now();
271
#endif
272

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

280
#if defined(BOTAN_TARGET_OS_HAS_CLOCK_GETTIME)
281

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

301
   for(clockid_t clock : clock_types) {
×
302
      struct timespec ts {};
×
303

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

310
#if defined(BOTAN_TARGET_OS_HAS_SYSTEM_CLOCK)
311
   // Plain C++11 fallback
312
   auto now = std::chrono::high_resolution_clock::now().time_since_epoch();
×
313
   return std::chrono::duration_cast<std::chrono::nanoseconds>(now).count();
×
314
#else
315
   return 0;
316
#endif
317
}
318

319
uint64_t OS::get_system_timestamp_ns() {
3,714,829✔
320
#if defined(BOTAN_TARGET_OS_HAS_CLOCK_GETTIME)
321
   struct timespec ts {};
3,714,829✔
322

323
   if(::clock_gettime(CLOCK_REALTIME, &ts) == 0) {
3,714,829✔
324
      return (static_cast<uint64_t>(ts.tv_sec) * 1000000000) + static_cast<uint64_t>(ts.tv_nsec);
3,714,829✔
325
   }
326
#endif
327

328
#if defined(BOTAN_TARGET_OS_HAS_SYSTEM_CLOCK)
329
   auto now = std::chrono::system_clock::now().time_since_epoch();
×
330
   return std::chrono::duration_cast<std::chrono::nanoseconds>(now).count();
×
331
#else
332
   throw Not_Implemented("OS::get_system_timestamp_ns this system does not support a clock");
333
#endif
334
}
335

336
std::string OS::format_time(time_t time, const std::string& format) {
2,887✔
337
   std::tm tm{};
2,887✔
338

339
#if defined(BOTAN_TARGET_OS_HAS_WIN32)
340
   if(::localtime_s(&tm, &time) != 0) {
341
      throw Encoding_Error("Could not convert time_t to localtime");
342
   }
343
#elif defined(BOTAN_TARGET_OS_HAS_POSIX1)
344
   if(!::localtime_r(&time, &tm)) {
2,887✔
345
      throw Encoding_Error("Could not convert time_t to localtime");
×
346
   }
347
#else
348
   if(auto tmp = std::localtime(&time)) {
349
      tm = *tmp;
350
   } else {
351
      throw Encoding_Error("Could not convert time_t to localtime");
352
   }
353
#endif
354

355
   std::ostringstream oss;
2,887✔
356
   oss << std::put_time(&tm, format.c_str());
2,887✔
357
   return oss.str();
5,774✔
358
}
2,887✔
359

360
size_t OS::system_page_size() {
4,499,040✔
361
   const size_t default_page_size = 4096;
4,499,040✔
362

363
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
364
   long p = ::sysconf(_SC_PAGESIZE);
8,736✔
365
   if(p > 1) {
4,499,040✔
366
      return static_cast<size_t>(p);
4,499,040✔
367
   } else {
368
      return default_page_size;
369
   }
370
#elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
371
   BOTAN_UNUSED(default_page_size);
372
   SYSTEM_INFO sys_info;
373
   ::GetSystemInfo(&sys_info);
374
   return sys_info.dwPageSize;
375
#else
376
   return default_page_size;
377
#endif
378
}
379

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

391
   /*
392
   * If RLIMIT_MEMLOCK is not defined, likely the OS does not support
393
   * unprivileged mlock calls.
394
   */
395
#if defined(RLIMIT_MEMLOCK) && defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
396
   const size_t mlock_requested =
8,736✔
397
      std::min<size_t>(read_env_variable_sz("BOTAN_MLOCK_POOL_SIZE", max_locked_kb), max_locked_kb);
8,736✔
398

399
   if(mlock_requested > 0) {
8,736✔
400
      struct ::rlimit limits {};
8,736✔
401

402
      ::getrlimit(RLIMIT_MEMLOCK, &limits);
8,736✔
403

404
      if(limits.rlim_cur < limits.rlim_max) {
8,736✔
405
         limits.rlim_cur = limits.rlim_max;
×
406
         ::setrlimit(RLIMIT_MEMLOCK, &limits);
×
407
         ::getrlimit(RLIMIT_MEMLOCK, &limits);
×
408
      }
409

410
      return std::min<size_t>(limits.rlim_cur, mlock_requested * 1024);
17,472✔
411
   }
412

413
#elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
414
   const size_t mlock_requested =
415
      std::min<size_t>(read_env_variable_sz("BOTAN_MLOCK_POOL_SIZE", max_locked_kb), max_locked_kb);
416

417
   SIZE_T working_min = 0, working_max = 0;
418
   if(!::GetProcessWorkingSetSize(::GetCurrentProcess(), &working_min, &working_max)) {
419
      return 0;
420
   }
421

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

438
   return 0;
439
}
440

441
bool OS::read_env_variable(std::string& value_out, std::string_view name_view) {
23,614✔
442
   value_out = "";
23,614✔
443

444
   if(running_in_privileged_state()) {
23,614✔
445
      return false;
446
   }
447

448
#if defined(BOTAN_TARGET_OS_HAS_WIN32) && defined(BOTAN_BUILD_COMPILER_IS_MSVC)
449
   const std::string name(name_view);
450
   char val[128] = {0};
451
   size_t req_size = 0;
452
   if(getenv_s(&req_size, val, sizeof(val), name.c_str()) == 0) {
453
      // Microsoft's implementation always writes a terminating \0,
454
      // and includes it in the reported length of the environment variable
455
      // if a value exists.
456
      if(req_size > 0 && val[req_size - 1] == '\0') {
457
         value_out = std::string(val);
458
      } else {
459
         value_out = std::string(val, req_size);
460
      }
461
      return true;
462
   }
463
#else
464
   const std::string name(name_view);
23,614✔
465
   if(const char* val = std::getenv(name.c_str())) {
23,614✔
466
      value_out = val;
23,614✔
467
      return true;
468
   }
469
#endif
470

471
   return false;
472
}
23,614✔
473

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

484
   return def;
485
}
8,736✔
486

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

489
namespace {
490

491
int get_locked_fd() {
492
   #if defined(BOTAN_TARGET_OS_IS_IOS) || defined(BOTAN_TARGET_OS_IS_MACOS)
493
   // On Darwin, tagging anonymous pages allows vmmap to track these.
494
   // Allowed from 240 to 255 for userland applications
495
   static constexpr int default_locked_fd = 255;
496
   int locked_fd = default_locked_fd;
497

498
   if(size_t locked_fdl = OS::read_env_variable_sz("BOTAN_LOCKED_FD", default_locked_fd)) {
499
      if(locked_fdl < 240 || locked_fdl > 255) {
500
         locked_fdl = default_locked_fd;
501
      }
502
      locked_fd = static_cast<int>(locked_fdl);
503
   }
504
   return VM_MAKE_TAG(locked_fd);
505
   #else
506
   return -1;
507
   #endif
508
}
509

510
}  // namespace
511

512
#endif
513

514
std::vector<void*> OS::allocate_locked_pages(size_t count) {
8,736✔
515
   std::vector<void*> result;
8,736✔
516

517
#if(defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)) || \
518
   defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
519

520
   result.reserve(count);
8,736✔
521

522
   const size_t page_size = OS::system_page_size();
8,736✔
523

524
   #if defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
525
   static const int locked_fd = get_locked_fd();
8,736✔
526
   #endif
527

528
   for(size_t i = 0; i != count; ++i) {
1,126,944✔
529
      void* ptr = nullptr;
1,118,208✔
530

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

533
      int mmap_flags = MAP_PRIVATE;
1,118,208✔
534

535
      #if defined(MAP_ANONYMOUS)
536
      mmap_flags |= MAP_ANONYMOUS;
1,118,208✔
537
      #elif defined(MAP_ANON)
538
      mmap_flags |= MAP_ANON;
539
      #endif
540

541
      #if defined(MAP_CONCEAL)
542
      mmap_flags |= MAP_CONCEAL;
543
      #elif defined(MAP_NOCORE)
544
      mmap_flags |= MAP_NOCORE;
545
      #endif
546

547
      int mmap_prot = PROT_READ | PROT_WRITE;
1,118,208✔
548

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

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

560
      if(ptr == MAP_FAILED) {
1,118,208✔
561
         continue;
×
562
      }
563

564
      // lock the data page
565
      if(::mlock(static_cast<uint8_t*>(ptr) + page_size, page_size) != 0) {
1,118,208✔
566
         ::munmap(ptr, 3 * page_size);
×
567
         continue;
×
568
      }
569

570
      #if defined(MADV_DONTDUMP)
571
      // we ignore errors here, as DONTDUMP is just a bonus
572
      ::madvise(static_cast<uint8_t*>(ptr) + page_size, page_size, MADV_DONTDUMP);
1,118,208✔
573
      #endif
574

575
   #elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
576
      ptr = ::VirtualAlloc(nullptr, 3 * page_size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
577

578
      if(ptr == nullptr)
579
         continue;
580

581
      if(::VirtualLock(static_cast<uint8_t*>(ptr) + page_size, page_size) == 0) {
582
         ::VirtualFree(ptr, 0, MEM_RELEASE);
583
         continue;
584
      }
585
   #endif
586

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

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

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

602
   return result;
8,736✔
603
}
×
604

605
void OS::page_allow_access(void* page) {
2,236,416✔
606
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
607
   const size_t page_size = OS::system_page_size();
2,236,416✔
608
   ::mprotect(page, page_size, PROT_READ | PROT_WRITE);
2,236,416✔
609
#elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
610
   const size_t page_size = OS::system_page_size();
611
   DWORD old_perms = 0;
612
   ::VirtualProtect(page, page_size, PAGE_READWRITE, &old_perms);
613
   BOTAN_UNUSED(old_perms);
614
#else
615
   BOTAN_UNUSED(page);
616
#endif
617
}
2,236,416✔
618

619
void OS::page_prohibit_access(void* page) {
2,236,416✔
620
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
621
   const size_t page_size = OS::system_page_size();
2,236,416✔
622
   ::mprotect(page, page_size, PROT_NONE);
2,236,416✔
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_NOACCESS, &old_perms);
627
   BOTAN_UNUSED(old_perms);
628
#else
629
   BOTAN_UNUSED(page);
630
#endif
631
}
2,236,416✔
632

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

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

639
      secure_scrub_memory(ptr, page_size);
1,118,208✔
640

641
      // ptr points to the data page, guard pages are before and after
642
      page_allow_access(static_cast<uint8_t*>(ptr) - page_size);
1,118,208✔
643
      page_allow_access(static_cast<uint8_t*>(ptr) + page_size);
1,118,208✔
644

645
#if defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
646
      ::munlock(ptr, page_size);
1,118,208✔
647
      ::munmap(static_cast<uint8_t*>(ptr) - page_size, 3 * page_size);
1,118,208✔
648
#elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
649
      ::VirtualUnlock(ptr, page_size);
650
      ::VirtualFree(static_cast<uint8_t*>(ptr) - page_size, 0, MEM_RELEASE);
651
#endif
652
   }
653
}
8,736✔
654

655
void OS::page_named(void* page, size_t size) {
1,118,208✔
656
#if defined(BOTAN_TARGET_OS_HAS_PRCTL) && defined(PR_SET_VMA) && defined(PR_SET_VMA_ANON_NAME)
657
   static constexpr char name[] = "Botan mlock pool";
1,118,208✔
658
   // NOLINTNEXTLINE(hicpp-vararg)
659
   int r = prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME, reinterpret_cast<uintptr_t>(page), size, name);
1,118,208✔
660
   BOTAN_UNUSED(r);
1,118,208✔
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,196✔
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,196✔
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,196✔
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

722
   struct sigaction sigaction {};
2✔
723

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

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

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

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

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

744
   // Restore old SIGILL handler, if any
745
   rc = ::sigaction(SIGILL, &old_sigaction, nullptr);
2✔
746
   if(rc != 0) {
2✔
747
      throw System_Error("run_cpu_instruction_probe sigaction restore failed", errno);
×
748
   }
749

750
#else
751
   BOTAN_UNUSED(probe_fn);
752
#endif
753

754
   return probe_result;
2✔
755
}
756

757
std::unique_ptr<OS::Echo_Suppression> OS::suppress_echo_on_terminal() {
×
758
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
759
   class POSIX_Echo_Suppression : public Echo_Suppression {
×
760
      public:
761
         POSIX_Echo_Suppression() : m_old_termios{} {
×
762
            m_stdin_fd = fileno(stdin);
×
763
            if(::tcgetattr(m_stdin_fd, &m_old_termios) != 0) {
×
764
               throw System_Error("Getting terminal status failed", errno);
×
765
            }
766

767
            struct termios noecho_flags = m_old_termios;
×
768
            noecho_flags.c_lflag &= ~ECHO;
×
769
            noecho_flags.c_lflag |= ECHONL;
×
770

771
            if(::tcsetattr(m_stdin_fd, TCSANOW, &noecho_flags) != 0) {
×
772
               throw System_Error("Clearing terminal echo bit failed", errno);
×
773
            }
774
         }
×
775

776
         void reenable_echo() override {
×
777
            if(m_stdin_fd > 0) {
×
778
               if(::tcsetattr(m_stdin_fd, TCSANOW, &m_old_termios) != 0) {
×
779
                  throw System_Error("Restoring terminal echo bit failed", errno);
×
780
               }
781
               m_stdin_fd = -1;
×
782
            }
783
         }
×
784

785
         ~POSIX_Echo_Suppression() override {
×
786
            try {
×
787
               reenable_echo();
×
788
            } catch(...) {}
×
789
         }
×
790

791
         POSIX_Echo_Suppression(const POSIX_Echo_Suppression& other) = delete;
792
         POSIX_Echo_Suppression(POSIX_Echo_Suppression&& other) = delete;
793
         POSIX_Echo_Suppression& operator=(const POSIX_Echo_Suppression& other) = delete;
794
         POSIX_Echo_Suppression& operator=(POSIX_Echo_Suppression&& other) = delete;
795

796
      private:
797
         int m_stdin_fd;
798
         struct termios m_old_termios;
799
   };
800

801
   return std::make_unique<POSIX_Echo_Suppression>();
×
802

803
#elif defined(BOTAN_TARGET_OS_HAS_WIN32)
804

805
   class Win32_Echo_Suppression : public Echo_Suppression {
806
      public:
807
         Win32_Echo_Suppression() {
808
            m_input_handle = ::GetStdHandle(STD_INPUT_HANDLE);
809
            if(::GetConsoleMode(m_input_handle, &m_console_state) == 0)
810
               throw System_Error("Getting console mode failed", ::GetLastError());
811

812
            DWORD new_mode = ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT;
813
            if(::SetConsoleMode(m_input_handle, new_mode) == 0)
814
               throw System_Error("Setting console mode failed", ::GetLastError());
815
         }
816

817
         void reenable_echo() override {
818
            if(m_input_handle != INVALID_HANDLE_VALUE) {
819
               if(::SetConsoleMode(m_input_handle, m_console_state) == 0)
820
                  throw System_Error("Setting console mode failed", ::GetLastError());
821
               m_input_handle = INVALID_HANDLE_VALUE;
822
            }
823
         }
824

825
         ~Win32_Echo_Suppression() override {
826
            try {
827
               reenable_echo();
828
            } catch(...) {}
829
         }
830

831
         Win32_Echo_Suppression(const Win32_Echo_Suppression& other) = delete;
832
         Win32_Echo_Suppression(Win32_Echo_Suppression&& other) = delete;
833
         Win32_Echo_Suppression& operator=(const Win32_Echo_Suppression& other) = delete;
834
         Win32_Echo_Suppression& operator=(Win32_Echo_Suppression&& other) = delete;
835

836
      private:
837
         HANDLE m_input_handle;
838
         DWORD m_console_state;
839
   };
840

841
   return std::make_unique<Win32_Echo_Suppression>();
842

843
#else
844

845
   // Not supported on this platform, return null
846
   return nullptr;
847
#endif
848
}
849

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