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