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

randombit / botan / 5230455705

10 Jun 2023 02:30PM UTC coverage: 91.715% (-0.03%) from 91.746%
5230455705

push

github

randombit
Merge GH #3584 Change clang-format AllowShortFunctionsOnASingleLine config from All to Inline

77182 of 84154 relevant lines covered (91.72%)

11975295.43 hits per line

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

66.05
/src/lib/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

15
#include <algorithm>
16
#include <chrono>
17
#include <cstdlib>
18

19
#if defined(BOTAN_TARGET_OS_HAS_THREADS)
20
   #include <thread>
21
#endif
22

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

27
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
28
   #include <errno.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_IS_ANDROID) || \
45
   defined(BOTAN_TARGET_OS_HAS_ELF_AUX_INFO)
46
   #include <sys/auxv.h>
47
#endif
48

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

54
#if defined(BOTAN_TARGET_OS_HAS_WIN32)
55
   #define NOMINMAX 1
56
   #define _WINSOCKAPI_  // stop windows.h including winsock.h
57
   #include <windows.h>
58
#endif
59

60
#if defined(BOTAN_TARGET_OS_IS_ANDROID)
61
   #include <elf.h>
62
extern "C" char** environ;
63
#endif
64

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

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

75
namespace Botan {
76

77
// Not defined in OS namespace for historical reasons
78
void secure_scrub_memory(void* ptr, size_t n) {
238,249,826✔
79
#if defined(BOTAN_TARGET_OS_HAS_RTLSECUREZEROMEMORY)
80
   ::RtlSecureZeroMemory(ptr, n);
81

82
#elif defined(BOTAN_TARGET_OS_HAS_EXPLICIT_BZERO)
83
   ::explicit_bzero(ptr, n);
238,249,826✔
84

85
#elif defined(BOTAN_TARGET_OS_HAS_EXPLICIT_MEMSET)
86
   (void)::explicit_memset(ptr, 0, n);
87

88
#elif defined(BOTAN_USE_VOLATILE_MEMSET_FOR_ZERO) && (BOTAN_USE_VOLATILE_MEMSET_FOR_ZERO == 1)
89
   /*
90
   Call memset through a static volatile pointer, which the compiler
91
   should not elide. This construct should be safe in conforming
92
   compilers, but who knows. I did confirm that on x86-64 GCC 6.1 and
93
   Clang 3.8 both create code that saves the memset address in the
94
   data segment and unconditionally loads and jumps to that address.
95
   */
96
   static void* (*const volatile memset_ptr)(void*, int, size_t) = std::memset;
97
   (memset_ptr)(ptr, 0, n);
98
#else
99

100
   volatile uint8_t* p = reinterpret_cast<volatile uint8_t*>(ptr);
101

102
   for(size_t i = 0; i != n; ++i)
103
      p[i] = 0;
104
#endif
105
}
238,249,826✔
106

107
uint32_t OS::get_process_id() {
233,770✔
108
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
109
   return ::getpid();
233,770✔
110
#elif defined(BOTAN_TARGET_OS_HAS_WIN32)
111
   return ::GetCurrentProcessId();
112
#elif defined(BOTAN_TARGET_OS_IS_LLVM) || defined(BOTAN_TARGET_OS_IS_NONE)
113
   return 0;  // truly no meaningful value
114
#else
115
   #error "Missing get_process_id"
116
#endif
117
}
118

119
unsigned long OS::get_auxval(unsigned long id) {
22,201✔
120
#if defined(BOTAN_TARGET_OS_HAS_GETAUXVAL)
121
   return ::getauxval(id);
×
122
#elif defined(BOTAN_TARGET_OS_IS_ANDROID) && defined(BOTAN_TARGET_ARCH_IS_ARM32)
123

124
   if(id == 0)
125
      return 0;
126

127
   char** p = environ;
128

129
   while(*p++ != nullptr)
130
      ;
131

132
   Elf32_auxv_t* e = reinterpret_cast<Elf32_auxv_t*>(p);
133

134
   while(e != nullptr) {
135
      if(e->a_type == id)
136
         return e->a_un.a_val;
137
      e++;
138
   }
139

140
   return 0;
141
#elif defined(BOTAN_TARGET_OS_HAS_ELF_AUX_INFO)
142
   unsigned long auxinfo = 0;
143
   ::elf_aux_info(static_cast<int>(id), &auxinfo, sizeof(auxinfo));
144
   return auxinfo;
145
#elif defined(BOTAN_TARGET_OS_HAS_AUXINFO)
146
   for(const AuxInfo* auxinfo = static_cast<AuxInfo*>(::_dlauxinfo()); auxinfo != AT_NULL; ++auxinfo) {
147
      if(id == auxinfo->a_type)
148
         return auxinfo->a_v;
149
   }
150

151
   return 0;
152
#else
153
   BOTAN_UNUSED(id);
154
   return 0;
155
#endif
156
}
157

158
bool OS::running_in_privileged_state() {
22,201✔
159
#if defined(AT_SECURE)
160
   return OS::get_auxval(AT_SECURE) != 0;
×
161
#elif defined(BOTAN_TARGET_OS_HAS_POSIX1)
162
   return (::getuid() != ::geteuid()) || (::getgid() != ::getegid());
163
#else
164
   return false;
165
#endif
166
}
167

168
uint64_t OS::get_cpu_cycle_counter() {
3,234,989✔
169
   uint64_t rtc = 0;
3,234,989✔
170

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

176
#elif defined(BOTAN_USE_GCC_INLINE_ASM)
177

178
   #if defined(BOTAN_TARGET_CPU_IS_X86_FAMILY)
179

180
   if(CPUID::has_rdtsc()) {
3,234,989✔
181
      uint32_t rtc_low = 0, rtc_high = 0;
3,234,989✔
182
      asm volatile("rdtsc" : "=d"(rtc_high), "=a"(rtc_low));
3,234,989✔
183
      rtc = (static_cast<uint64_t>(rtc_high) << 32) | rtc_low;
3,234,989✔
184
   }
185

186
   #elif defined(BOTAN_TARGET_ARCH_IS_PPC64)
187

188
   for(;;) {
189
      uint32_t rtc_low = 0, rtc_high = 0, rtc_high2 = 0;
190
      asm volatile("mftbu %0" : "=r"(rtc_high));
191
      asm volatile("mftb %0" : "=r"(rtc_low));
192
      asm volatile("mftbu %0" : "=r"(rtc_high2));
193

194
      if(rtc_high == rtc_high2) {
195
         rtc = (static_cast<uint64_t>(rtc_high) << 32) | rtc_low;
196
         break;
197
      }
198
   }
199

200
   #elif defined(BOTAN_TARGET_ARCH_IS_ALPHA)
201
   asm volatile("rpcc %0" : "=r"(rtc));
202

203
      // OpenBSD does not trap access to the %tick register
204
   #elif defined(BOTAN_TARGET_ARCH_IS_SPARC64) && !defined(BOTAN_TARGET_OS_IS_OPENBSD)
205
   asm volatile("rd %%tick, %0" : "=r"(rtc));
206

207
   #elif defined(BOTAN_TARGET_ARCH_IS_IA64)
208
   asm volatile("mov %0=ar.itc" : "=r"(rtc));
209

210
   #elif defined(BOTAN_TARGET_ARCH_IS_S390X)
211
   asm volatile("stck 0(%0)" : : "a"(&rtc) : "memory", "cc");
212

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

216
   #else
217
      //#warning "OS::get_cpu_cycle_counter not implemented"
218
   #endif
219

220
#endif
221

222
   return rtc;
3,234,989✔
223
}
224

225
size_t OS::get_cpu_available() {
754✔
226
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
227

228
   #if defined(_SC_NPROCESSORS_ONLN)
229
   const long cpu_online = ::sysconf(_SC_NPROCESSORS_ONLN);
754✔
230
   if(cpu_online > 0) {
754✔
231
      return static_cast<size_t>(cpu_online);
754✔
232
   }
233
   #endif
234

235
   #if defined(_SC_NPROCESSORS_CONF)
236
   const long cpu_conf = ::sysconf(_SC_NPROCESSORS_CONF);
×
237
   if(cpu_conf > 0) {
×
238
      return static_cast<size_t>(cpu_conf);
×
239
   }
240
   #endif
241

242
#endif
243

244
#if defined(BOTAN_TARGET_OS_HAS_THREADS)
245
   // hardware_concurrency is allowed to return 0 if the value is not
246
   // well defined or not computable.
247
   const size_t hw_concur = std::thread::hardware_concurrency();
×
248

249
   if(hw_concur > 0) {
×
250
      return hw_concur;
251
   }
252
#endif
253

254
   return 1;
255
}
256

257
uint64_t OS::get_high_resolution_clock() {
4,498✔
258
   if(uint64_t cpu_clock = OS::get_cpu_cycle_counter()) {
4,498✔
259
      return cpu_clock;
260
   }
261

262
#if defined(BOTAN_TARGET_OS_IS_EMSCRIPTEN)
263
   return emscripten_get_now();
264
#endif
265

266
   /*
267
   If we got here either we either don't have an asm instruction
268
   above, or (for x86) RDTSC is not available at runtime. Try some
269
   clock_gettimes and return the first one that works, or otherwise
270
   fall back to std::chrono.
271
   */
272

273
#if defined(BOTAN_TARGET_OS_HAS_CLOCK_GETTIME)
274

275
   // The ordering here is somewhat arbitrary...
276
   const clockid_t clock_types[] = {
×
277
   #if defined(CLOCK_MONOTONIC_HR)
278
      CLOCK_MONOTONIC_HR,
279
   #endif
280
   #if defined(CLOCK_MONOTONIC_RAW)
281
      CLOCK_MONOTONIC_RAW,
282
   #endif
283
   #if defined(CLOCK_MONOTONIC)
284
      CLOCK_MONOTONIC,
285
   #endif
286
   #if defined(CLOCK_PROCESS_CPUTIME_ID)
287
      CLOCK_PROCESS_CPUTIME_ID,
288
   #endif
289
   #if defined(CLOCK_THREAD_CPUTIME_ID)
290
      CLOCK_THREAD_CPUTIME_ID,
291
   #endif
292
   };
293

294
   for(clockid_t clock : clock_types) {
×
295
      struct timespec ts;
×
296
      if(::clock_gettime(clock, &ts) == 0) {
×
297
         return (static_cast<uint64_t>(ts.tv_sec) * 1000000000) + static_cast<uint64_t>(ts.tv_nsec);
×
298
      }
299
   }
300
#endif
301

302
   // Plain C++11 fallback
303
   auto now = std::chrono::high_resolution_clock::now().time_since_epoch();
×
304
   return std::chrono::duration_cast<std::chrono::nanoseconds>(now).count();
×
305
}
306

307
uint64_t OS::get_system_timestamp_ns() {
3,231,540✔
308
#if defined(BOTAN_TARGET_OS_HAS_CLOCK_GETTIME)
309
   struct timespec ts;
3,231,540✔
310
   if(::clock_gettime(CLOCK_REALTIME, &ts) == 0) {
3,231,540✔
311
      return (static_cast<uint64_t>(ts.tv_sec) * 1000000000) + static_cast<uint64_t>(ts.tv_nsec);
3,231,540✔
312
   }
313
#endif
314

315
   auto now = std::chrono::system_clock::now().time_since_epoch();
×
316
   return std::chrono::duration_cast<std::chrono::nanoseconds>(now).count();
×
317
}
318

319
size_t OS::system_page_size() {
575,530✔
320
   const size_t default_page_size = 4096;
575,530✔
321

322
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
323
   long p = ::sysconf(_SC_PAGESIZE);
8,590✔
324
   if(p > 1) {
575,530✔
325
      return static_cast<size_t>(p);
575,530✔
326
   } else {
327
      return default_page_size;
328
   }
329
#elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
330
   BOTAN_UNUSED(default_page_size);
331
   SYSTEM_INFO sys_info;
332
   ::GetSystemInfo(&sys_info);
333
   return sys_info.dwPageSize;
334
#else
335
   return default_page_size;
336
#endif
337
}
338

339
size_t OS::get_memory_locking_limit() {
8,590✔
340
   /*
341
   * Linux defaults to only 64 KiB of mlockable memory per process (too small)
342
   * but BSDs offer a small fraction of total RAM (more than we need). Bound the
343
   * total mlock size to 512 KiB which is enough to run the entire test suite
344
   * without spilling to non-mlock memory (and thus presumably also enough for
345
   * many useful programs), but small enough that we should not cause problems
346
   * even if many processes are mlocking on the same machine.
347
   */
348
   const size_t max_locked_kb = 512;
8,590✔
349

350
   /*
351
   * If RLIMIT_MEMLOCK is not defined, likely the OS does not support
352
   * unprivileged mlock calls.
353
   */
354
#if defined(RLIMIT_MEMLOCK) && defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
355
   const size_t mlock_requested =
8,590✔
356
      std::min<size_t>(read_env_variable_sz("BOTAN_MLOCK_POOL_SIZE", max_locked_kb), max_locked_kb);
8,590✔
357

358
   if(mlock_requested > 0) {
8,590✔
359
      struct ::rlimit limits;
8,590✔
360

361
      ::getrlimit(RLIMIT_MEMLOCK, &limits);
8,590✔
362

363
      if(limits.rlim_cur < limits.rlim_max) {
8,590✔
364
         limits.rlim_cur = limits.rlim_max;
×
365
         ::setrlimit(RLIMIT_MEMLOCK, &limits);
×
366
         ::getrlimit(RLIMIT_MEMLOCK, &limits);
×
367
      }
368

369
      return std::min<size_t>(limits.rlim_cur, mlock_requested * 1024);
8,590✔
370
   }
371

372
#elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
373
   const size_t mlock_requested =
374
      std::min<size_t>(read_env_variable_sz("BOTAN_MLOCK_POOL_SIZE", max_locked_kb), max_locked_kb);
375

376
   SIZE_T working_min = 0, working_max = 0;
377
   if(!::GetProcessWorkingSetSize(::GetCurrentProcess(), &working_min, &working_max)) {
378
      return 0;
379
   }
380

381
   // According to Microsoft MSDN:
382
   // 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
383
   // In the book "Windows Internals Part 2": the maximum lockable pages are minimum working set size - 8 pages
384
   // But the information in the book seems to be inaccurate/outdated
385
   // I've tested this on Windows 8.1 x64, Windows 10 x64 and Windows 7 x86
386
   // On all three OS the value is 11 instead of 8
387
   const size_t overhead = OS::system_page_size() * 11;
388
   if(working_min > overhead) {
389
      const size_t lockable_bytes = working_min - overhead;
390
      return std::min<size_t>(lockable_bytes, mlock_requested * 1024);
391
   }
392
#else
393
   // Not supported on this platform
394
   BOTAN_UNUSED(max_locked_kb);
395
#endif
396

397
   return 0;
398
}
399

400
bool OS::read_env_variable(std::string& value_out, std::string_view name_view) {
22,201✔
401
   value_out = "";
22,201✔
402

403
   if(running_in_privileged_state()) {
22,201✔
404
      return false;
405
   }
406

407
#if defined(BOTAN_TARGET_OS_HAS_WIN32) && defined(BOTAN_BUILD_COMPILER_IS_MSVC)
408
   const std::string name(name_view);
409
   char val[128] = {0};
410
   size_t req_size = 0;
411
   if(getenv_s(&req_size, val, sizeof(val), name.c_str()) == 0) {
412
      value_out = std::string(val, req_size);
413
      return true;
414
   }
415
#else
416
   const std::string name(name_view);
22,201✔
417
   if(const char* val = std::getenv(name.c_str())) {
22,201✔
418
      value_out = val;
22,201✔
419
      return true;
420
   }
421
#endif
422

423
   return false;
424
}
22,201✔
425

426
size_t OS::read_env_variable_sz(std::string_view name, size_t def) {
8,590✔
427
   std::string value;
8,590✔
428
   if(read_env_variable(value, name) && !value.empty()) {
8,590✔
429
      try {
×
430
         const size_t val = std::stoul(value, nullptr);
8,590✔
431
         return val;
432
      } catch(std::exception&) { /* ignore it */
×
433
      }
×
434
   }
435

436
   return def;
437
}
8,590✔
438

439
#if defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
440

441
namespace {
442

443
int get_locked_fd() {
444
   #if defined(BOTAN_TARGET_OS_IS_IOS) || defined(BOTAN_TARGET_OS_IS_MACOS)
445
   // On Darwin, tagging anonymous pages allows vmmap to track these.
446
   // Allowed from 240 to 255 for userland applications
447
   static constexpr int default_locked_fd = 255;
448
   int locked_fd = default_locked_fd;
449

450
   if(size_t locked_fdl = OS::read_env_variable_sz("BOTAN_LOCKED_FD", default_locked_fd)) {
451
      if(locked_fdl < 240 || locked_fdl > 255) {
452
         locked_fdl = default_locked_fd;
453
      }
454
      locked_fd = static_cast<int>(locked_fdl);
455
   }
456
   return VM_MAKE_TAG(locked_fd);
457
   #else
458
   return -1;
459
   #endif
460
}
461

462
}  // namespace
463

464
#endif
465

466
std::vector<void*> OS::allocate_locked_pages(size_t count) {
8,590✔
467
   std::vector<void*> result;
8,590✔
468

469
#if(defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)) || \
470
   defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
471

472
   result.reserve(count);
8,590✔
473

474
   const size_t page_size = OS::system_page_size();
8,590✔
475

476
   #if defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
477
   static const int locked_fd = get_locked_fd();
8,590✔
478
   #endif
479

480
   for(size_t i = 0; i != count; ++i) {
146,030✔
481
      void* ptr = nullptr;
137,440✔
482

483
   #if defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
484

485
      int mmap_flags = MAP_PRIVATE;
137,440✔
486

487
      #if defined(MAP_ANONYMOUS)
488
      mmap_flags |= MAP_ANONYMOUS;
137,440✔
489
      #elif defined(MAP_ANON)
490
      mmap_flags |= MAP_ANON;
491
      #endif
492

493
      #if defined(MAP_CONCEAL)
494
      mmap_flags |= MAP_CONCEAL;
495
      #elif defined(MAP_NOCORE)
496
      mmap_flags |= MAP_NOCORE;
497
      #endif
498

499
      int mmap_prot = PROT_READ | PROT_WRITE;
137,440✔
500

501
      #if defined(PROT_MAX)
502
      mmap_prot |= PROT_MAX(mmap_prot);
503
      #endif
504

505
      ptr = ::mmap(nullptr,
137,440✔
506
                   3 * page_size,
507
                   mmap_prot,
508
                   mmap_flags,
509
                   /*fd=*/locked_fd,
510
                   /*offset=*/0);
511

512
      if(ptr == MAP_FAILED) {
137,440✔
513
         continue;
×
514
      }
515

516
      // lock the data page
517
      if(::mlock(static_cast<uint8_t*>(ptr) + page_size, page_size) != 0) {
137,440✔
518
         ::munmap(ptr, 3 * page_size);
×
519
         continue;
×
520
      }
521

522
      #if defined(MADV_DONTDUMP)
523
      // we ignore errors here, as DONTDUMP is just a bonus
524
      ::madvise(static_cast<uint8_t*>(ptr) + page_size, page_size, MADV_DONTDUMP);
137,440✔
525
      #endif
526

527
   #elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
528
      ptr = ::VirtualAlloc(nullptr, 3 * page_size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
529

530
      if(ptr == nullptr)
531
         continue;
532

533
      if(::VirtualLock(static_cast<uint8_t*>(ptr) + page_size, page_size) == 0) {
534
         ::VirtualFree(ptr, 0, MEM_RELEASE);
535
         continue;
536
      }
537
   #endif
538

539
      std::memset(ptr, 0, 3 * page_size);  // zero data page and both guard pages
137,440✔
540

541
      // Attempts to name the data page
542
      page_named(ptr, 3 * page_size);
137,440✔
543
      // Make guard page preceeding the data page
544
      page_prohibit_access(static_cast<uint8_t*>(ptr));
137,440✔
545
      // Make guard page following the data page
546
      page_prohibit_access(static_cast<uint8_t*>(ptr) + 2 * page_size);
137,440✔
547

548
      result.push_back(static_cast<uint8_t*>(ptr) + page_size);
137,440✔
549
   }
550
#else
551
   BOTAN_UNUSED(count);
552
#endif
553

554
   return result;
8,590✔
555
}
×
556

557
void OS::page_allow_access(void* page) {
274,880✔
558
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
559
   const size_t page_size = OS::system_page_size();
274,880✔
560
   ::mprotect(page, page_size, PROT_READ | PROT_WRITE);
274,880✔
561
#elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
562
   const size_t page_size = OS::system_page_size();
563
   DWORD old_perms = 0;
564
   ::VirtualProtect(page, page_size, PAGE_READWRITE, &old_perms);
565
   BOTAN_UNUSED(old_perms);
566
#else
567
   BOTAN_UNUSED(page);
568
#endif
569
}
274,880✔
570

571
void OS::page_prohibit_access(void* page) {
274,880✔
572
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
573
   const size_t page_size = OS::system_page_size();
274,880✔
574
   ::mprotect(page, page_size, PROT_NONE);
274,880✔
575
#elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
576
   const size_t page_size = OS::system_page_size();
577
   DWORD old_perms = 0;
578
   ::VirtualProtect(page, page_size, PAGE_NOACCESS, &old_perms);
579
   BOTAN_UNUSED(old_perms);
580
#else
581
   BOTAN_UNUSED(page);
582
#endif
583
}
274,880✔
584

585
void OS::free_locked_pages(const std::vector<void*>& pages) {
8,590✔
586
   const size_t page_size = OS::system_page_size();
8,590✔
587

588
   for(size_t i = 0; i != pages.size(); ++i) {
146,030✔
589
      void* ptr = pages[i];
137,440✔
590

591
      secure_scrub_memory(ptr, page_size);
137,440✔
592

593
      // ptr points to the data page, guard pages are before and after
594
      page_allow_access(static_cast<uint8_t*>(ptr) - page_size);
137,440✔
595
      page_allow_access(static_cast<uint8_t*>(ptr) + page_size);
137,440✔
596

597
#if defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
598
      ::munlock(ptr, page_size);
137,440✔
599
      ::munmap(static_cast<uint8_t*>(ptr) - page_size, 3 * page_size);
137,440✔
600
#elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
601
      ::VirtualUnlock(ptr, page_size);
602
      ::VirtualFree(static_cast<uint8_t*>(ptr) - page_size, 0, MEM_RELEASE);
603
#endif
604
   }
605
}
8,590✔
606

607
void OS::page_named(void* page, size_t size) {
×
608
#if defined(BOTAN_TARGET_OS_HAS_PRCTL) && defined(PR_SET_VMA) && defined(PR_SET_VMA_ANON_NAME)
609
   static constexpr char name[] = "Botan mlock pool";
610
   int r = prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME, reinterpret_cast<uintptr_t>(page), size, name);
611
   BOTAN_UNUSED(r);
612
#else
613
   BOTAN_UNUSED(page, size);
×
614
#endif
615
}
×
616

617
#if defined(BOTAN_TARGET_OS_HAS_POSIX1) && !defined(BOTAN_TARGET_OS_IS_EMSCRIPTEN)
618

619
namespace {
620

621
// NOLINTNEXTLINE(*-avoid-non-const-global-variables)
622
::sigjmp_buf g_sigill_jmp_buf;
623

624
void botan_sigill_handler(int /*unused*/) {
1✔
625
   siglongjmp(g_sigill_jmp_buf, /*non-zero return value*/ 1);
1✔
626
}
627

628
}  // namespace
629

630
#endif
631

632
int OS::run_cpu_instruction_probe(const std::function<int()>& probe_fn) {
2✔
633
   volatile int probe_result = -3;
2✔
634

635
#if defined(BOTAN_TARGET_OS_HAS_POSIX1) && !defined(BOTAN_TARGET_OS_IS_EMSCRIPTEN)
636
   struct sigaction old_sigaction;
2✔
637
   struct sigaction sigaction;
2✔
638

639
   sigaction.sa_handler = botan_sigill_handler;
2✔
640
   sigemptyset(&sigaction.sa_mask);
2✔
641
   sigaction.sa_flags = 0;
2✔
642

643
   int rc = ::sigaction(SIGILL, &sigaction, &old_sigaction);
2✔
644

645
   if(rc != 0) {
2✔
646
      throw System_Error("run_cpu_instruction_probe sigaction failed", errno);
×
647
   }
648

649
   rc = sigsetjmp(g_sigill_jmp_buf, /*save sigs*/ 1);
3✔
650

651
   if(rc == 0) {
3✔
652
      // first call to sigsetjmp
653
      probe_result = probe_fn();
3✔
654
   } else if(rc == 1) {
1✔
655
      // non-local return from siglongjmp in signal handler: return error
656
      probe_result = -1;
1✔
657
   }
658

659
   // Restore old SIGILL handler, if any
660
   rc = ::sigaction(SIGILL, &old_sigaction, nullptr);
2✔
661
   if(rc != 0) {
2✔
662
      throw System_Error("run_cpu_instruction_probe sigaction restore failed", errno);
×
663
   }
664

665
#else
666
   BOTAN_UNUSED(probe_fn);
667
#endif
668

669
   return probe_result;
2✔
670
}
671

672
std::unique_ptr<OS::Echo_Suppression> OS::suppress_echo_on_terminal() {
×
673
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
674
   class POSIX_Echo_Suppression : public Echo_Suppression {
×
675
      public:
676
         POSIX_Echo_Suppression() {
×
677
            m_stdin_fd = fileno(stdin);
×
678
            if(::tcgetattr(m_stdin_fd, &m_old_termios) != 0) {
×
679
               throw System_Error("Getting terminal status failed", errno);
×
680
            }
681

682
            struct termios noecho_flags = m_old_termios;
×
683
            noecho_flags.c_lflag &= ~ECHO;
×
684
            noecho_flags.c_lflag |= ECHONL;
×
685

686
            if(::tcsetattr(m_stdin_fd, TCSANOW, &noecho_flags) != 0) {
×
687
               throw System_Error("Clearing terminal echo bit failed", errno);
×
688
            }
689
         }
×
690

691
         void reenable_echo() override {
×
692
            if(m_stdin_fd > 0) {
×
693
               if(::tcsetattr(m_stdin_fd, TCSANOW, &m_old_termios) != 0) {
×
694
                  throw System_Error("Restoring terminal echo bit failed", errno);
×
695
               }
696
               m_stdin_fd = -1;
×
697
            }
698
         }
×
699

700
         ~POSIX_Echo_Suppression() override {
×
701
            try {
×
702
               reenable_echo();
×
703
            } catch(...) {}
×
704
         }
×
705

706
         POSIX_Echo_Suppression(const POSIX_Echo_Suppression& other) = delete;
707
         POSIX_Echo_Suppression(POSIX_Echo_Suppression&& other) = delete;
708
         POSIX_Echo_Suppression& operator=(const POSIX_Echo_Suppression& other) = delete;
709
         POSIX_Echo_Suppression& operator=(POSIX_Echo_Suppression&& other) = delete;
710

711
      private:
712
         int m_stdin_fd;
713
         struct termios m_old_termios;
714
   };
715

716
   return std::make_unique<POSIX_Echo_Suppression>();
×
717

718
#elif defined(BOTAN_TARGET_OS_HAS_WIN32)
719

720
   class Win32_Echo_Suppression : public Echo_Suppression {
721
      public:
722
         Win32_Echo_Suppression() {
723
            m_input_handle = ::GetStdHandle(STD_INPUT_HANDLE);
724
            if(::GetConsoleMode(m_input_handle, &m_console_state) == 0)
725
               throw System_Error("Getting console mode failed", ::GetLastError());
726

727
            DWORD new_mode = ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT;
728
            if(::SetConsoleMode(m_input_handle, new_mode) == 0)
729
               throw System_Error("Setting console mode failed", ::GetLastError());
730
         }
731

732
         void reenable_echo() override {
733
            if(m_input_handle != INVALID_HANDLE_VALUE) {
734
               if(::SetConsoleMode(m_input_handle, m_console_state) == 0)
735
                  throw System_Error("Setting console mode failed", ::GetLastError());
736
               m_input_handle = INVALID_HANDLE_VALUE;
737
            }
738
         }
739

740
         ~Win32_Echo_Suppression() override {
741
            try {
742
               reenable_echo();
743
            } catch(...) {}
744
         }
745

746
         Win32_Echo_Suppression(const Win32_Echo_Suppression& other) = delete;
747
         Win32_Echo_Suppression(Win32_Echo_Suppression&& other) = delete;
748
         Win32_Echo_Suppression& operator=(const Win32_Echo_Suppression& other) = delete;
749
         Win32_Echo_Suppression& operator=(Win32_Echo_Suppression&& other) = delete;
750

751
      private:
752
         HANDLE m_input_handle;
753
         DWORD m_console_state;
754
   };
755

756
   return std::make_unique<Win32_Echo_Suppression>();
757

758
#else
759

760
   // Not supported on this platform, return null
761
   return nullptr;
762
#endif
763
}
764

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

© 2025 Coveralls, Inc