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

randombit / botan / 13212092742

08 Feb 2025 12:33AM UTC coverage: 91.658% (-0.004%) from 91.662%
13212092742

push

github

web-flow
Merge pull request #4642 from randombit/jack/target-info-header

Add internal target_info.h header

94839 of 103471 relevant lines covered (91.66%)

11295178.12 hits per line

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

66.85
/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/cpuid.h>
14
#include <botan/internal/target_info.h>
15

16
#include <algorithm>
17
#include <chrono>
18
#include <cstdlib>
19
#include <iomanip>
20
#include <sstream>
21

22
#if defined(BOTAN_TARGET_OS_HAS_EXPLICIT_BZERO)
23
   #include <string.h>
24
#endif
25

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

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

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

48
#if defined(BOTAN_TARGET_OS_HAS_AUXINFO)
49
   #include <dlfcn.h>
50
   #include <elf.h>
51
#endif
52

53
#if defined(BOTAN_TARGET_OS_HAS_WIN32)
54
   #define NOMINMAX 1
55
   #define _WINSOCKAPI_  // stop windows.h including winsock.h
56
   #include <windows.h>
57
   #if defined(BOTAN_BUILD_COMPILER_IS_MSVC)
58
      #include <libloaderapi.h>
59
      #include <stringapiset.h>
60
   #endif
61
#endif
62

63
#if defined(BOTAN_TARGET_OS_IS_IOS) || defined(BOTAN_TARGET_OS_IS_MACOS)
64
   #include <mach/vm_statistics.h>
65
   #include <sys/sysctl.h>
66
   #include <sys/types.h>
67
#endif
68

69
#if defined(BOTAN_TARGET_OS_HAS_PRCTL)
70
   #include <sys/prctl.h>
71
#endif
72

73
#if defined(BOTAN_TARGET_OS_IS_FREEBSD) || defined(BOTAN_TARGET_OS_IS_OPENBSD) || defined(BOTAN_TARGET_OS_IS_DRAGONFLY)
74
   #include <pthread_np.h>
75
#endif
76

77
#if defined(BOTAN_TARGET_OS_IS_HAIKU)
78
   #include <kernel/OS.h>
79
#endif
80

81
namespace Botan {
82

83
uint32_t OS::get_process_id() {
191,807✔
84
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
85
   return ::getpid();
191,807✔
86
#elif defined(BOTAN_TARGET_OS_HAS_WIN32)
87
   return ::GetCurrentProcessId();
88
#elif defined(BOTAN_TARGET_OS_IS_LLVM) || defined(BOTAN_TARGET_OS_IS_NONE)
89
   return 0;  // truly no meaningful value
90
#else
91
   #error "Missing get_process_id"
92
#endif
93
}
94

95
namespace {
96

97
#if defined(BOTAN_TARGET_OS_HAS_GETAUXVAL) || defined(BOTAN_TARGET_OS_HAS_ELF_AUX_INFO) || \
98
   defined(BOTAN_TARGET_OS_HAS_AUXINFO)
99

100
   #define BOTAN_TARGET_HAS_AUXVAL_INTERFACE
101
#endif
102

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

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

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

146
   return {};
147
}
148

149
}  // namespace
150

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

162
namespace {
163

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

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

182
}  // namespace
183

184
uint64_t OS::get_cpu_cycle_counter() {
3,557,315✔
185
   uint64_t rtc = 0;
3,557,315✔
186

187
#if defined(BOTAN_TARGET_OS_HAS_WIN32)
188
   LARGE_INTEGER tv;
189
   ::QueryPerformanceCounter(&tv);
190
   rtc = tv.QuadPart;
191

192
#elif defined(BOTAN_USE_GCC_INLINE_ASM)
193

194
   #if defined(BOTAN_TARGET_CPU_IS_X86_FAMILY)
195

196
   if(CPUID::has_rdtsc()) {
3,557,315✔
197
      uint32_t rtc_low = 0, rtc_high = 0;
3,557,315✔
198
      asm volatile("rdtsc" : "=d"(rtc_high), "=a"(rtc_low));
3,557,315✔
199
      rtc = (static_cast<uint64_t>(rtc_high) << 32) | rtc_low;
3,557,315✔
200
   }
201

202
   #elif defined(BOTAN_TARGET_ARCH_IS_PPC64)
203

204
   for(;;) {
205
      uint32_t rtc_low = 0, rtc_high = 0, rtc_high2 = 0;
206
      asm volatile("mftbu %0" : "=r"(rtc_high));
207
      asm volatile("mftb %0" : "=r"(rtc_low));
208
      asm volatile("mftbu %0" : "=r"(rtc_high2));
209

210
      if(rtc_high == rtc_high2) {
211
         rtc = (static_cast<uint64_t>(rtc_high) << 32) | rtc_low;
212
         break;
213
      }
214
   }
215

216
   #elif defined(BOTAN_TARGET_ARCH_IS_ALPHA)
217
   asm volatile("rpcc %0" : "=r"(rtc));
218

219
      // OpenBSD does not trap access to the %tick register
220
   #elif defined(BOTAN_TARGET_ARCH_IS_SPARC64) && !defined(BOTAN_TARGET_OS_IS_OPENBSD)
221
   asm volatile("rd %%tick, %0" : "=r"(rtc));
222

223
   #elif defined(BOTAN_TARGET_ARCH_IS_IA64)
224
   asm volatile("mov %0=ar.itc" : "=r"(rtc));
225

226
   #elif defined(BOTAN_TARGET_ARCH_IS_S390X)
227
   asm volatile("stck 0(%0)" : : "a"(&rtc) : "memory", "cc");
228

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

232
   #else
233
      //#warning "OS::get_cpu_cycle_counter not implemented"
234
   #endif
235

236
#endif
237

238
   return rtc;
3,557,315✔
239
}
240

