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

randombit / botan / 6362617071

30 Sep 2023 11:54AM UTC coverage: 91.751% (-0.01%) from 91.763%
6362617071

push

github

web-flow
Merge pull request #3628 from randombit/thread_pool_debug

thead pool debugging support proposal using native capabilities if po…

79497 of 86644 relevant lines covered (91.75%)

8513342.06 hits per line

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

66.67
/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_EXPLICIT_BZERO)
20
   #include <string.h>
21
#endif
22

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

37
#if defined(BOTAN_TARGET_OS_IS_EMSCRIPTEN)
38
   #include <emscripten/emscripten.h>
39
#endif
40

41
#if defined(BOTAN_TARGET_OS_HAS_GETAUXVAL) || defined(BOTAN_TARGET_OS_IS_ANDROID) || \
42
   defined(BOTAN_TARGET_OS_HAS_ELF_AUX_INFO)
43
   #include <sys/auxv.h>
44
#endif
45

46
#if defined(BOTAN_TARGET_OS_HAS_AUXINFO)
47
   #include <dlfcn.h>
48
   #include <elf.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
#endif
56

57
#if defined(BOTAN_TARGET_OS_IS_ANDROID)
58
   #include <elf.h>
59
extern "C" char** environ;
60
#endif
61

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

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

72
#if defined(BOTAN_TARGET_IS_FREEBSD) || defined(BOTAN_TARGET_IS_OPENBSD)
73
   #include <pthread_np.h>
74
#endif
75

76
namespace Botan {
77

78
// Not defined in OS namespace for historical reasons
79
void secure_scrub_memory(void* ptr, size_t n) {
226,623,710✔
80
#if defined(BOTAN_TARGET_OS_HAS_RTLSECUREZEROMEMORY)
81
   ::RtlSecureZeroMemory(ptr, n);
82

83
#elif defined(BOTAN_TARGET_OS_HAS_EXPLICIT_BZERO)
84
   ::explicit_bzero(ptr, n);
226,623,710✔
85

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

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

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

103
   for(size_t i = 0; i != n; ++i)
104
      p[i] = 0;
105
#endif
106
}
226,623,710✔
107

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

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

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

128
   char** p = environ;
129

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

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

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

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

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

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

169
uint64_t OS::get_cpu_cycle_counter() {
3,184,671✔
170
   uint64_t rtc = 0;
3,184,671✔
171

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

177
#elif defined(BOTAN_USE_GCC_INLINE_ASM)
178

179
   #if defined(BOTAN_TARGET_CPU_IS_X86_FAMILY)
180

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

187
   #elif defined(BOTAN_TARGET_ARCH_IS_PPC64)
188

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

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

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

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

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

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

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

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

221
#endif
222

223
   return rtc;
3,184,671✔
224
}
225

226
size_t OS::get_cpu_available() {
756✔
227
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
228

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

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

243
#endif
244

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

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

255
   return 1;
256
}
257

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

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

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

274
#if defined(BOTAN_TARGET_OS_HAS_CLOCK_GETTIME)
275

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

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

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

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

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

320
size_t OS::system_page_size() {
4,429,000✔
321
   const size_t default_page_size = 4096;
4,429,000✔
322

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

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

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

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

362
      ::getrlimit(RLIMIT_MEMLOCK, &limits);
8,600✔
363

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

370
      return std::min<size_t>(limits.rlim_cur, mlock_requested * 1024);
17,200✔
371
   }
372

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

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

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

398
   return 0;
399
}
400

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

404
   if(running_in_privileged_state()) {
22,223✔
405
      return false;
406
   }
407

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

424
   return false;
425
}
22,223✔
426

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

437
   return def;
438
}
8,600✔
439

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

442
namespace {
443

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

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

463
}  // namespace
464

465
#endif
466

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

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

473
   result.reserve(count);
8,600✔
474

475
   const size_t page_size = OS::system_page_size();
8,600✔
476

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

