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

randombit / botan / 13606441730

01 Mar 2025 03:02PM UTC coverage: 91.692% (+0.004%) from 91.688%
13606441730

push

github

web-flow
Merge pull request #4737 from randombit/jack/move-include

Move include for explicit_bzero

95833 of 104516 relevant lines covered (91.69%)

11235833.55 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() {
192,510✔
78
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
79
   return ::getpid();
192,510✔
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) {
22,563✔
120
   if(id) {
×
121
#if defined(BOTAN_TARGET_OS_HAS_GETAUXVAL)
122
      return ::getauxval(*id);
22,563✔
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() {
22,563✔
154
#if defined(AT_SECURE)
155
   if(auto at_secure = get_auxval(AT_SECURE)) {
45,126✔
156
      return at_secure != 0;
45,126✔
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,341,422✔
170
   uint64_t rtc = 0;
3,341,422✔
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,341,422✔
182
   asm volatile("rdtsc" : "=d"(rtc_high), "=a"(rtc_low));
3,341,422✔
183
   rtc = (static_cast<uint64_t>(rtc_high) << 32) | rtc_low;
3,341,422✔
184

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

187
   if(CPUID::has_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,341,422✔
230
}
231

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

235
   #if defined(_SC_NPROCESSORS_ONLN)
236
   const long cpu_online = ::sysconf(_SC_NPROCESSORS_ONLN);
799✔
237
   if(cpu_online > 0) {
799✔
238
      return static_cast<size_t>(cpu_online);
799✔
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,645✔
265
   if(uint64_t cpu_clock = OS::get_cpu_cycle_counter()) {
4,645✔
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
      if(::clock_gettime(clock, &ts) == 0) {
×
304
         return (static_cast<uint64_t>(ts.tv_sec) * 1000000000) + static_cast<uint64_t>(ts.tv_nsec);
×
305
      }
306
   }
307
#endif
308

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

318
uint64_t OS::get_system_timestamp_ns() {
3,296,159✔
319
#if defined(BOTAN_TARGET_OS_HAS_CLOCK_GETTIME)
320
   struct timespec ts;
3,296,159✔
321
   if(::clock_gettime(CLOCK_REALTIME, &ts) == 0) {
3,296,159✔
322
      return (static_cast<uint64_t>(ts.tv_sec) * 1000000000) + static_cast<uint64_t>(ts.tv_nsec);
3,296,159✔
323
   }
324
#endif
325

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

334
std::string OS::format_time(time_t time, const std::string& format) {
2,847✔
335
   std::tm tm;
2,847✔
336

337
#if defined(BOTAN_TARGET_OS_HAS_WIN32)
338
   localtime_s(&tm, &time);
339
#elif defined(BOTAN_TARGET_OS_HAS_POSIX1)
340
   localtime_r(&time, &tm);
2,847✔
341
#else
342
   if(auto tmp = std::localtime(&time)) {
343
      tm = *tmp;
344
   } else {
345
      throw Encoding_Error("Could not convert time_t to localtime");
346
   }
347
#endif
348

349
   std::ostringstream oss;
2,847✔
350
   oss << std::put_time(&tm, format.c_str());
2,847✔
351
   return oss.str();
5,694✔
352
}
2,847✔
353

354
size_t OS::system_page_size() {
4,499,040✔
355
   const size_t default_page_size = 4096;
4,499,040✔
356

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

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

385
   /*
386
   * If RLIMIT_MEMLOCK is not defined, likely the OS does not support
387
   * unprivileged mlock calls.
388
   */
389
#if defined(RLIMIT_MEMLOCK) && defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
390
   const size_t mlock_requested =
8,736✔
391
      std::min<size_t>(read_env_variable_sz("BOTAN_MLOCK_POOL_SIZE", max_locked_kb), max_locked_kb);
8,736✔
392

393
   if(mlock_requested > 0) {
8,736✔
394
      struct ::rlimit limits;
8,736✔
395

396
      ::getrlimit(RLIMIT_MEMLOCK, &limits);
8,736✔
397

398
      if(limits.rlim_cur < limits.rlim_max) {
8,736✔
399
         limits.rlim_cur = limits.rlim_max;
×
400
         ::setrlimit(RLIMIT_MEMLOCK, &limits);
×
401
         ::getrlimit(RLIMIT_MEMLOCK, &limits);
×
402
      }
403

404
      return std::min<size_t>(limits.rlim_cur, mlock_requested * 1024);
17,472✔
405
   }
406

407
#elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
408
   const size_t mlock_requested =
409
      std::min<size_t>(read_env_variable_sz("BOTAN_MLOCK_POOL_SIZE", max_locked_kb), max_locked_kb);
410

411
   SIZE_T working_min = 0, working_max = 0;
412
   if(!::GetProcessWorkingSetSize(::GetCurrentProcess(), &working_min, &working_max)) {
413
      return 0;
414
   }
415

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

432
   return 0;
433
}
434

435
bool OS::read_env_variable(std::string& value_out, std::string_view name_view) {
22,563✔
436
   value_out = "";
22,563✔
437

438
   if(running_in_privileged_state()) {
22,563✔
439
      return false;
440
   }
441

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

465
   return false;
466
}
22,563✔
467

468
size_t OS::read_env_variable_sz(std::string_view name, size_t def) {
8,736✔
469
   std::string value;
8,736✔
470
   if(read_env_variable(value, name) && !value.empty()) {
8,736✔
471
      try {
×
472
         const size_t val = std::stoul(value, nullptr);
8,736✔
473
         return val;
474
      } catch(std::exception&) { /* ignore it */
×
475
      }
×
476
   }
477

478
   return def;
479
}
8,736✔
480

481
#if defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
482

483
namespace {
484

485
int get_locked_fd() {
486
   #if defined(BOTAN_TARGET_OS_IS_IOS) || defined(BOTAN_TARGET_OS_IS_MACOS)
487
   // On Darwin, tagging anonymous pages allows vmmap to track these.
488
   // Allowed from 240 to 255 for userland applications
489
   static constexpr int default_locked_fd = 255;
490
   int locked_fd = default_locked_fd;
491

492
   if(size_t locked_fdl = OS::read_env_variable_sz("BOTAN_LOCKED_FD", default_locked_fd)) {
493
      if(locked_fdl < 240 || locked_fdl > 255) {
494
         locked_fdl = default_locked_fd;
495
      }
496
      locked_fd = static_cast<int>(locked_fdl);
497
   }
498
   return VM_MAKE_TAG(locked_fd);
499
   #else
500
   return -1;
501
   #endif
502
}
503

504
}  // namespace
505

506
#endif
507

508
std::vector<void*> OS::allocate_locked_pages(size_t count) {
8,736✔
509
   std::vector<void*> result;
8,736✔
510

511
#if(defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)) || \
512
   defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
513

514
   result.reserve(count);
8,736✔
515

516
   const size_t page_size = OS::system_page_size();
8,736✔
517

518
   #if defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
519
   static const int locked_fd = get_locked_fd();
8,736✔
520
   #endif
521

522
   for(size_t i = 0; i != count; ++i) {
1,126,944✔
523
      void* ptr = nullptr;
1,118,208✔
524

525
   #if defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
526

527
      int mmap_flags = MAP_PRIVATE;
1,118,208✔
528

529
      #if defined(MAP_ANONYMOUS)
530
      mmap_flags |= MAP_ANONYMOUS;
1,118,208✔
531
      #elif defined(MAP_ANON)
532
      mmap_flags |= MAP_ANON;
533
      #endif
534

535
      #if defined(MAP_CONCEAL)
536
      mmap_flags |= MAP_CONCEAL;
537
      #elif defined(MAP_NOCORE)
538
      mmap_flags |= MAP_NOCORE;
539
      #endif
540

541
      int mmap_prot = PROT_READ | PROT_WRITE;
1,118,208✔
542

543
      #if defined(PROT_MAX)
544
      mmap_prot |= PROT_MAX(mmap_prot);
545
      #endif
546

547
      ptr = ::mmap(nullptr,
1,118,208✔
548
                   3 * page_size,
549
                   mmap_prot,
550
                   mmap_flags,
551
                   /*fd=*/locked_fd,
552
                   /*offset=*/0);
553

554
      if(ptr == MAP_FAILED) {
1,118,208✔
555
         continue;
×
556
      }
557

558
      // lock the data page
559
      if(::mlock(static_cast<uint8_t*>(ptr) + page_size, page_size) != 0) {
1,118,208✔
560
         ::munmap(ptr, 3 * page_size);
×
561
         continue;
×
562
      }
563

564
      #if defined(MADV_DONTDUMP)
565
      // we ignore errors here, as DONTDUMP is just a bonus
566
      ::madvise(static_cast<uint8_t*>(ptr) + page_size, page_size, MADV_DONTDUMP);
1,118,208✔
567
      #endif
568

569
   #elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
570
      ptr = ::VirtualAlloc(nullptr, 3 * page_size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
571

572
      if(ptr == nullptr)
573
         continue;
574

575
      if(::VirtualLock(static_cast<uint8_t*>(ptr) + page_size, page_size) == 0) {
576
         ::VirtualFree(ptr, 0, MEM_RELEASE);
577
         continue;
578
      }
579
   #endif
580

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

583
      // Attempts to name the data page
584
      page_named(ptr, 3 * page_size);
2,236,416✔
585
      // Make guard page preceeding the data page
586
      page_prohibit_access(static_cast<uint8_t*>(ptr));
1,118,208✔
587
      // Make guard page following the data page
588
      page_prohibit_access(static_cast<uint8_t*>(ptr) + 2 * page_size);
1,118,208✔
589

590
      result.push_back(static_cast<uint8_t*>(ptr) + page_size);
1,118,208✔
591
   }
592
#else
593
   BOTAN_UNUSED(count);
594
#endif
595

596
   return result;
8,736✔
597
}
×
598

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

613
void OS::page_prohibit_access(void* page) {
2,236,416✔
614
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
615
   const size_t page_size = OS::system_page_size();
2,236,416✔
616
   ::mprotect(page, page_size, PROT_NONE);
2,236,416✔
617
#elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
618
   const size_t page_size = OS::system_page_size();
619
   DWORD old_perms = 0;
620
   ::VirtualProtect(page, page_size, PAGE_NOACCESS, &old_perms);
621
   BOTAN_UNUSED(old_perms);
622
#else
623
   BOTAN_UNUSED(page);
624
#endif
625
}
2,236,416✔
626

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

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

633
      secure_scrub_memory(ptr, page_size);
1,118,208✔
634

635
      // ptr points to the data page, guard pages are before and after
636
      page_allow_access(static_cast<uint8_t*>(ptr) - page_size);
1,118,208✔
637
      page_allow_access(static_cast<uint8_t*>(ptr) + page_size);
1,118,208✔
638

639
#if defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
640
      ::munlock(ptr, page_size);
1,118,208✔
641
      ::munmap(static_cast<uint8_t*>(ptr) - page_size, 3 * page_size);
1,118,208✔
642
#elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
643
      ::VirtualUnlock(ptr, page_size);
644
      ::VirtualFree(static_cast<uint8_t*>(ptr) - page_size, 0, MEM_RELEASE);
645
#endif
646
   }
647
}
8,736✔
648

649
void OS::page_named(void* page, size_t size) {
1,118,208✔
650
#if defined(BOTAN_TARGET_OS_HAS_PRCTL) && defined(PR_SET_VMA) && defined(PR_SET_VMA_ANON_NAME)
651
   static constexpr char name[] = "Botan mlock pool";
1,118,208✔
652
   int r = prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME, reinterpret_cast<uintptr_t>(page), size, name);
1,118,208✔
653
   BOTAN_UNUSED(r);
1,118,208✔
654
#else
655
   BOTAN_UNUSED(page, size);
656
#endif
657
}
×
658

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

694
#if defined(BOTAN_TARGET_OS_HAS_POSIX1) && !defined(BOTAN_TARGET_OS_IS_EMSCRIPTEN)
695

696
namespace {
697

698
// NOLINTNEXTLINE(*-avoid-non-const-global-variables)
699
::sigjmp_buf g_sigill_jmp_buf;
700

701
void botan_sigill_handler(int /*unused*/) {
1✔
702
   siglongjmp(g_sigill_jmp_buf, /*non-zero return value*/ 1);
1✔
703
}
704

705
}  // namespace
706

707
#endif
708

709
int OS::run_cpu_instruction_probe(const std::function<int()>& probe_fn) {
2✔
710
   volatile int probe_result = -3;
2✔
711

712
#if defined(BOTAN_TARGET_OS_HAS_POSIX1) && !defined(BOTAN_TARGET_OS_IS_EMSCRIPTEN)
713
   struct sigaction old_sigaction;
2✔
714
   struct sigaction sigaction;
2✔
715

716
   sigaction.sa_handler = botan_sigill_handler;
2✔
717
   sigemptyset(&sigaction.sa_mask);
2✔
718
   sigaction.sa_flags = 0;
2✔
719

720
   int rc = ::sigaction(SIGILL, &sigaction, &old_sigaction);
2✔
721

722
   if(rc != 0) {
2✔
723
      throw System_Error("run_cpu_instruction_probe sigaction failed", errno);
×
724
   }
725

726
   rc = sigsetjmp(g_sigill_jmp_buf, /*save sigs*/ 1);
3✔
727

728
   if(rc == 0) {
3✔
729
      // first call to sigsetjmp
730
      probe_result = probe_fn();
3✔
731
   } else if(rc == 1) {
1✔
732
      // non-local return from siglongjmp in signal handler: return error
733
      probe_result = -1;
1✔
734
   }
735

736
   // Restore old SIGILL handler, if any
737
   rc = ::sigaction(SIGILL, &old_sigaction, nullptr);
2✔
738
   if(rc != 0) {
2✔
739
      throw System_Error("run_cpu_instruction_probe sigaction restore failed", errno);
×
740
   }
741

742
#else
743
   BOTAN_UNUSED(probe_fn);
744
#endif
745

746
   return probe_result;
2✔
747
}
748

749
std::unique_ptr<OS::Echo_Suppression> OS::suppress_echo_on_terminal() {
×
750
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
751
   class POSIX_Echo_Suppression : public Echo_Suppression {
×
752
      public:
753
         POSIX_Echo_Suppression() {
×
754
            m_stdin_fd = fileno(stdin);
×
755
            if(::tcgetattr(m_stdin_fd, &m_old_termios) != 0) {
×
756
               throw System_Error("Getting terminal status failed", errno);
×
757
            }
758

759
            struct termios noecho_flags = m_old_termios;
×
760
            noecho_flags.c_lflag &= ~ECHO;
×
761
            noecho_flags.c_lflag |= ECHONL;
×
762

763
            if(::tcsetattr(m_stdin_fd, TCSANOW, &noecho_flags) != 0) {
×
764
               throw System_Error("Clearing terminal echo bit failed", errno);
×
765
            }
766
         }
×
767

768
         void reenable_echo() override {
×
769
            if(m_stdin_fd > 0) {
×
770
               if(::tcsetattr(m_stdin_fd, TCSANOW, &m_old_termios) != 0) {
×
771
                  throw System_Error("Restoring terminal echo bit failed", errno);
×
772
               }
773
               m_stdin_fd = -1;
×
774
            }
775
         }
×
776

777
         ~POSIX_Echo_Suppression() override {
×
778
            try {
×
779
               reenable_echo();
×
780
            } catch(...) {}
×
781
         }
×
782

783
         POSIX_Echo_Suppression(const POSIX_Echo_Suppression& other) = delete;
784
         POSIX_Echo_Suppression(POSIX_Echo_Suppression&& other) = delete;
785
         POSIX_Echo_Suppression& operator=(const POSIX_Echo_Suppression& other) = delete;
786
         POSIX_Echo_Suppression& operator=(POSIX_Echo_Suppression&& other) = delete;
787

788
      private:
789
         int m_stdin_fd;
790
         struct termios m_old_termios;
791
   };
792

793
   return std::make_unique<POSIX_Echo_Suppression>();
×
794

795
#elif defined(BOTAN_TARGET_OS_HAS_WIN32)
796

797
   class Win32_Echo_Suppression : public Echo_Suppression {
798
      public:
799
         Win32_Echo_Suppression() {
800
            m_input_handle = ::GetStdHandle(STD_INPUT_HANDLE);
801
            if(::GetConsoleMode(m_input_handle, &m_console_state) == 0)
802
               throw System_Error("Getting console mode failed", ::GetLastError());
803

804
            DWORD new_mode = ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT;
805
            if(::SetConsoleMode(m_input_handle, new_mode) == 0)
806
               throw System_Error("Setting console mode failed", ::GetLastError());
807
         }
808

809
         void reenable_echo() override {
810
            if(m_input_handle != INVALID_HANDLE_VALUE) {
811
               if(::SetConsoleMode(m_input_handle, m_console_state) == 0)
812
                  throw System_Error("Setting console mode failed", ::GetLastError());
813
               m_input_handle = INVALID_HANDLE_VALUE;
814
            }
815
         }
816

817
         ~Win32_Echo_Suppression() override {
818
            try {
819
               reenable_echo();
820
            } catch(...) {}
821
         }
822

823
         Win32_Echo_Suppression(const Win32_Echo_Suppression& other) = delete;
824
         Win32_Echo_Suppression(Win32_Echo_Suppression&& other) = delete;
825
         Win32_Echo_Suppression& operator=(const Win32_Echo_Suppression& other) = delete;
826
         Win32_Echo_Suppression& operator=(Win32_Echo_Suppression&& other) = delete;
827

828
      private:
829
         HANDLE m_input_handle;
830
         DWORD m_console_state;
831
   };
832

833
   return std::make_unique<Win32_Echo_Suppression>();
834

835
#else
836

837
   // Not supported on this platform, return null
838
   return nullptr;
839
#endif
840
}
841

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