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

randombit / botan / 13605970662

01 Mar 2025 02:59PM UTC coverage: 91.688% (-0.004%) from 91.692%
13605970662

push

github

web-flow
Merge pull request #4736 from randombit/jack/remove-dlauxinfo

Remove support for calling NetBSD _dlauxinfo

95829 of 104516 relevant lines covered (91.69%)

11219159.56 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_EXPLICIT_BZERO)
26
   #include <string.h>
27
#endif
28

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

43
#if defined(BOTAN_TARGET_OS_IS_EMSCRIPTEN)
44
   #include <emscripten/emscripten.h>
45
#endif
46

47
#if defined(BOTAN_TARGET_OS_HAS_GETAUXVAL) || defined(BOTAN_TARGET_OS_HAS_ELF_AUX_INFO)
48
   #include <sys/auxv.h>
49
#endif
50

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

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

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

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

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

79
namespace Botan {
80

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

93
namespace {
94

95
#if defined(BOTAN_TARGET_OS_HAS_GETAUXVAL) || defined(BOTAN_TARGET_OS_HAS_ELF_AUX_INFO)
96
   #define BOTAN_TARGET_HAS_AUXVAL_INTERFACE
97
#endif
98

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

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

123
std::optional<unsigned long> get_auxval(std::optional<unsigned long> id) {
22,563✔
124
   if(id) {
×
125
#if defined(BOTAN_TARGET_OS_HAS_GETAUXVAL)
126
      return ::getauxval(*id);
22,563✔
127
#elif defined(BOTAN_TARGET_OS_HAS_ELF_AUX_INFO)
128
      unsigned long auxinfo = 0;
129
      if(::elf_aux_info(static_cast<int>(*id), &auxinfo, sizeof(auxinfo)) == 0) {
130
         return auxinfo;
131
      }
132
#endif
133
   }
134

135
   return {};
136
}
137

138
}  // namespace
139

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

151
namespace {
152

153
/**
154
* Test if we are currently running with elevated permissions
155
* eg setuid, setgid, or with POSIX caps set.
156
*/
157
bool running_in_privileged_state() {
22,563✔
158
#if defined(AT_SECURE)
159
   if(auto at_secure = get_auxval(AT_SECURE)) {
45,126✔
160
      return at_secure != 0;
45,126✔
161
   }
162
#endif
163

164
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
165
   return (::getuid() != ::geteuid()) || (::getgid() != ::getegid());
166
#else
167
   return false;
168
#endif
169
}
170

171
}  // namespace
172

173
uint64_t OS::get_cpu_cycle_counter() {
6,141,296✔
174
   uint64_t rtc = 0;
6,141,296✔
175

176
#if defined(BOTAN_TARGET_OS_HAS_WIN32)
177
   LARGE_INTEGER tv;
178
   ::QueryPerformanceCounter(&tv);
179
   rtc = tv.QuadPart;
180

181
#elif defined(BOTAN_USE_GCC_INLINE_ASM)
182

183
   #if defined(BOTAN_TARGET_ARCH_IS_X86_64)
184

185
   uint32_t rtc_low = 0, rtc_high = 0;
6,141,296✔
186
   asm volatile("rdtsc" : "=d"(rtc_high), "=a"(rtc_low));
6,141,296✔
187
   rtc = (static_cast<uint64_t>(rtc_high) << 32) | rtc_low;
6,141,296✔
188

189
   #elif defined(BOTAN_TARGET_CPU_IS_X86_FAMILY) && defined(BOTAN_HAS_CPUID)
190

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

197
   #elif defined(BOTAN_TARGET_ARCH_IS_PPC64)
198

199
   for(;;) {
200
      uint32_t rtc_low = 0, rtc_high = 0, 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;
6,141,296✔
234
}
235

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

239
   #if defined(_SC_NPROCESSORS_ONLN)
240
   const long cpu_online = ::sysconf(_SC_NPROCESSORS_ONLN);
799✔
241
   if(cpu_online > 0) {
799✔
242
      return static_cast<size_t>(cpu_online);
799✔
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,641✔
269
   if(uint64_t cpu_clock = OS::get_cpu_cycle_counter()) {
4,641✔
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
      if(::clock_gettime(clock, &ts) == 0) {
×
308
         return (static_cast<uint64_t>(ts.tv_sec) * 1000000000) + static_cast<uint64_t>(ts.tv_nsec);
×
309
      }
310
   }
311
#endif
312

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

322
uint64_t OS::get_system_timestamp_ns() {
6,096,497✔
323
#if defined(BOTAN_TARGET_OS_HAS_CLOCK_GETTIME)
324
   struct timespec ts;
6,096,497✔
325
   if(::clock_gettime(CLOCK_REALTIME, &ts) == 0) {
6,096,497✔
326
      return (static_cast<uint64_t>(ts.tv_sec) * 1000000000) + static_cast<uint64_t>(ts.tv_nsec);
6,096,497✔
327
   }
328
#endif
329

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

338
std::string OS::format_time(time_t time, const std::string& format) {
2,847✔
339
   std::tm tm;
2,847✔
340

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

353
   std::ostringstream oss;
2,847✔
354
   oss << std::put_time(&tm, format.c_str());
2,847✔
355
   return oss.str();
5,694✔
356
}
2,847✔
357

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

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

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

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

397
   if(mlock_requested > 0) {
8,736✔
398
      struct ::rlimit limits;
8,736✔
399

400
      ::getrlimit(RLIMIT_MEMLOCK, &limits);
8,736✔
401

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

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

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

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

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

436
   return 0;
437
}
438

439
bool OS::read_env_variable(std::string& value_out, std::string_view name_view) {
22,563✔
440
   value_out = "";
22,563✔
441

442
   if(running_in_privileged_state()) {
22,563✔
443
      return false;
444
   }
445

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

469
   return false;
470
}
22,563✔
471

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

482
   return def;
483
}
8,736✔
484

485
#if defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
486

487
namespace {
488

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

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

508
}  // namespace
509

510
#endif
511

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

515
#if(defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)) || \
516
   defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
517

518
   result.reserve(count);
8,736✔
519

520
   const size_t page_size = OS::system_page_size();
8,736✔
521

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

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

529
   #if defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
530

531
      int mmap_flags = MAP_PRIVATE;
1,118,208✔
532

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

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

545
      int mmap_prot = PROT_READ | PROT_WRITE;
1,118,208✔
546

547
      #if defined(PROT_MAX)
548
      mmap_prot |= PROT_MAX(mmap_prot);
549
      #endif
550

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

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

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

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

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

576
      if(ptr == nullptr)
577
         continue;
578

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

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

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

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

600
   return result;
8,736✔
601
}
×
602

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

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

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

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

637
      secure_scrub_memory(ptr, page_size);
1,118,208✔
638

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

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

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

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

698
#if defined(BOTAN_TARGET_OS_HAS_POSIX1) && !defined(BOTAN_TARGET_OS_IS_EMSCRIPTEN)
699

700
namespace {
701

702
// NOLINTNEXTLINE(*-avoid-non-const-global-variables)
703
::sigjmp_buf g_sigill_jmp_buf;
704

705
void botan_sigill_handler(int /*unused*/) {
1✔
706
   siglongjmp(g_sigill_jmp_buf, /*non-zero return value*/ 1);
1✔
707
}
708

709
}  // namespace
710

711
#endif
712

713
int OS::run_cpu_instruction_probe(const std::function<int()>& probe_fn) {
2✔
714
   volatile int probe_result = -3;
2✔
715

716
#if defined(BOTAN_TARGET_OS_HAS_POSIX1) && !defined(BOTAN_TARGET_OS_IS_EMSCRIPTEN)
717
   struct sigaction old_sigaction;
2✔
718
   struct sigaction sigaction;
2✔
719

720
   sigaction.sa_handler = botan_sigill_handler;
2✔
721
   sigemptyset(&sigaction.sa_mask);
2✔
722
   sigaction.sa_flags = 0;
2✔
723

724
   int rc = ::sigaction(SIGILL, &sigaction, &old_sigaction);
2✔
725

726
   if(rc != 0) {
2✔
727
      throw System_Error("run_cpu_instruction_probe sigaction failed", errno);
×
728
   }
729

730
   rc = sigsetjmp(g_sigill_jmp_buf, /*save sigs*/ 1);
3✔
731

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

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

746
#else
747
   BOTAN_UNUSED(probe_fn);
748
#endif
749

750
   return probe_result;
2✔
751
}
752

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

763
            struct termios noecho_flags = m_old_termios;
×
764
            noecho_flags.c_lflag &= ~ECHO;
×
765
            noecho_flags.c_lflag |= ECHONL;
×
766

767
            if(::tcsetattr(m_stdin_fd, TCSANOW, &noecho_flags) != 0) {
×
768
               throw System_Error("Clearing terminal echo bit failed", errno);
×
769
            }
770
         }
×
771

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

781
         ~POSIX_Echo_Suppression() override {
×
782
            try {
×
783
               reenable_echo();
×
784
            } catch(...) {}
×
785
         }
×
786

787
         POSIX_Echo_Suppression(const POSIX_Echo_Suppression& other) = delete;
788
         POSIX_Echo_Suppression(POSIX_Echo_Suppression&& other) = delete;
789
         POSIX_Echo_Suppression& operator=(const POSIX_Echo_Suppression& other) = delete;
790
         POSIX_Echo_Suppression& operator=(POSIX_Echo_Suppression&& other) = delete;
791

792
      private:
793
         int m_stdin_fd;
794
         struct termios m_old_termios;
795
   };
