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

randombit / botan / 6449924519

08 Oct 2023 08:54PM UTC coverage: 91.682% (-0.008%) from 91.69%
6449924519

push

github

web-flow
Merge pull request #3738 from randombit/thread_debug_windows

OS::set_thread_name attempt to port to windows >= 10

79968 of 87223 relevant lines covered (91.68%)

8585350.14 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
   #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_ANDROID)
62
   #include <elf.h>
63
extern "C" char** environ;
64
#endif
65

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

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

76
#if defined(BOTAN_TARGET_IS_FREEBSD) || defined(BOTAN_TARGET_IS_OPENBSD)
77
   #include <pthread_np.h>
78
#endif
79

80
namespace Botan {
81

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

87
#elif defined(BOTAN_TARGET_OS_HAS_EXPLICIT_BZERO)
88
   ::explicit_bzero(ptr, n);
228,126,770✔
89

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

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

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

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

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

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

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

132
   char** p = environ;
133

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

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

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

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

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

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

173
uint64_t OS::get_cpu_cycle_counter() {
3,521,148✔
174
   uint64_t rtc = 0;
3,521,148✔
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_CPU_IS_X86_FAMILY)
184

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

191
   #elif defined(BOTAN_TARGET_ARCH_IS_PPC64)
192

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

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

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

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

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

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

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

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

225
#endif
226

227
   return rtc;
3,521,148✔
228
}
229

230
size_t OS::get_cpu_available() {
758✔
231
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
232

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

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

247
#endif
248

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

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

259
   return 1;
260
}
261

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

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

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

278
#if defined(BOTAN_TARGET_OS_HAS_CLOCK_GETTIME)
279

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

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

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

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

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

324
size_t OS::system_page_size() {
4,433,635✔
325
   const size_t default_page_size = 4096;
4,433,635✔
326

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

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

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

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

366
      ::getrlimit(RLIMIT_MEMLOCK, &limits);
8,609✔
367

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

374
      return std::min<size_t>(limits.rlim_cur, mlock_requested * 1024);
17,218✔
375
   }
376

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

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

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

402
   return 0;
403
}
404

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

408
   if(running_in_privileged_state()) {
22,243✔
409
      return false;
410
   }
411

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

428
   return false;
429
}
22,243✔
430

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

441
   return def;
442
}
8,609✔
443

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

446
namespace {
447

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

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

467
}  // namespace
468

469
#endif
470

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

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

477
   result.reserve(count);
8,609✔
478

479
   const size_t page_size = OS::system_page_size();
8,609✔
480

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

485
   for(size_t i = 0; i != count; ++i) {
1,110,561✔
486
      void* ptr = nullptr;
1,101,952✔
487

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

490
      int mmap_flags = MAP_PRIVATE;
1,101,952✔
491

492
      #if defined(MAP_ANONYMOUS)
493
      mmap_flags |= MAP_ANONYMOUS;
1,101,952✔
494
      #elif defined(MAP_ANON)
495
      mmap_flags |= MAP_ANON;
496
      #endif
497

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

504
      int mmap_prot = PROT_READ | PROT_WRITE;
1,101,952✔
505

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

510
      ptr = ::mmap(nullptr,
1,101,952✔
511
                   3 * page_size,
512
                   mmap_prot,
513
                   mmap_flags,
514
                   /*fd=*/locked_fd,
515
                   /*offset=*/0);
516

517
      if(ptr == MAP_FAILED) {
1,101,952✔
518
         continue;
×
519
      }
520

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

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

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

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

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

544
      std::memset(ptr, 0, 3 * page_size);  // zero data page and both guard pages
1,101,952✔
545

546
      // Attempts to name the data page
547
      page_named(ptr, 3 * page_size);
1,101,952✔
548
      // Make guard page preceeding the data page
549
      page_prohibit_access(static_cast<uint8_t*>(ptr));
1,101,952✔
550
      // Make guard page following the data page
551
      page_prohibit_access(static_cast<uint8_t*>(ptr) + 2 * page_size);
1,101,952✔
552

553
      result.push_back(static_cast<uint8_t*>(ptr) + page_size);
1,101,952✔
554
   }
555
#else
556
   BOTAN_UNUSED(count);
557
#endif
558

559
   return result;
8,609✔
560
}
×
561

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

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

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

