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

randombit / botan / 16803652459

07 Aug 2025 11:50AM UTC coverage: 90.679% (+0.002%) from 90.677%
16803652459

push

github

web-flow
Merge pull request #4255 from solemnwarning/clang-cl

Add support for building with clang-cl

99985 of 110263 relevant lines covered (90.68%)

12427924.06 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 <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,245✔
78
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
79
   return ::getpid();
199,245✔
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,623,667✔
170
   uint64_t rtc = 0;
3,623,667✔
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;
3,623,667✔
182
   uint32_t rtc_high = 0;
3,623,667✔
183
   asm volatile("rdtsc" : "=d"(rtc_high), "=a"(rtc_low));
3,623,667✔
184
   rtc = (static_cast<uint64_t>(rtc_high) << 32) | rtc_low;
3,623,667✔
185

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

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

195
   #elif defined(BOTAN_TARGET_ARCH_IS_PPC64)
196

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

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

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

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

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

221
   #elif defined(BOTAN_TARGET_ARCH_IS_S390X)
222
   asm volatile("stck 0(%0)" : : "a"(&rtc) : "memory", "cc");
223

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

227
   #else
228
      //#warning "OS::get_cpu_cycle_counter not implemented"
229
   #endif
230

231
#endif
232

233
   return rtc;
3,623,667✔
234
}
235

236
size_t OS::get_cpu_available() {
798✔
237
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
238

239
   #if defined(_SC_NPROCESSORS_ONLN)
240
   const long cpu_online = ::sysconf(_SC_NPROCESSORS_ONLN);
798✔
241
   if(cpu_online > 0) {
798✔
242
      return static_cast<size_t>(cpu_online);
798✔
243
   }
244
   #endif
245

246
   #if defined(_SC_NPROCESSORS_CONF)
247
   const long cpu_conf = ::sysconf(_SC_NPROCESSORS_CONF);
×
248
   if(cpu_conf > 0) {
×
249
      return static_cast<size_t>(cpu_conf);
×
250
   }
251
   #endif
252

253
#endif
254

255
#if defined(BOTAN_TARGET_OS_HAS_THREADS)
256
   // hardware_concurrency is allowed to return 0 if the value is not
257
   // well defined or not computable.
258
   const size_t hw_concur = std::thread::hardware_concurrency();
×
259

260
   if(hw_concur > 0) {
×
261
      return hw_concur;
262
   }
263
#endif
264

265
   return 1;
266
}
267