796

797
   return std::make_unique<POSIX_Echo_Suppression>();
×
798

799
#elif defined(BOTAN_TARGET_OS_HAS_WIN32)
800

801
   class Win32_Echo_Suppression : public Echo_Suppression {
802
      public:
803
         Win32_Echo_Suppression() {
804
            m_input_handle = ::GetStdHandle(STD_INPUT_HANDLE);
805
            if(::GetConsoleMode(m_input_handle, &m_console_state) == 0)
806
               throw System_Error("Getting console mode failed", ::GetLastError());
807

808
            DWORD new_mode = ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT;
809
            if(::SetConsoleMode(m_input_handle, new_mode) == 0)
810
               throw System_Error("Setting console mode failed", ::GetLastError());
811
         }
812

813
         void reenable_echo() override {
814
            if(m_input_handle != INVALID_HANDLE_VALUE) {
815
               if(::SetConsoleMode(m_input_handle, m_console_state) == 0)
816
                  throw System_Error("Setting console mode failed", ::GetLastError());
817
               m_input_handle = INVALID_HANDLE_VALUE;
818
            }
819
         }
820

821
         ~Win32_Echo_Suppression() override {
822
            try {
823
               reenable_echo();
824
            } catch(...) {}
825
         }
826

827
         Win32_Echo_Suppression(const Win32_Echo_Suppression& other) = delete;
828
         Win32_Echo_Suppression(Win32_Echo_Suppression&& other) = delete;
829
         Win32_Echo_Suppression& operator=(const Win32_Echo_Suppression& other) = delete;
830
         Win32_Echo_Suppression& operator=(Win32_Echo_Suppression&& other) = delete;
831

832
      private:
833
         HANDLE m_input_handle;
834
         DWORD m_console_state;
835
   };
836

837
   return std::make_unique<Win32_Echo_Suppression>();
838

839
#else
840

841
   // Not supported on this platform, return null
842
   return nullptr;
843
#endif
844
}
845

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