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

randombit / botan / 5123321399

30 May 2023 04:06PM UTC coverage: 92.213% (+0.004%) from 92.209%
5123321399

Pull #3558

github

web-flow
Merge dd72f7389 into 057bcbc35
Pull Request #3558: Add braces around all if/else statements

75602 of 81986 relevant lines covered (92.21%)

11859779.3 hits per line

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

67.48
/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
   #if !defined(PR_SET_VMA)
74
      #define PR_SET_VMA 0x53564d41
75
      #define PR_SET_VMA_ANON_NAME 0
76
   #endif
77
#endif
78

79
namespace Botan {
80

81
// Not defined in OS namespace for historical reasons
82
void secure_scrub_memory(void* ptr, size_t n) {
228,547,144✔
83
#if defined(BOTAN_TARGET_OS_HAS_RTLSECUREZEROMEMORY)
84
   ::RtlSecureZeroMemory(ptr, n);
85

86
#elif defined(BOTAN_TARGET_OS_HAS_EXPLICIT_BZERO)
87
   ::explicit_bzero(ptr, n);
228,547,144✔
88

89
#elif defined(BOTAN_TARGET_OS_HAS_EXPLICIT_MEMSET)
90
   (void)::explicit_memset(ptr, 0, n);
91

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

104
   volatile uint8_t* p = reinterpret_cast<volatile uint8_t*>(ptr);
105

106
   for(size_t i = 0; i != n; ++i)
107
      p[i] = 0;
108
#endif
109
}
228,547,144✔
110

111
uint32_t OS::get_process_id() {
230,989✔
112
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
113
   return ::getpid();
230,989✔
114
#elif defined(BOTAN_TARGET_OS_HAS_WIN32)
115
   return ::GetCurrentProcessId();
116
#elif defined(BOTAN_TARGET_OS_IS_LLVM) || defined(BOTAN_TARGET_OS_IS_NONE)
117
   return 0;  // truly no meaningful value
118
#else
119
   #error "Missing get_process_id"
120
#endif
121
}
122

123
unsigned long OS::get_auxval(unsigned long id) {
22,183✔
124
#if defined(BOTAN_TARGET_OS_HAS_GETAUXVAL)
125
   return ::getauxval(id);
×
126
#elif defined(BOTAN_TARGET_OS_IS_ANDROID) && defined(BOTAN_TARGET_ARCH_IS_ARM32)
127

128
   if(id == 0)
129
      return 0;
130

131
   char** p = environ;
132

133
   while(*p++ != nullptr)
134
      ;
135

136
   Elf32_auxv_t* e = reinterpret_cast<Elf32_auxv_t*>(p);
137

138
   while(e != nullptr) {
139
      if(e->a_type == id)
140
         return e->a_un.a_val;
141
      e++;
142
   }
143

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

155
   return 0;
156
#else
157
   BOTAN_UNUSED(id);
158
   return 0;
159
#endif
160
}
161

162
bool OS::running_in_privileged_state() {
22,183✔
163
#if defined(AT_SECURE)
164
   return OS::get_auxval(AT_SECURE) != 0;
×
165
#elif defined(BOTAN_TARGET_OS_HAS_POSIX1)
166
   return (::getuid() != ::geteuid()) || (::getgid() != ::getegid());
167
#else
168
   return false;
169
#endif
170
}
171

172
uint64_t OS::get_cpu_cycle_counter() {
3,222,794✔
173
   uint64_t rtc = 0;
3,222,794✔
174

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

180
#elif defined(BOTAN_USE_GCC_INLINE_ASM)
181

182
   #if defined(BOTAN_TARGET_CPU_IS_X86_FAMILY)
183

184
   if(CPUID::has_rdtsc()) {
3,222,794✔
185
      uint32_t rtc_low = 0, rtc_high = 0;
3,222,794✔
186
      asm volatile("rdtsc" : "=d"(rtc_high), "=a"(rtc_low));
3,222,794✔
187
      rtc = (static_cast<uint64_t>(rtc_high) << 32) | rtc_low;
3,222,794✔
188
   }
189

190
   #elif defined(BOTAN_TARGET_ARCH_IS_PPC64)
191

192
   for(;;) {
193
      uint32_t rtc_low = 0, rtc_high = 0, rtc_high2 = 0;
194
      asm volatile("mftbu %0" : "=r"(rtc_high));
195
      asm volatile("mftb %0" : "=r"(rtc_low));
196
      asm volatile("mftbu %0" : "=r"(rtc_high2));
197

198
      if(rtc_high == rtc_high2) {
199
         rtc = (static_cast<uint64_t>(rtc_high) << 32) | rtc_low;
200
         break;
201
      }
202
   }
203

204
   #elif defined(BOTAN_TARGET_ARCH_IS_ALPHA)
205
   asm volatile("rpcc %0" : "=r"(rtc));
206

207
      // OpenBSD does not trap access to the %tick register
208
   #elif defined(BOTAN_TARGET_ARCH_IS_SPARC64) && !defined(BOTAN_TARGET_OS_IS_OPENBSD)
209
   asm volatile("rd %%tick, %0" : "=r"(rtc));
210

211
   #elif defined(BOTAN_TARGET_ARCH_IS_IA64)
212
   asm volatile("mov %0=ar.itc" : "=r"(rtc));
213

214
   #elif defined(BOTAN_TARGET_ARCH_IS_S390X)
215
   asm volatile("stck 0(%0)" : : "a"(&rtc) : "memory", "cc");
216

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

220
   #else
221
      //#warning "OS::get_cpu_cycle_counter not implemented"
222
   #endif
223

224
#endif
225

226
   return rtc;
3,222,794✔
227
}
228

229
size_t OS::get_cpu_available() {
751✔
230
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
231

232
   #if defined(_SC_NPROCESSORS_ONLN)
233
   const long cpu_online = ::sysconf(_SC_NPROCESSORS_ONLN);
751✔
234
   if(cpu_online > 0) {
751✔
235
      return static_cast<size_t>(cpu_online);
751✔
236
   }
237
   #endif
238

239
   #if defined(_SC_NPROCESSORS_CONF)
240
   const long cpu_conf = ::sysconf(_SC_NPROCESSORS_CONF);
×
241
   if(cpu_conf > 0) {
×
242
      return static_cast<size_t>(cpu_conf);
×
243
   }
244
   #endif
245

246
#endif
247

248
#if defined(BOTAN_TARGET_OS_HAS_THREADS)
249
   // hardware_concurrency is allowed to return 0 if the value is not
250
   // well defined or not computable.
251
   const size_t hw_concur = std::thread::hardware_concurrency();
×
252

253
   if(hw_concur > 0) {
×
254
      return hw_concur;
255
   }
256
#endif
257

258
   return 1;
259
}
260

261
uint64_t OS::get_high_resolution_clock() {
4,496✔
262
   if(uint64_t cpu_clock = OS::get_cpu_cycle_counter()) {
4,496✔
263
      return cpu_clock;
264
   }
265

266
#if defined(BOTAN_TARGET_OS_IS_EMSCRIPTEN)
267
   return emscripten_get_now();
268
#endif
269

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

277
#if defined(BOTAN_TARGET_OS_HAS_CLOCK_GETTIME)
278

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

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

306
   // Plain C++11 fallback
307
   auto now = std::chrono::high_resolution_clock::now().time_since_epoch();
×
308
   return std::chrono::duration_cast<std::chrono::nanoseconds>(now).count();
×
309
}
310

311
uint64_t OS::get_system_timestamp_ns() {
3,219,347✔
312
#if defined(BOTAN_TARGET_OS_HAS_CLOCK_GETTIME)
313
   struct timespec ts;
3,219,347✔
314
   if(::clock_gettime(CLOCK_REALTIME, &ts) == 0) {
3,219,347✔
315
      return (static_cast<uint64_t>(ts.tv_sec) * 1000000000) + static_cast<uint64_t>(ts.tv_nsec);
3,219,347✔
316
   }
317
#endif
318

319
   auto now = std::chrono::system_clock::now().time_since_epoch();
×
320
   return std::chrono::duration_cast<std::chrono::nanoseconds>(now).count();
×
321
}
322

323
size_t OS::system_page_size() {
575,061✔
324
   const size_t default_page_size = 4096;
575,061✔
325

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

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

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

362
   if(mlock_requested > 0) {
8,583✔
363
      struct ::rlimit limits;
8,583✔
364

365
      ::getrlimit(RLIMIT_MEMLOCK, &limits);
8,583✔
366

367
      if(limits.rlim_cur < limits.rlim_max) {
8,583✔
368
         limits.rlim_cur = limits.rlim_max;
×
369
         ::setrlimit(RLIMIT_MEMLOCK, &limits);
×
370
         ::getrlimit(RLIMIT_MEMLOCK, &limits);
×
371
      }
372

373
      return std::min<size_t>(limits.rlim_cur, mlock_requested * 1024);
8,583✔
374
   }
375

376
#elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
377
   const size_t mlock_requested =
378
      std::min<size_t>(read_env_variable_sz("BOTAN_MLOCK_POOL_SIZE", max_locked_kb), max_locked_kb);
379

380
   SIZE_T working_min = 0, working_max = 0;
381
   if(!::GetProcessWorkingSetSize(::GetCurrentProcess(), &working_min, &working_max)) {
382
      return 0;
383
   }
384

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

401
   return 0;
402
}
403

404
bool OS::read_env_variable(std::string& value_out, std::string_view name_view) {
22,183✔
405
   value_out = "";
22,183✔
406

407
   if(running_in_privileged_state()) {
22,183✔
408
      return false;
409
   }
410

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

427
   return false;
428
}
22,183✔
429

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

440
   return def;
441
}
8,583✔
442