481
   for(size_t i = 0; i != count; ++i) {
1,109,400✔
482
      void* ptr = nullptr;
1,100,800✔
483

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

486
      int mmap_flags = MAP_PRIVATE;
1,100,800✔
487

488
      #if defined(MAP_ANONYMOUS)
489
      mmap_flags |= MAP_ANONYMOUS;
1,100,800✔
490
      #elif defined(MAP_ANON)
491
      mmap_flags |= MAP_ANON;
492
      #endif
493

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

500
      int mmap_prot = PROT_READ | PROT_WRITE;
1,100,800✔
501

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

506
      ptr = ::mmap(nullptr,
1,100,800✔
507
                   3 * page_size,
508
                   mmap_prot,
509
                   mmap_flags,
510
                   /*fd=*/locked_fd,
511
                   /*offset=*/0);
512

513
      if(ptr == MAP_FAILED) {
1,100,800✔
514
         continue;
×
515
      }
516

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

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

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

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

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

540
      std::memset(ptr, 0, 3 * page_size);  // zero data page and both guard pages
1,100,800✔
541

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

549
      result.push_back(static_cast<uint8_t*>(ptr) + page_size);
1,100,800✔
550
   }
551
#else
552
   BOTAN_UNUSED(count);
553
#endif
554

555
   return result;
8,600✔
556
}
×
557

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

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

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

