]> git.sesse.net Git - stockfish/blob - src/misc.cpp
Avoid "using namespace std"
[stockfish] / src / misc.cpp
1 /*
2   Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3   Copyright (C) 2004-2023 The Stockfish developers (see AUTHORS file)
4
5   Stockfish is free software: you can redistribute it and/or modify
6   it under the terms of the GNU General Public License as published by
7   the Free Software Foundation, either version 3 of the License, or
8   (at your option) any later version.
9
10   Stockfish is distributed in the hope that it will be useful,
11   but WITHOUT ANY WARRANTY; without even the implied warranty of
12   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   GNU General Public License for more details.
14
15   You should have received a copy of the GNU General Public License
16   along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 #include "misc.h"
20
21 #ifdef _WIN32
22 #if _WIN32_WINNT < 0x0601
23 #undef  _WIN32_WINNT
24 #define _WIN32_WINNT 0x0601 // Force to include needed API prototypes
25 #endif
26
27 #ifndef NOMINMAX
28 #define NOMINMAX
29 #endif
30
31 #include <windows.h>
32 // The needed Windows API for processor groups could be missed from old Windows
33 // versions, so instead of calling them directly (forcing the linker to resolve
34 // the calls at compile time), try to load them at runtime. To do this we need
35 // first to define the corresponding function pointers.
36 extern "C" {
37 using fun1_t = bool(*)(LOGICAL_PROCESSOR_RELATIONSHIP,
38                        PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX, PDWORD);
39 using fun2_t = bool(*)(USHORT, PGROUP_AFFINITY);
40 using fun3_t = bool(*)(HANDLE, CONST GROUP_AFFINITY*, PGROUP_AFFINITY);
41 using fun4_t = bool(*)(USHORT, PGROUP_AFFINITY, USHORT, PUSHORT);
42 using fun5_t = WORD(*)();
43 using fun6_t = bool(*)(HANDLE, DWORD, PHANDLE);
44 using fun7_t = bool(*)(LPCSTR, LPCSTR, PLUID);
45 using fun8_t = bool(*)(HANDLE, BOOL, PTOKEN_PRIVILEGES, DWORD, PTOKEN_PRIVILEGES, PDWORD);
46 }
47 #endif
48
49 #include <atomic>
50 #include <cmath>
51 #include <cstdlib>
52 #include <fstream>
53 #include <iomanip>
54 #include <iostream>
55 #include <mutex>
56 #include <sstream>
57 #include <string_view>
58
59 #include "types.h"
60
61 #if defined(__linux__) && !defined(__ANDROID__)
62 #include <sys/mman.h>
63 #endif
64
65 #if defined(__APPLE__) || defined(__ANDROID__) || defined(__OpenBSD__) || (defined(__GLIBCXX__) && !defined(_GLIBCXX_HAVE_ALIGNED_ALLOC) && !defined(_WIN32)) || defined(__e2k__)
66 #define POSIXALIGNEDALLOC
67 #include <stdlib.h>
68 #endif
69
70 namespace Stockfish {
71
72 namespace {
73
74 /// Version number or dev.
75 constexpr std::string_view version = "dev";
76
77 /// Our fancy logging facility. The trick here is to replace cin.rdbuf() and
78 /// cout.rdbuf() with two Tie objects that tie cin and cout to a file stream. We
79 /// can toggle the logging of std::cout and std:cin at runtime whilst preserving
80 /// usual I/O functionality, all without changing a single line of code!
81 /// Idea from http://groups.google.com/group/comp.lang.c++/msg/1d941c0f26ea0d81
82
83 struct Tie: public std::streambuf { // MSVC requires split streambuf for cin and cout
84
85   Tie(std::streambuf* b, std::streambuf* l) : buf(b), logBuf(l) {}
86
87   int sync() override { return logBuf->pubsync(), buf->pubsync(); }
88   int overflow(int c) override { return log(buf->sputc((char)c), "<< "); }
89   int underflow() override { return buf->sgetc(); }
90   int uflow() override { return log(buf->sbumpc(), ">> "); }
91
92   std::streambuf *buf, *logBuf;
93
94   int log(int c, const char* prefix) {
95
96     static int last = '\n'; // Single log file
97
98     if (last == '\n')
99         logBuf->sputn(prefix, 3);
100
101     return last = logBuf->sputc((char)c);
102   }
103 };
104
105 class Logger {
106
107   Logger() : in(std::cin.rdbuf(), file.rdbuf()), out(std::cout.rdbuf(), file.rdbuf()) {}
108  ~Logger() { start(""); }
109
110   std::ofstream file;
111   Tie in, out;
112
113 public:
114   static void start(const std::string& fname) {
115
116     static Logger l;
117
118     if (l.file.is_open())
119     {
120         std::cout.rdbuf(l.out.buf);
121         std::cin.rdbuf(l.in.buf);
122         l.file.close();
123     }
124
125     if (!fname.empty())
126     {
127         l.file.open(fname, std::ifstream::out);
128
129         if (!l.file.is_open())
130         {
131             std::cerr << "Unable to open debug log file " << fname << std::endl;
132             exit(EXIT_FAILURE);
133         }
134
135         std::cin.rdbuf(&l.in);
136         std::cout.rdbuf(&l.out);
137     }
138   }
139 };
140
141 } // namespace
142
143
144 /// engine_info() returns the full name of the current Stockfish version.
145 /// For local dev compiles we try to append the commit sha and commit date
146 /// from git if that fails only the local compilation date is set and "nogit" is specified:
147 /// Stockfish dev-YYYYMMDD-SHA
148 /// or
149 /// Stockfish dev-YYYYMMDD-nogit
150 ///
151 /// For releases (non dev builds) we only include the version number:
152 /// Stockfish version
153
154 std::string engine_info(bool to_uci) {
155   std::stringstream ss;
156   ss << "Stockfish " << version << std::setfill('0');
157
158   if constexpr (version == "dev")
159   {
160       ss << "-";
161       #ifdef GIT_DATE
162       ss << stringify(GIT_DATE);
163       #else
164       constexpr std::string_view months("Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec");
165       std::string month, day, year;
166       std::stringstream date(__DATE__); // From compiler, format is "Sep 21 2008"
167
168       date >> month >> day >> year;
169       ss << year << std::setw(2) << std::setfill('0') << (1 + months.find(month) / 4) << std::setw(2) << std::setfill('0') << day;
170       #endif
171
172       ss << "-";
173
174       #ifdef GIT_SHA
175       ss << stringify(GIT_SHA);
176       #else
177       ss << "nogit";
178       #endif
179   }
180
181   ss << (to_uci  ? "\nid author ": " by ")
182      << "the Stockfish developers (see AUTHORS file)";
183
184   return ss.str();
185 }
186
187
188 /// compiler_info() returns a string trying to describe the compiler we use
189
190 std::string compiler_info() {
191
192   #define make_version_string(major, minor, patch) stringify(major) "." stringify(minor) "." stringify(patch)
193
194 /// Predefined macros hell:
195 ///
196 /// __GNUC__           Compiler is gcc, Clang or Intel on Linux
197 /// __INTEL_COMPILER   Compiler is Intel
198 /// _MSC_VER           Compiler is MSVC or Intel on Windows
199 /// _WIN32             Building on Windows (any)
200 /// _WIN64             Building on Windows 64 bit
201
202   std::string compiler = "\nCompiled by ";
203
204   #ifdef __clang__
205      compiler += "clang++ ";
206      compiler += make_version_string(__clang_major__, __clang_minor__, __clang_patchlevel__);
207   #elif __INTEL_COMPILER
208      compiler += "Intel compiler ";
209      compiler += "(version ";
210      compiler += stringify(__INTEL_COMPILER) " update " stringify(__INTEL_COMPILER_UPDATE);
211      compiler += ")";
212   #elif _MSC_VER
213      compiler += "MSVC ";
214      compiler += "(version ";
215      compiler += stringify(_MSC_FULL_VER) "." stringify(_MSC_BUILD);
216      compiler += ")";
217   #elif defined(__e2k__) && defined(__LCC__)
218     #define dot_ver2(n) \
219       compiler += (char)'.'; \
220       compiler += (char)('0' + (n) / 10); \
221       compiler += (char)('0' + (n) % 10);
222
223      compiler += "MCST LCC ";
224      compiler += "(version ";
225      compiler += std::to_string(__LCC__ / 100);
226      dot_ver2(__LCC__ % 100)
227      dot_ver2(__LCC_MINOR__)
228      compiler += ")";
229   #elif __GNUC__
230      compiler += "g++ (GNUC) ";
231      compiler += make_version_string(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__);
232   #else
233      compiler += "Unknown compiler ";
234      compiler += "(unknown version)";
235   #endif
236
237   #if defined(__APPLE__)
238      compiler += " on Apple";
239   #elif defined(__CYGWIN__)
240      compiler += " on Cygwin";
241   #elif defined(__MINGW64__)
242      compiler += " on MinGW64";
243   #elif defined(__MINGW32__)
244      compiler += " on MinGW32";
245   #elif defined(__ANDROID__)
246      compiler += " on Android";
247   #elif defined(__linux__)
248      compiler += " on Linux";
249   #elif defined(_WIN64)
250      compiler += " on Microsoft Windows 64-bit";
251   #elif defined(_WIN32)
252      compiler += " on Microsoft Windows 32-bit";
253   #else
254      compiler += " on unknown system";
255   #endif
256
257   compiler += "\nCompilation settings include: ";
258   compiler += (Is64Bit ? " 64bit" : " 32bit");
259   #if defined(USE_VNNI)
260     compiler += " VNNI";
261   #endif
262   #if defined(USE_AVX512)
263     compiler += " AVX512";
264   #endif
265   compiler += (HasPext ? " BMI2" : "");
266   #if defined(USE_AVX2)
267     compiler += " AVX2";
268   #endif
269   #if defined(USE_SSE41)
270     compiler += " SSE41";
271   #endif
272   #if defined(USE_SSSE3)
273     compiler += " SSSE3";
274   #endif
275   #if defined(USE_SSE2)
276     compiler += " SSE2";
277   #endif
278   compiler += (HasPopCnt ? " POPCNT" : "");
279   #if defined(USE_MMX)
280     compiler += " MMX";
281   #endif
282   #if defined(USE_NEON_DOTPROD)
283     compiler += " NEON_DOTPROD";
284   #elif defined(USE_NEON)
285     compiler += " NEON";
286   #endif
287
288   #if !defined(NDEBUG)
289     compiler += " DEBUG";
290   #endif
291
292   compiler += "\n__VERSION__ macro expands to: ";
293   #ifdef __VERSION__
294      compiler += __VERSION__;
295   #else
296      compiler += "(undefined macro)";
297   #endif
298   compiler += "\n";
299
300   return compiler;
301 }
302
303
304 /// Debug functions used mainly to collect run-time statistics
305 constexpr int MaxDebugSlots = 32;
306
307 namespace {
308
309 template<size_t N>
310 struct DebugInfo {
311     std::atomic<int64_t> data[N] = { 0 };
312
313     constexpr inline std::atomic<int64_t>& operator[](int index) { return data[index]; }
314 };
315
316 DebugInfo<2> hit[MaxDebugSlots];
317 DebugInfo<2> mean[MaxDebugSlots];
318 DebugInfo<3> stdev[MaxDebugSlots];
319 DebugInfo<6> correl[MaxDebugSlots];
320
321 }  // namespace
322
323 void dbg_hit_on(bool cond, int slot) {
324
325     ++hit[slot][0];
326     if (cond)
327         ++hit[slot][1];
328 }
329
330 void dbg_mean_of(int64_t value, int slot) {
331
332     ++mean[slot][0];
333     mean[slot][1] += value;
334 }
335
336 void dbg_stdev_of(int64_t value, int slot) {
337
338     ++stdev[slot][0];
339     stdev[slot][1] += value;
340     stdev[slot][2] += value * value;
341 }
342
343 void dbg_correl_of(int64_t value1, int64_t value2, int slot) {
344
345     ++correl[slot][0];
346     correl[slot][1] += value1;
347     correl[slot][2] += value1 * value1;
348     correl[slot][3] += value2;
349     correl[slot][4] += value2 * value2;
350     correl[slot][5] += value1 * value2;
351 }
352
353 void dbg_print() {
354
355     int64_t n;
356     auto E   = [&n](int64_t x) { return double(x) / n; };
357     auto sqr = [](double x) { return x * x; };
358
359     for (int i = 0; i < MaxDebugSlots; ++i)
360         if ((n = hit[i][0]))
361             std::cerr << "Hit #" << i
362                       << ": Total " << n << " Hits " << hit[i][1]
363                       << " Hit Rate (%) " << 100.0 * E(hit[i][1])
364                       << std::endl;
365
366     for (int i = 0; i < MaxDebugSlots; ++i)
367         if ((n = mean[i][0]))
368         {
369             std::cerr << "Mean #" << i
370                       << ": Total " << n << " Mean " << E(mean[i][1])
371                       << std::endl;
372         }
373
374     for (int i = 0; i < MaxDebugSlots; ++i)
375         if ((n = stdev[i][0]))
376         {
377             double r = sqrt(E(stdev[i][2]) - sqr(E(stdev[i][1])));
378             std::cerr << "Stdev #" << i
379                       << ": Total " << n << " Stdev " << r
380                       << std::endl;
381         }
382
383     for (int i = 0; i < MaxDebugSlots; ++i)
384         if ((n = correl[i][0]))
385         {
386             double r = (E(correl[i][5]) - E(correl[i][1]) * E(correl[i][3]))
387                        / (  sqrt(E(correl[i][2]) - sqr(E(correl[i][1])))
388                           * sqrt(E(correl[i][4]) - sqr(E(correl[i][3]))));
389             std::cerr << "Correl. #" << i
390                       << ": Total " << n << " Coefficient " << r
391                       << std::endl;
392         }
393 }
394
395
396 /// Used to serialize access to std::cout to avoid multiple threads writing at
397 /// the same time.
398
399 std::ostream& operator<<(std::ostream& os, SyncCout sc) {
400
401   static std::mutex m;
402
403   if (sc == IO_LOCK)
404       m.lock();
405
406   if (sc == IO_UNLOCK)
407       m.unlock();
408
409   return os;
410 }
411
412
413 /// Trampoline helper to avoid moving Logger to misc.h
414 void start_logger(const std::string& fname) { Logger::start(fname); }
415
416
417 /// prefetch() preloads the given address in L1/L2 cache. This is a non-blocking
418 /// function that doesn't stall the CPU waiting for data to be loaded from memory,
419 /// which can be quite slow.
420 #ifdef NO_PREFETCH
421
422 void prefetch(void*) {}
423
424 #else
425
426 void prefetch(void* addr) {
427
428 #  if defined(__INTEL_COMPILER)
429    // This hack prevents prefetches from being optimized away by
430    // Intel compiler. Both MSVC and gcc seem not be affected by this.
431    __asm__ ("");
432 #  endif
433
434 #  if defined(__INTEL_COMPILER) || defined(_MSC_VER)
435   _mm_prefetch((char*)addr, _MM_HINT_T0);
436 #  else
437   __builtin_prefetch(addr);
438 #  endif
439 }
440
441 #endif
442
443
444 /// std_aligned_alloc() is our wrapper for systems where the c++17 implementation
445 /// does not guarantee the availability of aligned_alloc(). Memory allocated with
446 /// std_aligned_alloc() must be freed with std_aligned_free().
447
448 void* std_aligned_alloc(size_t alignment, size_t size) {
449
450 #if defined(POSIXALIGNEDALLOC)
451   void *mem;
452   return posix_memalign(&mem, alignment, size) ? nullptr : mem;
453 #elif defined(_WIN32) && !defined(_M_ARM) && !defined(_M_ARM64)
454   return _mm_malloc(size, alignment);
455 #elif defined(_WIN32)
456   return _aligned_malloc(size, alignment);
457 #else
458   return std::aligned_alloc(alignment, size);
459 #endif
460 }
461
462 void std_aligned_free(void* ptr) {
463
464 #if defined(POSIXALIGNEDALLOC)
465   free(ptr);
466 #elif defined(_WIN32) && !defined(_M_ARM) && !defined(_M_ARM64)
467   _mm_free(ptr);
468 #elif defined(_WIN32)
469   _aligned_free(ptr);
470 #else
471   free(ptr);
472 #endif
473 }
474
475 /// aligned_large_pages_alloc() will return suitably aligned memory, if possible using large pages.
476
477 #if defined(_WIN32)
478
479 static void* aligned_large_pages_alloc_windows([[maybe_unused]] size_t allocSize) {
480
481   #if !defined(_WIN64)
482     return nullptr;
483   #else
484
485   HANDLE hProcessToken { };
486   LUID luid { };
487   void* mem = nullptr;
488
489   const size_t largePageSize = GetLargePageMinimum();
490   if (!largePageSize)
491       return nullptr;
492
493   // Dynamically link OpenProcessToken, LookupPrivilegeValue and AdjustTokenPrivileges
494
495   HMODULE hAdvapi32 = GetModuleHandle(TEXT("advapi32.dll"));
496
497   if (!hAdvapi32)
498       hAdvapi32 = LoadLibrary(TEXT("advapi32.dll"));
499
500   auto fun6 = (fun6_t)(void(*)())GetProcAddress(hAdvapi32, "OpenProcessToken");
501   if (!fun6)
502       return nullptr;
503   auto fun7 = (fun7_t)(void(*)())GetProcAddress(hAdvapi32, "LookupPrivilegeValueA");
504   if (!fun7)
505       return nullptr;
506   auto fun8 = (fun8_t)(void(*)())GetProcAddress(hAdvapi32, "AdjustTokenPrivileges");
507   if (!fun8)
508       return nullptr;
509
510   // We need SeLockMemoryPrivilege, so try to enable it for the process
511   if (!fun6( // OpenProcessToken()
512       GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hProcessToken))
513           return nullptr;
514
515   if (fun7( // LookupPrivilegeValue(nullptr, SE_LOCK_MEMORY_NAME, &luid)
516       nullptr, "SeLockMemoryPrivilege", &luid))
517   {
518       TOKEN_PRIVILEGES tp { };
519       TOKEN_PRIVILEGES prevTp { };
520       DWORD prevTpLen = 0;
521
522       tp.PrivilegeCount = 1;
523       tp.Privileges[0].Luid = luid;
524       tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
525
526       // Try to enable SeLockMemoryPrivilege. Note that even if AdjustTokenPrivileges() succeeds,
527       // we still need to query GetLastError() to ensure that the privileges were actually obtained.
528       if (fun8( // AdjustTokenPrivileges()
529               hProcessToken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), &prevTp, &prevTpLen) &&
530           GetLastError() == ERROR_SUCCESS)
531       {
532           // Round up size to full pages and allocate
533           allocSize = (allocSize + largePageSize - 1) & ~size_t(largePageSize - 1);
534           mem = VirtualAlloc(
535               nullptr, allocSize, MEM_RESERVE | MEM_COMMIT | MEM_LARGE_PAGES, PAGE_READWRITE);
536
537           // Privilege no longer needed, restore previous state
538           fun8( // AdjustTokenPrivileges ()
539               hProcessToken, FALSE, &prevTp, 0, nullptr, nullptr);
540       }
541   }
542
543   CloseHandle(hProcessToken);
544
545   return mem;
546
547   #endif
548 }
549
550 void* aligned_large_pages_alloc(size_t allocSize) {
551
552   // Try to allocate large pages
553   void* mem = aligned_large_pages_alloc_windows(allocSize);
554
555   // Fall back to regular, page aligned, allocation if necessary
556   if (!mem)
557       mem = VirtualAlloc(nullptr, allocSize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
558
559   return mem;
560 }
561
562 #else
563
564 void* aligned_large_pages_alloc(size_t allocSize) {
565
566 #if defined(__linux__)
567   constexpr size_t alignment = 2 * 1024 * 1024; // assumed 2MB page size
568 #else
569   constexpr size_t alignment = 4096; // assumed small page size
570 #endif
571
572   // round up to multiples of alignment
573   size_t size = ((allocSize + alignment - 1) / alignment) * alignment;
574   void *mem = std_aligned_alloc(alignment, size);
575 #if defined(MADV_HUGEPAGE)
576   madvise(mem, size, MADV_HUGEPAGE);
577 #endif
578   return mem;
579 }
580
581 #endif
582
583
584 /// aligned_large_pages_free() will free the previously allocated ttmem
585
586 #if defined(_WIN32)
587
588 void aligned_large_pages_free(void* mem) {
589
590   if (mem && !VirtualFree(mem, 0, MEM_RELEASE))
591   {
592       DWORD err = GetLastError();
593       std::cerr << "Failed to free large page memory. Error code: 0x"
594                 << std::hex << err
595                 << std::dec << std::endl;
596       exit(EXIT_FAILURE);
597   }
598 }
599
600 #else
601
602 void aligned_large_pages_free(void *mem) {
603   std_aligned_free(mem);
604 }
605
606 #endif
607
608
609 namespace WinProcGroup {
610
611 #ifndef _WIN32
612
613 void bindThisThread(size_t) {}
614
615 #else
616
617 /// best_node() retrieves logical processor information using Windows specific
618 /// API and returns the best node id for the thread with index idx. Original
619 /// code from Texel by Peter Ă–sterlund.
620
621 static int best_node(size_t idx) {
622
623   int threads = 0;
624   int nodes = 0;
625   int cores = 0;
626   DWORD returnLength = 0;
627   DWORD byteOffset = 0;
628
629   // Early exit if the needed API is not available at runtime
630   HMODULE k32 = GetModuleHandle(TEXT("Kernel32.dll"));
631   auto fun1 = (fun1_t)(void(*)())GetProcAddress(k32, "GetLogicalProcessorInformationEx");
632   if (!fun1)
633       return -1;
634
635   // First call to GetLogicalProcessorInformationEx() to get returnLength.
636   // We expect the call to fail due to null buffer.
637   if (fun1(RelationAll, nullptr, &returnLength))
638       return -1;
639
640   // Once we know returnLength, allocate the buffer
641   SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *buffer, *ptr;
642   ptr = buffer = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*)malloc(returnLength);
643
644   // Second call to GetLogicalProcessorInformationEx(), now we expect to succeed
645   if (!fun1(RelationAll, buffer, &returnLength))
646   {
647       free(buffer);
648       return -1;
649   }
650
651   while (byteOffset < returnLength)
652   {
653       if (ptr->Relationship == RelationNumaNode)
654           nodes++;
655
656       else if (ptr->Relationship == RelationProcessorCore)
657       {
658           cores++;
659           threads += (ptr->Processor.Flags == LTP_PC_SMT) ? 2 : 1;
660       }
661
662       assert(ptr->Size);
663       byteOffset += ptr->Size;
664       ptr = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*)(((char*)ptr) + ptr->Size);
665   }
666
667   free(buffer);
668
669   std::vector<int> groups;
670
671   // Run as many threads as possible on the same node until core limit is
672   // reached, then move on filling the next node.
673   for (int n = 0; n < nodes; n++)
674       for (int i = 0; i < cores / nodes; i++)
675           groups.push_back(n);
676
677   // In case a core has more than one logical processor (we assume 2) and we
678   // have still threads to allocate, then spread them evenly across available
679   // nodes.
680   for (int t = 0; t < threads - cores; t++)
681       groups.push_back(t % nodes);
682
683   // If we still have more threads than the total number of logical processors
684   // then return -1 and let the OS to decide what to do.
685   return idx < groups.size() ? groups[idx] : -1;
686 }
687
688
689 /// bindThisThread() set the group affinity of the current thread
690
691 void bindThisThread(size_t idx) {
692
693   // Use only local variables to be thread-safe
694   int node = best_node(idx);
695
696   if (node == -1)
697       return;
698
699   // Early exit if the needed API are not available at runtime
700   HMODULE k32 = GetModuleHandle(TEXT("Kernel32.dll"));
701   auto fun2 = (fun2_t)(void(*)())GetProcAddress(k32, "GetNumaNodeProcessorMaskEx");
702   auto fun3 = (fun3_t)(void(*)())GetProcAddress(k32, "SetThreadGroupAffinity");
703   auto fun4 = (fun4_t)(void(*)())GetProcAddress(k32, "GetNumaNodeProcessorMask2");
704   auto fun5 = (fun5_t)(void(*)())GetProcAddress(k32, "GetMaximumProcessorGroupCount");
705
706   if (!fun2 || !fun3)
707       return;
708
709   if (!fun4 || !fun5)
710   {
711       GROUP_AFFINITY affinity;
712       if (fun2(node, &affinity))                                                 // GetNumaNodeProcessorMaskEx
713           fun3(GetCurrentThread(), &affinity, nullptr);                          // SetThreadGroupAffinity
714   }
715   else
716   {
717       // If a numa node has more than one processor group, we assume they are
718       // sized equal and we spread threads evenly across the groups.
719       USHORT elements, returnedElements;
720       elements = fun5();                                                         // GetMaximumProcessorGroupCount
721       GROUP_AFFINITY *affinity = (GROUP_AFFINITY*)malloc(elements * sizeof(GROUP_AFFINITY));
722       if (fun4(node, affinity, elements, &returnedElements))                     // GetNumaNodeProcessorMask2
723           fun3(GetCurrentThread(), &affinity[idx % returnedElements], nullptr);  // SetThreadGroupAffinity
724       free(affinity);
725   }
726 }
727
728 #endif
729
730 } // namespace WinProcGroup
731
732 #ifdef _WIN32
733 #include <direct.h>
734 #define GETCWD _getcwd
735 #else
736 #include <unistd.h>
737 #define GETCWD getcwd
738 #endif
739
740 namespace CommandLine {
741
742 std::string argv0;            // path+name of the executable binary, as given by argv[0]
743 std::string binaryDirectory;  // path of the executable directory
744 std::string workingDirectory; // path of the working directory
745
746 void init([[maybe_unused]] int argc, char* argv[]) {
747     std::string pathSeparator;
748
749     // extract the path+name of the executable binary
750     argv0 = argv[0];
751
752 #ifdef _WIN32
753     pathSeparator = "\\";
754   #ifdef _MSC_VER
755     // Under windows argv[0] may not have the extension. Also _get_pgmptr() had
756     // issues in some windows 10 versions, so check returned values carefully.
757     char* pgmptr = nullptr;
758     if (!_get_pgmptr(&pgmptr) && pgmptr != nullptr && *pgmptr)
759         argv0 = pgmptr;
760   #endif
761 #else
762     pathSeparator = "/";
763 #endif
764
765     // extract the working directory
766     workingDirectory = "";
767     char buff[40000];
768     char* cwd = GETCWD(buff, 40000);
769     if (cwd)
770         workingDirectory = cwd;
771
772     // extract the binary directory path from argv0
773     binaryDirectory = argv0;
774     size_t pos = binaryDirectory.find_last_of("\\/");
775     if (pos == std::string::npos)
776         binaryDirectory = "." + pathSeparator;
777     else
778         binaryDirectory.resize(pos + 1);
779
780     // pattern replacement: "./" at the start of path is replaced by the working directory
781     if (binaryDirectory.find("." + pathSeparator) == 0)
782         binaryDirectory.replace(0, 1, workingDirectory);
783 }
784
785
786 } // namespace CommandLine
787
788 } // namespace Stockfish