443
#if defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
444

445
namespace {
446

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

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

466
}  // namespace
467

468
#endif
469

470
std::vector<void*> OS::allocate_locked_pages(size_t count) {
8,583✔
471
   std::vector<void*> result;
8,583✔
472

473
#if(defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)) || \
474
   defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
475

476
   result.reserve(count);
8,583✔
477

478
   const size_t page_size = OS::system_page_size();
8,583✔
479

480
   #if defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
481
   static const int locked_fd = get_locked_fd();
8,583✔
482
   #endif
483

484
   for(size_t i = 0; i != count; ++i) {
145,911✔
485
      void* ptr = nullptr;
137,328✔
486

487
   #if defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
488

489
      int mmap_flags = MAP_PRIVATE;
137,328✔
490

491
      #if defined(MAP_ANONYMOUS)
492
      mmap_flags |= MAP_ANONYMOUS;
137,328✔
493
      #elif defined(MAP_ANON)
494
      mmap_flags |= MAP_ANON;
495
      #endif
496

497
      #if defined(MAP_CONCEAL)
498
      mmap_flags |= MAP_CONCEAL;
499
      #elif defined(MAP_NOCORE)
500
      mmap_flags |= MAP_NOCORE;
501
      #endif
502

503
      int mmap_prot = PROT_READ | PROT_WRITE;
137,328✔
504

505
      #if defined(PROT_MAX)
506
      mmap_prot |= PROT_MAX(mmap_prot);
507
      #endif
508

509
      ptr = ::mmap(nullptr,
137,328✔
510
                   3 * page_size,
511
                   mmap_prot,
512
                   mmap_flags,
513
                   /*fd=*/locked_fd,
514
                   /*offset=*/0);
515

516
      if(ptr == MAP_FAILED) {
137,328✔
517
         continue;
×
518
      }
519

520
      // lock the data page
521
      if(::mlock(static_cast<uint8_t*>(ptr) + page_size, page_size) != 0) {
137,328✔
522
         ::munmap(ptr, 3 * page_size);
×
523
         continue;
×
524
      }
525

526
      #if defined(MADV_DONTDUMP)
527
      // we ignore errors here, as DONTDUMP is just a bonus
528
      ::madvise(static_cast<uint8_t*>(ptr) + page_size, page_size, MADV_DONTDUMP);
137,328✔
529
      #endif
530

531
   #elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
532
      ptr = ::VirtualAlloc(nullptr, 3 * page_size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
533

534
      if(ptr == nullptr)
535
         continue;
536

537
      if(::VirtualLock(static_cast<uint8_t*>(ptr) + page_size, page_size) == 0) {
538
         ::VirtualFree(ptr, 0, MEM_RELEASE);
539
         continue;
540
      }
541
   #endif
542

543
      std::memset(ptr, 0, 3 * page_size);  // zero data page and both guard pages
137,328✔
544

545
      // Attempts to name the data page
546
      page_named(ptr, 3 * page_size);
274,656✔
547
      // Make guard page preceeding the data page
548
      page_prohibit_access(static_cast<uint8_t*>(ptr));
137,328✔
549
      // Make guard page following the data page
550
      page_prohibit_access(static_cast<uint8_t*>(ptr) + 2 * page_size);
137,328✔
551

552
      result.push_back(static_cast<uint8_t*>(ptr) + page_size);
137,328✔
553
   }
554
#else
555
   BOTAN_UNUSED(count);
556
#endif
557

558
   return result;
8,583✔
559
}
×
560

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

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

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

592
   for(size_t i = 0; i != pages.size(); ++i) {
145,911✔
593
      void* ptr = pages[i];
137,328✔
594

595
      secure_scrub_memory(ptr, page_size);
137,328✔
596

597
      // ptr points to the data page, guard pages are before and after
598
      page_allow_access(static_cast<uint8_t*>(ptr) - page_size);
137,328✔
599
      page_allow_access(static_cast<uint8_t*>(ptr) + page_size);
137,328✔
600

601
#if defined(BOTAN_TARGET_OS_HAS_POSIX1) && defined(BOTAN_TARGET_OS_HAS_POSIX_MLOCK)
602
      ::munlock(ptr, page_size);
137,328✔
603
      ::munmap(static_cast<uint8_t*>(ptr) - page_size, 3 * page_size);
137,328✔
604
#elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK)
605
      ::VirtualUnlock(ptr, page_size);
606
      ::VirtualFree(static_cast<uint8_t*>(ptr) - page_size, 0, MEM_RELEASE);
607
#endif
608
   }
609
}
8,583✔
610

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

621
#if defined(BOTAN_TARGET_OS_HAS_POSIX1) && !defined(BOTAN_TARGET_OS_IS_EMSCRIPTEN)
622

623
namespace {
624

625
::sigjmp_buf g_sigill_jmp_buf;
626

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

629
}  // namespace
630

631
#endif
632

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

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

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

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

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

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

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

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

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

670
   return probe_result;
2✔
671
}
672

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

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

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

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

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

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

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

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

719
#elif defined(BOTAN_TARGET_OS_HAS_WIN32)
720

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

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

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

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

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

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

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

759
#else
760

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

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