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