268
uint64_t OS::get_high_resolution_clock() {
4,639✔
269
   if(uint64_t cpu_clock = OS::get_cpu_cycle_counter()) {
4,639✔
270
      return cpu_clock;
271
   }
272

273
#if defined(BOTAN_TARGET_OS_IS_EMSCRIPTEN)
274
   return emscripten_get_now();
275
#endif
276

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

284
#if defined(BOTAN_TARGET_OS_HAS_CLOCK_GETTIME)
285

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

305
   for(clockid_t clock : clock_types) {
×
306
      struct timespec ts {};
×
307

308
      if(::clock_gettime(clock, &ts) == 0) {
×
309
         return (static_cast<uint64_t>(ts.tv_sec) * 1000000000) + static_cast<uint64_t>(ts.tv_nsec);
×
310
      }
311
   }
312
#endif
313

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

323
uint64_t OS::get_system_timestamp_ns() {
3,579,068✔
324
#if defined(BOTAN_TARGET_OS_HAS_CLOCK_GETTIME)
325
   struct timespec ts {};
3,579,068✔
326

327
   if(::clock_gettime(CLOCK_REALTIME, &ts) == 0) {
3,579,068✔
328
      return (static_cast<uint64_t>(ts.tv_sec) * 1000000000) + static_cast<uint64_t>(ts.tv_nsec);
3,579,068✔
329
   }
330
#endif
331

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

340
std::string OS::format_time(time_t time, const std::string& format) {
2,897✔
341
   std::tm tm{};
2,897✔
342

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

359
   std::ostringstream oss;
2,897✔
360
   oss << std::put_time(&tm, format.c_str());
2,897✔
361
   return oss.str();
5,794✔
362
}
2,897✔
363

364
size_t OS::system_page_size() {
4,499,040✔
365
   const size_t default_page_size = 4096;
4,499,040✔
366

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

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

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

403
   if(mlock_requested > 0) {
8,736✔
404
      struct ::rlimit limits {};
8,736✔
405

406
      ::getrlimit(RLIMIT_MEMLOCK, &limits);
8,736✔
407

408
      if(limits.rlim_cur < limits.rlim_max) {
8,736✔
409
         limits.rlim_cur = limits.rlim_max;
×
410
         ::setrlimit(RLIMIT_MEMLOCK, &limits);
×
411
         ::getrlimit(RLIMIT_MEMLOCK, &limits);
×
412
      }
413

414
      return std::min<size_t>(limits.rlim_cur, mlock_requested * 1024);
17,472✔
415
   }
416

417
#elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
418
   const size_t mlock_requested =
419
      std::min<size_t>(read_env_variable_sz("BOTAN_MLOCK_POOL_SIZE", max_locked_kb), max_locked_kb);
420

421
   SIZE_T working_min = 0, working_max = 0;
422
   if(!::GetProcessWorkingSetSize(::GetCurrentProcess(), &working_min, &working_max)) {
423
      return 0;
424
   }
425

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

442
   return 0;
443
}
444

445
bool OS::read_env_variable(std::string& value_out, std::string_view name_view) {
23,614✔
446
   value_out = "";
23,614✔
447

448
   if(running_in_privileged_state()) {
23,614✔
449
      return false;
450
   }
451

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

476
   return false;
477
}
23,614✔
478

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

489
   return def;
490
}
8,736✔
491

492
#if defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
493

494
namespace {
495

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

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

515
}  // namespace
516

517
#endif
518

519
std::vector<void*> OS::allocate_locked_pages(size_t count) {
8,736✔
520
   std::vector<void*> result;
8,736✔
521

522
#if(defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)) || \
523
   defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
524

525
   result.reserve(count);
8,736✔
526

527
   const size_t page_size = OS::system_page_size();
8,736✔
528

529
   #if defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
530
   static const int locked_fd = get_locked_fd();
8,736✔
531
   #endif
532

533
   for(size_t i = 0; i != count; ++i) {
1,126,944✔
534
      void* ptr = nullptr;
1,118,208✔
535

536
   #if defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
537

538
      int mmap_flags = MAP_PRIVATE;
1,118,208✔
539

540
      #if defined(MAP_ANONYMOUS)
541
      mmap_flags |= MAP_ANONYMOUS;
1,118,208✔
542
      #elif defined(MAP_ANON)
543
      mmap_flags |= MAP_ANON;
544
      #endif
545

546
      #if defined(MAP_CONCEAL)
547
      mmap_flags |= MAP_CONCEAL;
548
      #elif defined(MAP_NOCORE)
549
      mmap_flags |= MAP_NOCORE;
550
      #endif
551

552
      int mmap_prot = PROT_READ | PROT_WRITE;
1,118,208✔
553

554
      #if defined(PROT_MAX)
555
      mmap_prot |= PROT_MAX(mmap_prot);
556
      #endif
557

558
      ptr = ::mmap(nullptr,
1,118,208✔
559
                   3 * page_size,
560
                   mmap_prot,
561
                   mmap_flags,
562
                   /*fd=*/locked_fd,
563
                   /*offset=*/0);
564

565
      if(ptr == MAP_FAILED) {
1,118,208✔
566
         continue;
×
567
      }
568

569
      // lock the data page
570
      if(::mlock(static_cast<uint8_t*>(ptr) + page_size, page_size) != 0) {
1,118,208✔
571
         ::munmap(ptr, 3 * page_size);
×
572
         continue;
×
573
      }
574

575
      #if defined(MADV_DONTDUMP)
576
      // we ignore errors here, as DONTDUMP is just a bonus
577
      ::madvise(static_cast<uint8_t*>(ptr) + page_size, page_size, MADV_DONTDUMP);
1,118,208✔
578
      #endif
579

580
   #elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
581
      ptr = ::VirtualAlloc(nullptr, 3 * page_size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
582

583
      if(ptr == nullptr)
584
         continue;
585

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

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

594
      // Attempts to name the data page
595
      page_named(ptr, 3 * page_size);
2,236,416✔
596
      // Make guard page preceeding the data page
597
      page_prohibit_access(static_cast<uint8_t*>(ptr));
1,118,208✔
598
      // Make guard page following the data page
599
      page_prohibit_access(static_cast<uint8_t*>(ptr) + 2 * page_size);
1,118,208✔
600

601
      result.push_back(static_cast<uint8_t*>(ptr) + page_size);
1,118,208✔
602
   }
603
#else
604
   BOTAN_UNUSED(count);
605
#endif
606

607
   return result;
8,736✔
608
}
×
609

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

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

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

641
   for(void* ptr : pages) {
1,126,944✔
642
      secure_scrub_memory(ptr, page_size);
1,118,208✔
643

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

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

658
void OS::page_named(void* page, size_t size) {
1,118,208✔
659
#if defined(BOTAN_TARGET_OS_HAS_PRCTL) && defined(PR_SET_VMA) && defined(PR_SET_VMA_ANON_NAME)
660
   static constexpr char name[] = "Botan mlock pool";
1,118,208✔
661
   // NOLINTNEXTLINE(*-vararg)
662
   int r = prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME, reinterpret_cast<uintptr_t>(page), size, name);
1,118,208✔
663
   BOTAN_UNUSED(r);
1,118,208✔
664
#else
665
   BOTAN_UNUSED(page, size);
666
#endif
667
}
×
668

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

704
#if defined(BOTAN_TARGET_OS_HAS_POSIX1) && !defined(BOTAN_TARGET_OS_IS_EMSCRIPTEN)
705

706
namespace {
707

708
// NOLINTNEXTLINE(*-avoid-non-const-global-variables)
709
::sigjmp_buf g_sigill_jmp_buf;
710

711
void botan_sigill_handler(int /*unused*/) {
1✔
712
   siglongjmp(g_sigill_jmp_buf, /*non-zero return value*/ 1);
1✔
713
}
714

715
}  // namespace
716

717
#endif
718

719
int OS::run_cpu_instruction_probe(const std::function<int()>& probe_fn) {
2✔
720
   volatile int probe_result = -3;
2✔
721

722
#if defined(BOTAN_TARGET_OS_HAS_POSIX1) && !defined(BOTAN_TARGET_OS_IS_EMSCRIPTEN)
723
   struct sigaction old_sigaction {};
2✔
724

725
   struct sigaction sigaction {};
2✔
726

727
   sigaction.sa_handler = botan_sigill_handler;
2✔
728
   sigemptyset(&sigaction.sa_mask);
2✔
729
   sigaction.sa_flags = 0;
2✔
730

731
   int rc = ::sigaction(SIGILL, &sigaction, &old_sigaction);
2✔
732

733
   if(rc != 0) {
2✔
734
      throw System_Error("run_cpu_instruction_probe sigaction failed", errno);
×
735
   }
736

737
   rc = sigsetjmp(g_sigill_jmp_buf, /*save sigs*/ 1);
3✔
738

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

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

753
#else
754
   BOTAN_UNUSED(probe_fn);
755
#endif
756

757
   return probe_result;
2✔
758
}
759

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

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

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

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

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

793
         POSIX_Echo_Suppression(const POSIX_Echo_Suppression& other) = delete;
794
         POSIX_Echo_Suppression(POSIX_Echo_Suppression&& other) = delete;
795
         POSIX_Echo_Suppression& operator=(const POSIX_Echo_Suppression& other) = delete;
796
         POSIX_Echo_Suppression& operator=(POSIX_Echo_Suppression&& other) = delete;
797

798
      private:
799
         int m_stdin_fd;
800
         struct termios m_old_termios;
801
   };
802

803
   return std::make_unique<POSIX_Echo_Suppression>();
×
804

805
#elif defined(BOTAN_TARGET_OS_HAS_WIN32)
806

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

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

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

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

833
         Win32_Echo_Suppression(const Win32_Echo_Suppression& other) = delete;
834
         Win32_Echo_Suppression(Win32_Echo_Suppression&& other) = delete;
835
         Win32_Echo_Suppression& operator=(const Win32_Echo_Suppression& other) = delete;
836
         Win32_Echo_Suppression& operator=(Win32_Echo_Suppression&& other) = delete;
837

838
      private:
839
         HANDLE m_input_handle;
840
         DWORD m_console_state;
841
   };
842

843
   return std::make_unique<Win32_Echo_Suppression>();
844

845
#else
846

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

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