241
size_t OS::get_cpu_available() {
799✔
242
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
243

244
   #if defined(_SC_NPROCESSORS_ONLN)
245
   const long cpu_online = ::sysconf(_SC_NPROCESSORS_ONLN);
799✔
246
   if(cpu_online > 0) {
799✔
247
      return static_cast<size_t>(cpu_online);
799✔
248
   }
249
   #endif
250

251
   #if defined(_SC_NPROCESSORS_CONF)
252
   const long cpu_conf = ::sysconf(_SC_NPROCESSORS_CONF);
×
253
   if(cpu_conf > 0) {
×
254
      return static_cast<size_t>(cpu_conf);
×
255
   }
256
   #endif
257

258
#endif
259

260
#if defined(BOTAN_TARGET_OS_HAS_THREADS)
261
   // hardware_concurrency is allowed to return 0 if the value is not
262
   // well defined or not computable.
263
   const size_t hw_concur = std::thread::hardware_concurrency();
×
264

265
   if(hw_concur > 0) {
×
266
      return hw_concur;
267
   }
268
#endif
269

270
   return 1;
271
}
272

273
uint64_t OS::get_high_resolution_clock() {
4,646✔
274
   if(uint64_t cpu_clock = OS::get_cpu_cycle_counter()) {
4,646✔
275
      return cpu_clock;
276
   }
277

278
#if defined(BOTAN_TARGET_OS_IS_EMSCRIPTEN)
279
   return emscripten_get_now();
280
#endif
281

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

289
#if defined(BOTAN_TARGET_OS_HAS_CLOCK_GETTIME)
290

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

310
   for(clockid_t clock : clock_types) {
×
311
      struct timespec ts;
×
312
      if(::clock_gettime(clock, &ts) == 0) {
×
313
         return (static_cast<uint64_t>(ts.tv_sec) * 1000000000) + static_cast<uint64_t>(ts.tv_nsec);
×
314
      }
315
   }
316
#endif
317

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

327
uint64_t OS::get_system_timestamp_ns() {
3,513,387✔
328
#if defined(BOTAN_TARGET_OS_HAS_CLOCK_GETTIME)
329
   struct timespec ts;
3,513,387✔
330
   if(::clock_gettime(CLOCK_REALTIME, &ts) == 0) {
3,513,387✔
331
      return (static_cast<uint64_t>(ts.tv_sec) * 1000000000) + static_cast<uint64_t>(ts.tv_nsec);
3,513,387✔
332
   }
333
#endif
334

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

343
std::string OS::format_time(time_t time, const std::string& format) {
2,831✔
344
   std::tm tm;
2,831✔
345

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

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

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

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

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

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

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

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

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

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

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

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

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

441
   return 0;
442
}
443

444
bool OS::read_env_variable(std::string& value_out, std::string_view name_view) {
22,564✔
445
   value_out = "";
22,564✔
446

447
   if(running_in_privileged_state()) {
22,564✔
448
      return false;
449
   }
450

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

474
   return false;
475
}
22,564✔
476

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

487
   return def;
488
}
8,736✔
489

490
#if defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
491

492
namespace {
493

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

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

513
}  // namespace
514

515
#endif
516

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

520
#if(defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)) || \
521
   defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
522

523
   result.reserve(count);
8,736✔
524

525
   const size_t page_size = OS::system_page_size();
8,736✔
526

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

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

534
   #if defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
535

536
      int mmap_flags = MAP_PRIVATE;
1,118,208✔
537

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

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

550
      int mmap_prot = PROT_READ | PROT_WRITE;
1,118,208✔
551

552
      #if defined(PROT_MAX)
553
      mmap_prot |= PROT_MAX(mmap_prot);
554
      #endif
555

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

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

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

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

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

581
      if(ptr == nullptr)
582
         continue;
583

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

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

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

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

605
   return result;
8,736✔
606
}
×
607

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

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

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

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

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
   int r = prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME, reinterpret_cast<uintptr_t>(page), size, name);
1,118,208✔
662
   BOTAN_UNUSED(r);
1,118,208✔
663
#else
664
   BOTAN_UNUSED(page, size);
665
#endif
666
}
×
667

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

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

705
namespace {
706

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

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

714
}  // namespace
715

716
#endif
717

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

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

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

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

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

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

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

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

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

755
   return probe_result;
2✔
756
}
757

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

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

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

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

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

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

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

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

804
#elif defined(BOTAN_TARGET_OS_HAS_WIN32)
805

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

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

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

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

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

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

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

844
#else
845

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

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