593
   for(size_t i = 0; i != pages.size(); ++i) {
1,110,561✔
594
      void* ptr = pages[i];
1,101,952✔
595

596
      secure_scrub_memory(ptr, page_size);
1,101,952✔
597

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

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

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

622
#if defined(BOTAN_TARGET_OS_HAS_THREADS)
623
void OS::set_thread_name(std::thread& thread, const std::string& name) {
1,526✔
624
   #if defined(BOTAN_TARGET_OS_IS_LINUX) || defined(BOTAN_TARGET_OS_IS_FREEBSD)
625
   static_cast<void>(pthread_setname_np(thread.native_handle(), name.c_str()));
1,526✔
626
   #elif defined(BOTAN_TARGET_OS_IS_OPENBSD)
627
   static_cast<void>(pthread_set_name_np(thread.native_handle(), name.c_str()));
628
   #elif defined(BOTAN_TARGET_OS_IS_NETBSD)
629
   static_cast<void>(pthread_set_name_np(thread.native_handle(), "%s", const_cast<char*>(name.c_str())));
630
   #elif defined(BOTAN_TARGET_OS_HAS_WIN32) && defined(BOTAN_BUILD_COMPILER_IS_MSVC)
631
   typedef HRESULT(WINAPI * std_proc)(HANDLE, PCWSTR);
632
   HMODULE kern = GetModuleHandleA("KernelBase.dll");
633
   std_proc set_thread_name = reinterpret_cast<std_proc>(GetProcAddress(kern, "SetThreadDescription"));
634
   if(set_thread_name) {
635
      std::wstring w;
636
      auto sz = MultiByteToWideChar(CP_UTF8, 0, name.data(), -1, nullptr, 0);
637
      if(sz > 0) {
638
         w.resize(sz);
639
         if(MultiByteToWideChar(CP_UTF8, 0, name.data(), -1, &w[0], sz) > 0) {
640
            (void)set_thread_name(thread.native_handle(), w.c_str());
641
         }
642
      }
643
   }
644
   #else
645
   // TODO other possible oses ?
646
   // macOs does not seem to allow to name threads other than the current one.
647
   BOTAN_UNUSED(thread, name);
648
   #endif
649
}
1,526✔
650
#endif
651

652
#if defined(BOTAN_TARGET_OS_HAS_POSIX1) && !defined(BOTAN_TARGET_OS_IS_EMSCRIPTEN)
653

654
namespace {
655

656
// NOLINTNEXTLINE(*-avoid-non-const-global-variables)
657
::sigjmp_buf g_sigill_jmp_buf;
658

659
void botan_sigill_handler(int /*unused*/) {
1✔
660
   siglongjmp(g_sigill_jmp_buf, /*non-zero return value*/ 1);
1✔
661
}
662

663
}  // namespace
664

665
#endif
666

667
int OS::run_cpu_instruction_probe(const std::function<int()>& probe_fn) {
2✔
668
   volatile int probe_result = -3;
2✔
669

670
#if defined(BOTAN_TARGET_OS_HAS_POSIX1) && !defined(BOTAN_TARGET_OS_IS_EMSCRIPTEN)
671
   struct sigaction old_sigaction;
2✔
672
   struct sigaction sigaction;
2✔
673

674
   sigaction.sa_handler = botan_sigill_handler;
2✔
675
   sigemptyset(&sigaction.sa_mask);
2✔
676
   sigaction.sa_flags = 0;
2✔
677

678
   int rc = ::sigaction(SIGILL, &sigaction, &old_sigaction);
2✔
679

680
   if(rc != 0) {
2✔
681
      throw System_Error("run_cpu_instruction_probe sigaction failed", errno);
×
682
   }
683

684
   rc = sigsetjmp(g_sigill_jmp_buf, /*save sigs*/ 1);
3✔
685

686
   if(rc == 0) {
3✔
687
      // first call to sigsetjmp
688
      probe_result = probe_fn();
3✔
689
   } else if(rc == 1) {
1✔
690
      // non-local return from siglongjmp in signal handler: return error
691
      probe_result = -1;
1✔
692
   }
693

694
   // Restore old SIGILL handler, if any
695
   rc = ::sigaction(SIGILL, &old_sigaction, nullptr);
2✔
696
   if(rc != 0) {
2✔
697
      throw System_Error("run_cpu_instruction_probe sigaction restore failed", errno);
×
698
   }
699

700
#else
701
   BOTAN_UNUSED(probe_fn);
702
#endif
703

704
   return probe_result;
2✔
705
}
706

707
std::unique_ptr<OS::Echo_Suppression> OS::suppress_echo_on_terminal() {
×
708
#if defined(BOTAN_TARGET_OS_HAS_POSIX1)
709
   class POSIX_Echo_Suppression : public Echo_Suppression {
×
710
      public:
711
         POSIX_Echo_Suppression() {
×
712
            m_stdin_fd = fileno(stdin);
×
713
            if(::tcgetattr(m_stdin_fd, &m_old_termios) != 0) {
×
714
               throw System_Error("Getting terminal status failed", errno);
×
715
            }
716

717
            struct termios noecho_flags = m_old_termios;
×
718
            noecho_flags.c_lflag &= ~ECHO;
×
719
            noecho_flags.c_lflag |= ECHONL;
×
720

721
            if(::tcsetattr(m_stdin_fd, TCSANOW, &noecho_flags) != 0) {
×
722
               throw System_Error("Clearing terminal echo bit failed", errno);
×
723
            }
724
         }
×
725

726
         void reenable_echo() override {
×
727
            if(m_stdin_fd > 0) {
×
728
               if(::tcsetattr(m_stdin_fd, TCSANOW, &m_old_termios) != 0) {
×
729
                  throw System_Error("Restoring terminal echo bit failed", errno);
×
730
               }
731
               m_stdin_fd = -1;
×
732
            }
733
         }
×
734

735
         ~POSIX_Echo_Suppression() override {
×
736
            try {
×
737
               reenable_echo();
×
738
            } catch(...) {}
×
739
         }
×
740

741
         POSIX_Echo_Suppression(const POSIX_Echo_Suppression& other) = delete;
742
         POSIX_Echo_Suppression(POSIX_Echo_Suppression&& other) = delete;
743
         POSIX_Echo_Suppression& operator=(const POSIX_Echo_Suppression& other) = delete;
744
         POSIX_Echo_Suppression& operator=(POSIX_Echo_Suppression&& other) = delete;
745

746
      private:
747
         int m_stdin_fd;
748
         struct termios m_old_termios;
749
   };
750

751
   return std::make_unique<POSIX_Echo_Suppression>();
×
752

753
#elif defined(BOTAN_TARGET_OS_HAS_WIN32)
754

755
   class Win32_Echo_Suppression : public Echo_Suppression {
756
      public:
757
         Win32_Echo_Suppression() {
758
            m_input_handle = ::GetStdHandle(STD_INPUT_HANDLE);
759
            if(::GetConsoleMode(m_input_handle, &m_console_state) == 0)
760
               throw System_Error("Getting console mode failed", ::GetLastError());
761

762
            DWORD new_mode = ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT;
763
            if(::SetConsoleMode(m_input_handle, new_mode) == 0)
764
               throw System_Error("Setting console mode failed", ::GetLastError());
765
         }
766

767
         void reenable_echo() override {
768
            if(m_input_handle != INVALID_HANDLE_VALUE) {
769
               if(::SetConsoleMode(m_input_handle, m_console_state) == 0)
770
                  throw System_Error("Setting console mode failed", ::GetLastError());
771
               m_input_handle = INVALID_HANDLE_VALUE;
772
            }
773
         }
774

775
         ~Win32_Echo_Suppression() override {
776
            try {
777
               reenable_echo();
778
            } catch(...) {}
779
         }
780

781
         Win32_Echo_Suppression(const Win32_Echo_Suppression& other) = delete;
782
         Win32_Echo_Suppression(Win32_Echo_Suppression&& other) = delete;
783
         Win32_Echo_Suppression& operator=(const Win32_Echo_Suppression& other) = delete;
784
         Win32_Echo_Suppression& operator=(Win32_Echo_Suppression&& other) = delete;
785

786
      private:
787
         HANDLE m_input_handle;
788
         DWORD m_console_state;
789
   };
790

791
   return std::make_unique<Win32_Echo_Suppression>();
792

793
#else
794

795
   // Not supported on this platform, return null
796
   return nullptr;
797
#endif
798
}
799

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