589
   for(size_t i = 0; i != pages.size(); ++i) {
1,109,400✔
590
      void* ptr = pages[i];
1,100,800✔
591

592
      secure_scrub_memory(ptr, page_size);
1,100,800✔
593

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

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

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

618
#if defined(BOTAN_TARGET_OS_HAS_THREADS)
619
void OS::set_thread_name(std::thread& thread, const std::string& name) {
1,522✔
620
   #if defined(BOTAN_TARGET_OS_IS_LINUX) || defined(BOTAN_TARGET_OS_IS_FREEBSD)
621
   static_cast<void>(pthread_setname_np(thread.native_handle(), name.c_str()));
1,522✔
622
   #elif defined(BOTAN_TARGET_OS_IS_OPENBSD)
623
   static_cast<void>(pthread_set_name_np(thread.native_handle(), name.c_str()));
624
   #elif defined(BOTAN_TARGET_OS_IS_NETBSD)
625
   static_cast<void>(pthread_set_name_np(thread.native_handle(), "%s", const_cast<char*>(name.c_str())));
626
   #elif defined(BOTAN_TARGET_OS_HAS_WIN32) && defined(BOTAN_BUILD_COMPILER_IS_MSVC)
627
   // Using SetThreadDescription from Win10
628
   BOTAN_UNUSED(thread, name);
629
   #else
630
   // TODO other possible oses ?
631
   // macOs does not seem to allow to name threads other than the current one.
632
   BOTAN_UNUSED(thread, name);
633
   #endif
634
}
1,522✔
635
#endif
636

637
#if defined(BOTAN_TARGET_OS_HAS_POSIX1) && !defined(BOTAN_TARGET_OS_IS_EMSCRIPTEN)
638

639
namespace {
640

641
// NOLINTNEXTLINE(*-avoid-non-const-global-variables)
642
::sigjmp_buf g_sigill_jmp_buf;
643

644
void botan_sigill_handler(int /*unused*/) {
1✔
645
   siglongjmp(g_sigill_jmp_buf, /*non-zero return value*/ 1);
1✔
646
}
647

648
}  // namespace
649

650
#endif
651

652
int OS::run_cpu_instruction_probe(const std::function<int()>& probe_fn) {
2✔
653
   volatile int probe_result = -3;
2✔
654

655
#if defined(BOTAN_TARGET_OS_HAS_POSIX1) && !defined(BOTAN_TARGET_OS_IS_EMSCRIPTEN)
656
   struct sigaction old_sigaction;
2✔
657
   struct sigaction sigaction;
2✔
658

659
   sigaction.sa_handler = botan_sigill_handler;
2✔
660
   sigemptyset(&sigaction.sa_mask);
2✔
661
   sigaction.sa_flags = 0;
2✔
662

663
   int rc = ::sigaction(SIGILL, &sigaction, &old_sigaction);
2✔
664

665
   if(rc != 0) {
2✔
666
      throw System_Error("run_cpu_instruction_probe sigaction failed", errno);
×
667
   }
668

669
   rc = sigsetjmp(g_sigill_jmp_buf, /*save sigs*/ 1);
3✔
670

671
   if(rc == 0) {
3✔
672
      // first call to sigsetjmp
673
      probe_result = probe_fn();
3✔
674
   } else if(rc == 1) {
1✔
675
      // non-local return from siglongjmp in signal handler: return error
676
      probe_result = -1;
1✔
677
   }
678

679
   // Restore old SIGILL handler, if any
680
   rc = ::sigaction(SIGILL, &old_sigaction, nullptr);
2✔
681
   if(rc != 0) {
2✔
682
      throw System_Error("run_cpu_instruction_probe sigaction restore failed", errno);
×
683
   }
684

685
#else
686
   BOTAN_UNUSED(probe_fn);
687
#endif
688

689
   return probe_result;
2✔
690
}
691

692
std::unique_ptr<OS::Echo_Suppression> OS::suppress_echo_on_terminal() {
×
693
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
694
   class POSIX_Echo_Suppression : public Echo_Suppression {
×
695
      public:
696
         POSIX_Echo_Suppression() {
×
697
            m_stdin_fd = fileno(stdin);
×
698
            if(::tcgetattr(m_stdin_fd, &m_old_termios) != 0) {
×
699
               throw System_Error("Getting terminal status failed", errno);
×
700
            }
701

702
            struct termios noecho_flags = m_old_termios;
×
703
            noecho_flags.c_lflag &= ~ECHO;
×
704
            noecho_flags.c_lflag |= ECHONL;
×
705

706
            if(::tcsetattr(m_stdin_fd, TCSANOW, &noecho_flags) != 0) {
×
707
               throw System_Error("Clearing terminal echo bit failed", errno);
×
708
            }
709
         }
×
710

711
         void reenable_echo() override {
×
712
            if(m_stdin_fd > 0) {
×
713
               if(::tcsetattr(m_stdin_fd, TCSANOW, &m_old_termios) != 0) {
×
714
                  throw System_Error("Restoring terminal echo bit failed", errno);
×
715
               }
716
               m_stdin_fd = -1;
×
717
            }
718
         }
×
719

720
         ~POSIX_Echo_Suppression() override {
×
721
            try {
×
722
               reenable_echo();
×
723
            } catch(...) {}
×
724
         }
×
725

726
         POSIX_Echo_Suppression(const POSIX_Echo_Suppression& other) = delete;
727
         POSIX_Echo_Suppression(POSIX_Echo_Suppression&& other) = delete;
728
         POSIX_Echo_Suppression& operator=(const POSIX_Echo_Suppression& other) = delete;
729
         POSIX_Echo_Suppression& operator=(POSIX_Echo_Suppression&& other) = delete;
730

731
      private:
732
         int m_stdin_fd;
733
         struct termios m_old_termios;
734
   };
735

736
   return std::make_unique<POSIX_Echo_Suppression>();
×
737

738
#elif defined(BOTAN_TARGET_OS_HAS_WIN32)
739

740
   class Win32_Echo_Suppression : public Echo_Suppression {
741
      public:
742
         Win32_Echo_Suppression() {
743
            m_input_handle = ::GetStdHandle(STD_INPUT_HANDLE);
744
            if(::GetConsoleMode(m_input_handle, &m_console_state) == 0)
745
               throw System_Error("Getting console mode failed", ::GetLastError());
746

747
            DWORD new_mode = ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT;
748
            if(::SetConsoleMode(m_input_handle, new_mode) == 0)
749
               throw System_Error("Setting console mode failed", ::GetLastError());
750
         }
751

752
         void reenable_echo() override {
753
            if(m_input_handle != INVALID_HANDLE_VALUE) {
754
               if(::SetConsoleMode(m_input_handle, m_console_state) == 0)
755
                  throw System_Error("Setting console mode failed", ::GetLastError());
756
               m_input_handle = INVALID_HANDLE_VALUE;
757
            }
758
         }
759

760
         ~Win32_Echo_Suppression() override {
761
            try {
762
               reenable_echo();
763
            } catch(...) {}
764
         }
765

766
         Win32_Echo_Suppression(const Win32_Echo_Suppression& other) = delete;
767
         Win32_Echo_Suppression(Win32_Echo_Suppression&& other) = delete;
768
         Win32_Echo_Suppression& operator=(const Win32_Echo_Suppression& other) = delete;
769
         Win32_Echo_Suppression& operator=(Win32_Echo_Suppression&& other) = delete;
770

771
      private:
772
         HANDLE m_input_handle;
773
         DWORD m_console_state;
774
   };
775

776
   return std::make_unique<Win32_Echo_Suppression>();
777

778
#else
779

780
   // Not supported on this platform, return null
781
   return nullptr;
782
#endif
783
}
784

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